1 //===- Tokens.cpp - collect tokens from preprocessing ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 #include "clang/Tooling/Syntax/Tokens.h" 9 10 #include "clang/Basic/Diagnostic.h" 11 #include "clang/Basic/IdentifierTable.h" 12 #include "clang/Basic/LLVM.h" 13 #include "clang/Basic/LangOptions.h" 14 #include "clang/Basic/SourceLocation.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/TokenKinds.h" 17 #include "clang/Lex/PPCallbacks.h" 18 #include "clang/Lex/Preprocessor.h" 19 #include "clang/Lex/Token.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/FormatVariadic.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <algorithm> 29 #include <cassert> 30 #include <iterator> 31 #include <string> 32 #include <utility> 33 #include <vector> 34 35 using namespace clang; 36 using namespace clang::syntax; 37 38 namespace { 39 // Finds the smallest consecutive subsuquence of Toks that covers R. 40 llvm::ArrayRef<syntax::Token> 41 getTokensCovering(llvm::ArrayRef<syntax::Token> Toks, SourceRange R, 42 const SourceManager &SM) { 43 if (R.isInvalid()) 44 return {}; 45 const syntax::Token *Begin = 46 llvm::partition_point(Toks, [&](const syntax::Token &T) { 47 return SM.isBeforeInTranslationUnit(T.location(), R.getBegin()); 48 }); 49 const syntax::Token *End = 50 llvm::partition_point(Toks, [&](const syntax::Token &T) { 51 return !SM.isBeforeInTranslationUnit(R.getEnd(), T.location()); 52 }); 53 if (Begin > End) 54 return {}; 55 return {Begin, End}; 56 } 57 58 // Finds the smallest expansion range that contains expanded tokens First and 59 // Last, e.g.: 60 // #define ID(x) x 61 // ID(ID(ID(a1) a2)) 62 // ~~ -> a1 63 // ~~ -> a2 64 // ~~~~~~~~~ -> a1 a2 65 SourceRange findCommonRangeForMacroArgs(const syntax::Token &First, 66 const syntax::Token &Last, 67 const SourceManager &SM) { 68 SourceRange Res; 69 auto FirstLoc = First.location(), LastLoc = Last.location(); 70 // Keep traversing up the spelling chain as longs as tokens are part of the 71 // same expansion. 72 while (!FirstLoc.isFileID() && !LastLoc.isFileID()) { 73 auto ExpInfoFirst = SM.getSLocEntry(SM.getFileID(FirstLoc)).getExpansion(); 74 auto ExpInfoLast = SM.getSLocEntry(SM.getFileID(LastLoc)).getExpansion(); 75 // Stop if expansions have diverged. 76 if (ExpInfoFirst.getExpansionLocStart() != 77 ExpInfoLast.getExpansionLocStart()) 78 break; 79 // Do not continue into macro bodies. 80 if (!ExpInfoFirst.isMacroArgExpansion() || 81 !ExpInfoLast.isMacroArgExpansion()) 82 break; 83 FirstLoc = SM.getImmediateSpellingLoc(FirstLoc); 84 LastLoc = SM.getImmediateSpellingLoc(LastLoc); 85 // Update the result afterwards, as we want the tokens that triggered the 86 // expansion. 87 Res = {FirstLoc, LastLoc}; 88 } 89 // Normally mapping back to expansion location here only changes FileID, as 90 // we've already found some tokens expanded from the same macro argument, and 91 // they should map to a consecutive subset of spelled tokens. Unfortunately 92 // SourceManager::isBeforeInTranslationUnit discriminates sourcelocations 93 // based on their FileID in addition to offsets. So even though we are 94 // referring to same tokens, SourceManager might tell us that one is before 95 // the other if they've got different FileIDs. 96 return SM.getExpansionRange(CharSourceRange(Res, true)).getAsRange(); 97 } 98 99 } // namespace 100 101 syntax::Token::Token(SourceLocation Location, unsigned Length, 102 tok::TokenKind Kind) 103 : Location(Location), Length(Length), Kind(Kind) { 104 assert(Location.isValid()); 105 } 106 107 syntax::Token::Token(const clang::Token &T) 108 : Token(T.getLocation(), T.getLength(), T.getKind()) { 109 assert(!T.isAnnotation()); 110 } 111 112 llvm::StringRef syntax::Token::text(const SourceManager &SM) const { 113 bool Invalid = false; 114 const char *Start = SM.getCharacterData(location(), &Invalid); 115 assert(!Invalid); 116 return llvm::StringRef(Start, length()); 117 } 118 119 FileRange syntax::Token::range(const SourceManager &SM) const { 120 assert(location().isFileID() && "must be a spelled token"); 121 FileID File; 122 unsigned StartOffset; 123 std::tie(File, StartOffset) = SM.getDecomposedLoc(location()); 124 return FileRange(File, StartOffset, StartOffset + length()); 125 } 126 127 FileRange syntax::Token::range(const SourceManager &SM, 128 const syntax::Token &First, 129 const syntax::Token &Last) { 130 auto F = First.range(SM); 131 auto L = Last.range(SM); 132 assert(F.file() == L.file() && "tokens from different files"); 133 assert((F == L || F.endOffset() <= L.beginOffset()) && 134 "wrong order of tokens"); 135 return FileRange(F.file(), F.beginOffset(), L.endOffset()); 136 } 137 138 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) { 139 return OS << T.str(); 140 } 141 142 FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset) 143 : File(File), Begin(BeginOffset), End(EndOffset) { 144 assert(File.isValid()); 145 assert(BeginOffset <= EndOffset); 146 } 147 148 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 149 unsigned Length) { 150 assert(BeginLoc.isValid()); 151 assert(BeginLoc.isFileID()); 152 153 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 154 End = Begin + Length; 155 } 156 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 157 SourceLocation EndLoc) { 158 assert(BeginLoc.isValid()); 159 assert(BeginLoc.isFileID()); 160 assert(EndLoc.isValid()); 161 assert(EndLoc.isFileID()); 162 assert(SM.getFileID(BeginLoc) == SM.getFileID(EndLoc)); 163 assert(SM.getFileOffset(BeginLoc) <= SM.getFileOffset(EndLoc)); 164 165 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 166 End = SM.getFileOffset(EndLoc); 167 } 168 169 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, 170 const FileRange &R) { 171 return OS << llvm::formatv("FileRange(file = {0}, offsets = {1}-{2})", 172 R.file().getHashValue(), R.beginOffset(), 173 R.endOffset()); 174 } 175 176 llvm::StringRef FileRange::text(const SourceManager &SM) const { 177 bool Invalid = false; 178 StringRef Text = SM.getBufferData(File, &Invalid); 179 if (Invalid) 180 return ""; 181 assert(Begin <= Text.size()); 182 assert(End <= Text.size()); 183 return Text.substr(Begin, length()); 184 } 185 186 llvm::ArrayRef<syntax::Token> TokenBuffer::expandedTokens(SourceRange R) const { 187 return getTokensCovering(expandedTokens(), R, *SourceMgr); 188 } 189 190 CharSourceRange FileRange::toCharRange(const SourceManager &SM) const { 191 return CharSourceRange( 192 SourceRange(SM.getComposedLoc(File, Begin), SM.getComposedLoc(File, End)), 193 /*IsTokenRange=*/false); 194 } 195 196 std::pair<const syntax::Token *, const TokenBuffer::Mapping *> 197 TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const { 198 assert(Expanded); 199 assert(ExpandedTokens.data() <= Expanded && 200 Expanded < ExpandedTokens.data() + ExpandedTokens.size()); 201 202 auto FileIt = Files.find( 203 SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location()))); 204 assert(FileIt != Files.end() && "no file for an expanded token"); 205 206 const MarkedFile &File = FileIt->second; 207 208 unsigned ExpandedIndex = Expanded - ExpandedTokens.data(); 209 // Find the first mapping that produced tokens after \p Expanded. 210 auto It = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 211 return M.BeginExpanded <= ExpandedIndex; 212 }); 213 // Our token could only be produced by the previous mapping. 214 if (It == File.Mappings.begin()) { 215 // No previous mapping, no need to modify offsets. 216 return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded], nullptr}; 217 } 218 --It; // 'It' now points to last mapping that started before our token. 219 220 // Check if the token is part of the mapping. 221 if (ExpandedIndex < It->EndExpanded) 222 return {&File.SpelledTokens[It->BeginSpelled], /*Mapping*/ &*It}; 223 224 // Not part of the mapping, use the index from previous mapping to compute the 225 // corresponding spelled token. 226 return { 227 &File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)], 228 /*Mapping*/ nullptr}; 229 } 230 231 llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const { 232 auto It = Files.find(FID); 233 assert(It != Files.end()); 234 return It->second.SpelledTokens; 235 } 236 237 const syntax::Token *TokenBuffer::spelledTokenAt(SourceLocation Loc) const { 238 assert(Loc.isFileID()); 239 const auto *Tok = llvm::partition_point( 240 spelledTokens(SourceMgr->getFileID(Loc)), 241 [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 242 if (!Tok || Tok->location() != Loc) 243 return nullptr; 244 return Tok; 245 } 246 247 std::string TokenBuffer::Mapping::str() const { 248 return std::string( 249 llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})", 250 BeginSpelled, EndSpelled, BeginExpanded, EndExpanded)); 251 } 252 253 llvm::Optional<llvm::ArrayRef<syntax::Token>> 254 TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const { 255 // Mapping an empty range is ambiguous in case of empty mappings at either end 256 // of the range, bail out in that case. 257 if (Expanded.empty()) 258 return llvm::None; 259 260 const syntax::Token *BeginSpelled; 261 const Mapping *BeginMapping; 262 std::tie(BeginSpelled, BeginMapping) = 263 spelledForExpandedToken(&Expanded.front()); 264 265 const syntax::Token *LastSpelled; 266 const Mapping *LastMapping; 267 std::tie(LastSpelled, LastMapping) = 268 spelledForExpandedToken(&Expanded.back()); 269 270 FileID FID = SourceMgr->getFileID(BeginSpelled->location()); 271 // FIXME: Handle multi-file changes by trying to map onto a common root. 272 if (FID != SourceMgr->getFileID(LastSpelled->location())) 273 return llvm::None; 274 275 const MarkedFile &File = Files.find(FID)->second; 276 277 // If both tokens are coming from a macro argument expansion, try and map to 278 // smallest part of the macro argument. BeginMapping && LastMapping check is 279 // only for performance, they are a prerequisite for Expanded.front() and 280 // Expanded.back() being part of a macro arg expansion. 281 if (BeginMapping && LastMapping && 282 SourceMgr->isMacroArgExpansion(Expanded.front().location()) && 283 SourceMgr->isMacroArgExpansion(Expanded.back().location())) { 284 auto CommonRange = findCommonRangeForMacroArgs(Expanded.front(), 285 Expanded.back(), *SourceMgr); 286 // It might be the case that tokens are arguments of different macro calls, 287 // in that case we should continue with the logic below instead of returning 288 // an empty range. 289 if (CommonRange.isValid()) 290 return getTokensCovering(File.SpelledTokens, CommonRange, *SourceMgr); 291 } 292 293 // Do not allow changes that doesn't cover full expansion. 294 unsigned BeginExpanded = Expanded.begin() - ExpandedTokens.data(); 295 unsigned EndExpanded = Expanded.end() - ExpandedTokens.data(); 296 if (BeginMapping && BeginExpanded != BeginMapping->BeginExpanded) 297 return llvm::None; 298 if (LastMapping && LastMapping->EndExpanded != EndExpanded) 299 return llvm::None; 300 // All is good, return the result. 301 return llvm::makeArrayRef( 302 BeginMapping ? File.SpelledTokens.data() + BeginMapping->BeginSpelled 303 : BeginSpelled, 304 LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled 305 : LastSpelled + 1); 306 } 307 308 llvm::Optional<TokenBuffer::Expansion> 309 TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const { 310 assert(Spelled); 311 assert(Spelled->location().isFileID() && "not a spelled token"); 312 auto FileIt = Files.find(SourceMgr->getFileID(Spelled->location())); 313 assert(FileIt != Files.end() && "file not tracked by token buffer"); 314 315 auto &File = FileIt->second; 316 assert(File.SpelledTokens.data() <= Spelled && 317 Spelled < (File.SpelledTokens.data() + File.SpelledTokens.size())); 318 319 unsigned SpelledIndex = Spelled - File.SpelledTokens.data(); 320 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 321 return M.BeginSpelled < SpelledIndex; 322 }); 323 if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex) 324 return llvm::None; 325 326 Expansion E; 327 E.Spelled = llvm::makeArrayRef(File.SpelledTokens.data() + M->BeginSpelled, 328 File.SpelledTokens.data() + M->EndSpelled); 329 E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M->BeginExpanded, 330 ExpandedTokens.data() + M->EndExpanded); 331 return E; 332 } 333 llvm::ArrayRef<syntax::Token> 334 syntax::spelledTokensTouching(SourceLocation Loc, 335 llvm::ArrayRef<syntax::Token> Tokens) { 336 assert(Loc.isFileID()); 337 338 auto *Right = llvm::partition_point( 339 Tokens, [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 340 bool AcceptRight = Right != Tokens.end() && Right->location() <= Loc; 341 bool AcceptLeft = 342 Right != Tokens.begin() && (Right - 1)->endLocation() >= Loc; 343 return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0), 344 Right + (AcceptRight ? 1 : 0)); 345 } 346 347 llvm::ArrayRef<syntax::Token> 348 syntax::spelledTokensTouching(SourceLocation Loc, 349 const syntax::TokenBuffer &Tokens) { 350 return spelledTokensTouching( 351 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 352 } 353 354 const syntax::Token * 355 syntax::spelledIdentifierTouching(SourceLocation Loc, 356 llvm::ArrayRef<syntax::Token> Tokens) { 357 for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) { 358 if (Tok.kind() == tok::identifier) 359 return &Tok; 360 } 361 return nullptr; 362 } 363 364 const syntax::Token * 365 syntax::spelledIdentifierTouching(SourceLocation Loc, 366 const syntax::TokenBuffer &Tokens) { 367 return spelledIdentifierTouching( 368 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 369 } 370 371 std::vector<const syntax::Token *> 372 TokenBuffer::macroExpansions(FileID FID) const { 373 auto FileIt = Files.find(FID); 374 assert(FileIt != Files.end() && "file not tracked by token buffer"); 375 auto &File = FileIt->second; 376 std::vector<const syntax::Token *> Expansions; 377 auto &Spelled = File.SpelledTokens; 378 for (auto Mapping : File.Mappings) { 379 const syntax::Token *Token = &Spelled[Mapping.BeginSpelled]; 380 if (Token->kind() == tok::TokenKind::identifier) 381 Expansions.push_back(Token); 382 } 383 return Expansions; 384 } 385 386 std::vector<syntax::Token> syntax::tokenize(const FileRange &FR, 387 const SourceManager &SM, 388 const LangOptions &LO) { 389 std::vector<syntax::Token> Tokens; 390 IdentifierTable Identifiers(LO); 391 auto AddToken = [&](clang::Token T) { 392 // Fill the proper token kind for keywords, etc. 393 if (T.getKind() == tok::raw_identifier && !T.needsCleaning() && 394 !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases. 395 clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier()); 396 T.setIdentifierInfo(&II); 397 T.setKind(II.getTokenID()); 398 } 399 Tokens.push_back(syntax::Token(T)); 400 }; 401 402 auto SrcBuffer = SM.getBufferData(FR.file()); 403 Lexer L(SM.getLocForStartOfFile(FR.file()), LO, SrcBuffer.data(), 404 SrcBuffer.data() + FR.beginOffset(), 405 // We can't make BufEnd point to FR.endOffset, as Lexer requires a 406 // null terminated buffer. 407 SrcBuffer.data() + SrcBuffer.size()); 408 409 clang::Token T; 410 while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < FR.endOffset()) 411 AddToken(T); 412 // LexFromRawLexer returns true when it parses the last token of the file, add 413 // it iff it starts within the range we are interested in. 414 if (SM.getFileOffset(T.getLocation()) < FR.endOffset()) 415 AddToken(T); 416 return Tokens; 417 } 418 419 std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM, 420 const LangOptions &LO) { 421 return tokenize(syntax::FileRange(FID, 0, SM.getFileIDSize(FID)), SM, LO); 422 } 423 424 /// Records information reqired to construct mappings for the token buffer that 425 /// we are collecting. 426 class TokenCollector::CollectPPExpansions : public PPCallbacks { 427 public: 428 CollectPPExpansions(TokenCollector &C) : Collector(&C) {} 429 430 /// Disabled instance will stop reporting anything to TokenCollector. 431 /// This ensures that uses of the preprocessor after TokenCollector::consume() 432 /// is called do not access the (possibly invalid) collector instance. 433 void disable() { Collector = nullptr; } 434 435 void MacroExpands(const clang::Token &MacroNameTok, const MacroDefinition &MD, 436 SourceRange Range, const MacroArgs *Args) override { 437 if (!Collector) 438 return; 439 const auto &SM = Collector->PP.getSourceManager(); 440 // Only record top-level expansions that directly produce expanded tokens. 441 // This excludes those where: 442 // - the macro use is inside a macro body, 443 // - the macro appears in an argument to another macro. 444 // However macro expansion isn't really a tree, it's token rewrite rules, 445 // so there are other cases, e.g. 446 // #define B(X) X 447 // #define A 1 + B 448 // A(2) 449 // Both A and B produce expanded tokens, though the macro name 'B' comes 450 // from an expansion. The best we can do is merge the mappings for both. 451 452 // The *last* token of any top-level macro expansion must be in a file. 453 // (In the example above, see the closing paren of the expansion of B). 454 if (!Range.getEnd().isFileID()) 455 return; 456 // If there's a current expansion that encloses this one, this one can't be 457 // top-level. 458 if (LastExpansionEnd.isValid() && 459 !SM.isBeforeInTranslationUnit(LastExpansionEnd, Range.getEnd())) 460 return; 461 462 // If the macro invocation (B) starts in a macro (A) but ends in a file, 463 // we'll create a merged mapping for A + B by overwriting the endpoint for 464 // A's startpoint. 465 if (!Range.getBegin().isFileID()) { 466 Range.setBegin(SM.getExpansionLoc(Range.getBegin())); 467 assert(Collector->Expansions.count(Range.getBegin().getRawEncoding()) && 468 "Overlapping macros should have same expansion location"); 469 } 470 471 Collector->Expansions[Range.getBegin().getRawEncoding()] = Range.getEnd(); 472 LastExpansionEnd = Range.getEnd(); 473 } 474 // FIXME: handle directives like #pragma, #include, etc. 475 private: 476 TokenCollector *Collector; 477 /// Used to detect recursive macro expansions. 478 SourceLocation LastExpansionEnd; 479 }; 480 481 /// Fills in the TokenBuffer by tracing the run of a preprocessor. The 482 /// implementation tracks the tokens, macro expansions and directives coming 483 /// from the preprocessor and: 484 /// - for each token, figures out if it is a part of an expanded token stream, 485 /// spelled token stream or both. Stores the tokens appropriately. 486 /// - records mappings from the spelled to expanded token ranges, e.g. for macro 487 /// expansions. 488 /// FIXME: also properly record: 489 /// - #include directives, 490 /// - #pragma, #line and other PP directives, 491 /// - skipped pp regions, 492 /// - ... 493 494 TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) { 495 // Collect the expanded token stream during preprocessing. 496 PP.setTokenWatcher([this](const clang::Token &T) { 497 if (T.isAnnotation()) 498 return; 499 DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs() 500 << "Token: " 501 << syntax::Token(T).dumpForTests( 502 this->PP.getSourceManager()) 503 << "\n" 504 505 ); 506 Expanded.push_back(syntax::Token(T)); 507 }); 508 // And locations of macro calls, to properly recover boundaries of those in 509 // case of empty expansions. 510 auto CB = std::make_unique<CollectPPExpansions>(*this); 511 this->Collector = CB.get(); 512 PP.addPPCallbacks(std::move(CB)); 513 } 514 515 /// Builds mappings and spelled tokens in the TokenBuffer based on the expanded 516 /// token stream. 517 class TokenCollector::Builder { 518 public: 519 Builder(std::vector<syntax::Token> Expanded, PPExpansions CollectedExpansions, 520 const SourceManager &SM, const LangOptions &LangOpts) 521 : Result(SM), CollectedExpansions(std::move(CollectedExpansions)), SM(SM), 522 LangOpts(LangOpts) { 523 Result.ExpandedTokens = std::move(Expanded); 524 } 525 526 TokenBuffer build() && { 527 assert(!Result.ExpandedTokens.empty()); 528 assert(Result.ExpandedTokens.back().kind() == tok::eof); 529 530 // Tokenize every file that contributed tokens to the expanded stream. 531 buildSpelledTokens(); 532 533 // The expanded token stream consists of runs of tokens that came from 534 // the same source (a macro expansion, part of a file etc). 535 // Between these runs are the logical positions of spelled tokens that 536 // didn't expand to anything. 537 while (NextExpanded < Result.ExpandedTokens.size() - 1 /* eof */) { 538 // Create empty mappings for spelled tokens that expanded to nothing here. 539 // May advance NextSpelled, but NextExpanded is unchanged. 540 discard(); 541 // Create mapping for a contiguous run of expanded tokens. 542 // Advances NextExpanded past the run, and NextSpelled accordingly. 543 unsigned OldPosition = NextExpanded; 544 advance(); 545 if (NextExpanded == OldPosition) 546 diagnoseAdvanceFailure(); 547 } 548 // If any tokens remain in any of the files, they didn't expand to anything. 549 // Create empty mappings up until the end of the file. 550 for (const auto &File : Result.Files) 551 discard(File.first); 552 553 return std::move(Result); 554 } 555 556 private: 557 // Consume a sequence of spelled tokens that didn't expand to anything. 558 // In the simplest case, skips spelled tokens until finding one that produced 559 // the NextExpanded token, and creates an empty mapping for them. 560 // If Drain is provided, skips remaining tokens from that file instead. 561 void discard(llvm::Optional<FileID> Drain = llvm::None) { 562 SourceLocation Target = 563 Drain ? SM.getLocForEndOfFile(*Drain) 564 : SM.getExpansionLoc( 565 Result.ExpandedTokens[NextExpanded].location()); 566 FileID File = SM.getFileID(Target); 567 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 568 auto &NextSpelled = this->NextSpelled[File]; 569 570 TokenBuffer::Mapping Mapping; 571 Mapping.BeginSpelled = NextSpelled; 572 // When dropping trailing tokens from a file, the empty mapping should 573 // be positioned within the file's expanded-token range (at the end). 574 Mapping.BeginExpanded = Mapping.EndExpanded = 575 Drain ? Result.Files[*Drain].EndExpanded : NextExpanded; 576 // We may want to split into several adjacent empty mappings. 577 // FlushMapping() emits the current mapping and starts a new one. 578 auto FlushMapping = [&, this] { 579 Mapping.EndSpelled = NextSpelled; 580 if (Mapping.BeginSpelled != Mapping.EndSpelled) 581 Result.Files[File].Mappings.push_back(Mapping); 582 Mapping.BeginSpelled = NextSpelled; 583 }; 584 585 while (NextSpelled < SpelledTokens.size() && 586 SpelledTokens[NextSpelled].location() < Target) { 587 // If we know mapping bounds at [NextSpelled, KnownEnd] (macro expansion) 588 // then we want to partition our (empty) mapping. 589 // [Start, NextSpelled) [NextSpelled, KnownEnd] (KnownEnd, Target) 590 SourceLocation KnownEnd = CollectedExpansions.lookup( 591 SpelledTokens[NextSpelled].location().getRawEncoding()); 592 if (KnownEnd.isValid()) { 593 FlushMapping(); // Emits [Start, NextSpelled) 594 while (NextSpelled < SpelledTokens.size() && 595 SpelledTokens[NextSpelled].location() <= KnownEnd) 596 ++NextSpelled; 597 FlushMapping(); // Emits [NextSpelled, KnownEnd] 598 // Now the loop contitues and will emit (KnownEnd, Target). 599 } else { 600 ++NextSpelled; 601 } 602 } 603 FlushMapping(); 604 } 605 606 // Consumes the NextExpanded token and others that are part of the same run. 607 // Increases NextExpanded and NextSpelled by at least one, and adds a mapping 608 // (unless this is a run of file tokens, which we represent with no mapping). 609 void advance() { 610 const syntax::Token &Tok = Result.ExpandedTokens[NextExpanded]; 611 SourceLocation Expansion = SM.getExpansionLoc(Tok.location()); 612 FileID File = SM.getFileID(Expansion); 613 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 614 auto &NextSpelled = this->NextSpelled[File]; 615 616 if (Tok.location().isFileID()) { 617 // A run of file tokens continues while the expanded/spelled tokens match. 618 while (NextSpelled < SpelledTokens.size() && 619 NextExpanded < Result.ExpandedTokens.size() && 620 SpelledTokens[NextSpelled].location() == 621 Result.ExpandedTokens[NextExpanded].location()) { 622 ++NextSpelled; 623 ++NextExpanded; 624 } 625 // We need no mapping for file tokens copied to the expanded stream. 626 } else { 627 // We found a new macro expansion. We should have its spelling bounds. 628 auto End = CollectedExpansions.lookup(Expansion.getRawEncoding()); 629 assert(End.isValid() && "Macro expansion wasn't captured?"); 630 631 // Mapping starts here... 632 TokenBuffer::Mapping Mapping; 633 Mapping.BeginExpanded = NextExpanded; 634 Mapping.BeginSpelled = NextSpelled; 635 // ... consumes spelled tokens within bounds we captured ... 636 while (NextSpelled < SpelledTokens.size() && 637 SpelledTokens[NextSpelled].location() <= End) 638 ++NextSpelled; 639 // ... consumes expanded tokens rooted at the same expansion ... 640 while (NextExpanded < Result.ExpandedTokens.size() && 641 SM.getExpansionLoc( 642 Result.ExpandedTokens[NextExpanded].location()) == Expansion) 643 ++NextExpanded; 644 // ... and ends here. 645 Mapping.EndExpanded = NextExpanded; 646 Mapping.EndSpelled = NextSpelled; 647 Result.Files[File].Mappings.push_back(Mapping); 648 } 649 } 650 651 // advance() is supposed to consume at least one token - if not, we crash. 652 void diagnoseAdvanceFailure() { 653 #ifndef NDEBUG 654 // Show the failed-to-map token in context. 655 for (unsigned I = (NextExpanded < 10) ? 0 : NextExpanded - 10; 656 I < NextExpanded + 5 && I < Result.ExpandedTokens.size(); ++I) { 657 const char *L = 658 (I == NextExpanded) ? "!! " : (I < NextExpanded) ? "ok " : " "; 659 llvm::errs() << L << Result.ExpandedTokens[I].dumpForTests(SM) << "\n"; 660 } 661 #endif 662 llvm_unreachable("Couldn't map expanded token to spelled tokens!"); 663 } 664 665 /// Initializes TokenBuffer::Files and fills spelled tokens and expanded 666 /// ranges for each of the files. 667 void buildSpelledTokens() { 668 for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) { 669 const auto &Tok = Result.ExpandedTokens[I]; 670 auto FID = SM.getFileID(SM.getExpansionLoc(Tok.location())); 671 auto It = Result.Files.try_emplace(FID); 672 TokenBuffer::MarkedFile &File = It.first->second; 673 674 // The eof token should not be considered part of the main-file's range. 675 File.EndExpanded = Tok.kind() == tok::eof ? I : I + 1; 676 677 if (!It.second) 678 continue; // we have seen this file before. 679 // This is the first time we see this file. 680 File.BeginExpanded = I; 681 File.SpelledTokens = tokenize(FID, SM, LangOpts); 682 } 683 } 684 685 TokenBuffer Result; 686 unsigned NextExpanded = 0; // cursor in ExpandedTokens 687 llvm::DenseMap<FileID, unsigned> NextSpelled; // cursor in SpelledTokens 688 PPExpansions CollectedExpansions; 689 const SourceManager &SM; 690 const LangOptions &LangOpts; 691 }; 692 693 TokenBuffer TokenCollector::consume() && { 694 PP.setTokenWatcher(nullptr); 695 Collector->disable(); 696 return Builder(std::move(Expanded), std::move(Expansions), 697 PP.getSourceManager(), PP.getLangOpts()) 698 .build(); 699 } 700 701 std::string syntax::Token::str() const { 702 return std::string(llvm::formatv("Token({0}, length = {1})", 703 tok::getTokenName(kind()), length())); 704 } 705 706 std::string syntax::Token::dumpForTests(const SourceManager &SM) const { 707 return std::string(llvm::formatv("Token(`{0}`, {1}, length = {2})", text(SM), 708 tok::getTokenName(kind()), length())); 709 } 710 711 std::string TokenBuffer::dumpForTests() const { 712 auto PrintToken = [this](const syntax::Token &T) -> std::string { 713 if (T.kind() == tok::eof) 714 return "<eof>"; 715 return std::string(T.text(*SourceMgr)); 716 }; 717 718 auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS, 719 llvm::ArrayRef<syntax::Token> Tokens) { 720 if (Tokens.empty()) { 721 OS << "<empty>"; 722 return; 723 } 724 OS << Tokens[0].text(*SourceMgr); 725 for (unsigned I = 1; I < Tokens.size(); ++I) { 726 if (Tokens[I].kind() == tok::eof) 727 continue; 728 OS << " " << PrintToken(Tokens[I]); 729 } 730 }; 731 732 std::string Dump; 733 llvm::raw_string_ostream OS(Dump); 734 735 OS << "expanded tokens:\n" 736 << " "; 737 // (!) we do not show '<eof>'. 738 DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back()); 739 OS << "\n"; 740 741 std::vector<FileID> Keys; 742 for (auto F : Files) 743 Keys.push_back(F.first); 744 llvm::sort(Keys); 745 746 for (FileID ID : Keys) { 747 const MarkedFile &File = Files.find(ID)->second; 748 auto *Entry = SourceMgr->getFileEntryForID(ID); 749 if (!Entry) 750 continue; // Skip builtin files. 751 OS << llvm::formatv("file '{0}'\n", Entry->getName()) 752 << " spelled tokens:\n" 753 << " "; 754 DumpTokens(OS, File.SpelledTokens); 755 OS << "\n"; 756 757 if (File.Mappings.empty()) { 758 OS << " no mappings.\n"; 759 continue; 760 } 761 OS << " mappings:\n"; 762 for (auto &M : File.Mappings) { 763 OS << llvm::formatv( 764 " ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n", 765 PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled, 766 M.EndSpelled == File.SpelledTokens.size() 767 ? "<eof>" 768 : PrintToken(File.SpelledTokens[M.EndSpelled]), 769 M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]), 770 M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]), 771 M.EndExpanded); 772 } 773 } 774 return OS.str(); 775 } 776