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 syntax::Token::Token(SourceLocation Location, unsigned Length, 39 tok::TokenKind Kind) 40 : Location(Location), Length(Length), Kind(Kind) { 41 assert(Location.isValid()); 42 } 43 44 syntax::Token::Token(const clang::Token &T) 45 : Token(T.getLocation(), T.getLength(), T.getKind()) { 46 assert(!T.isAnnotation()); 47 } 48 49 llvm::StringRef syntax::Token::text(const SourceManager &SM) const { 50 bool Invalid = false; 51 const char *Start = SM.getCharacterData(location(), &Invalid); 52 assert(!Invalid); 53 return llvm::StringRef(Start, length()); 54 } 55 56 FileRange syntax::Token::range(const SourceManager &SM) const { 57 assert(location().isFileID() && "must be a spelled token"); 58 FileID File; 59 unsigned StartOffset; 60 std::tie(File, StartOffset) = SM.getDecomposedLoc(location()); 61 return FileRange(File, StartOffset, StartOffset + length()); 62 } 63 64 FileRange syntax::Token::range(const SourceManager &SM, 65 const syntax::Token &First, 66 const syntax::Token &Last) { 67 auto F = First.range(SM); 68 auto L = Last.range(SM); 69 assert(F.file() == L.file() && "tokens from different files"); 70 assert((F == L || F.endOffset() <= L.beginOffset()) && 71 "wrong order of tokens"); 72 return FileRange(F.file(), F.beginOffset(), L.endOffset()); 73 } 74 75 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) { 76 return OS << T.str(); 77 } 78 79 FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset) 80 : File(File), Begin(BeginOffset), End(EndOffset) { 81 assert(File.isValid()); 82 assert(BeginOffset <= EndOffset); 83 } 84 85 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 86 unsigned Length) { 87 assert(BeginLoc.isValid()); 88 assert(BeginLoc.isFileID()); 89 90 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 91 End = Begin + Length; 92 } 93 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 94 SourceLocation EndLoc) { 95 assert(BeginLoc.isValid()); 96 assert(BeginLoc.isFileID()); 97 assert(EndLoc.isValid()); 98 assert(EndLoc.isFileID()); 99 assert(SM.getFileID(BeginLoc) == SM.getFileID(EndLoc)); 100 assert(SM.getFileOffset(BeginLoc) <= SM.getFileOffset(EndLoc)); 101 102 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 103 End = SM.getFileOffset(EndLoc); 104 } 105 106 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, 107 const FileRange &R) { 108 return OS << llvm::formatv("FileRange(file = {0}, offsets = {1}-{2})", 109 R.file().getHashValue(), R.beginOffset(), 110 R.endOffset()); 111 } 112 113 llvm::StringRef FileRange::text(const SourceManager &SM) const { 114 bool Invalid = false; 115 StringRef Text = SM.getBufferData(File, &Invalid); 116 if (Invalid) 117 return ""; 118 assert(Begin <= Text.size()); 119 assert(End <= Text.size()); 120 return Text.substr(Begin, length()); 121 } 122 123 llvm::ArrayRef<syntax::Token> TokenBuffer::expandedTokens(SourceRange R) const { 124 if (R.isInvalid()) 125 return {}; 126 const Token *Begin = 127 llvm::partition_point(expandedTokens(), [&](const syntax::Token &T) { 128 return SourceMgr->isBeforeInTranslationUnit(T.location(), R.getBegin()); 129 }); 130 const Token *End = 131 llvm::partition_point(expandedTokens(), [&](const syntax::Token &T) { 132 return !SourceMgr->isBeforeInTranslationUnit(R.getEnd(), T.location()); 133 }); 134 if (Begin > End) 135 return {}; 136 return {Begin, End}; 137 } 138 139 CharSourceRange FileRange::toCharRange(const SourceManager &SM) const { 140 return CharSourceRange( 141 SourceRange(SM.getComposedLoc(File, Begin), SM.getComposedLoc(File, End)), 142 /*IsTokenRange=*/false); 143 } 144 145 std::pair<const syntax::Token *, const TokenBuffer::Mapping *> 146 TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const { 147 assert(Expanded); 148 assert(ExpandedTokens.data() <= Expanded && 149 Expanded < ExpandedTokens.data() + ExpandedTokens.size()); 150 151 auto FileIt = Files.find( 152 SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location()))); 153 assert(FileIt != Files.end() && "no file for an expanded token"); 154 155 const MarkedFile &File = FileIt->second; 156 157 unsigned ExpandedIndex = Expanded - ExpandedTokens.data(); 158 // Find the first mapping that produced tokens after \p Expanded. 159 auto It = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 160 return M.BeginExpanded <= ExpandedIndex; 161 }); 162 // Our token could only be produced by the previous mapping. 163 if (It == File.Mappings.begin()) { 164 // No previous mapping, no need to modify offsets. 165 return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded], nullptr}; 166 } 167 --It; // 'It' now points to last mapping that started before our token. 168 169 // Check if the token is part of the mapping. 170 if (ExpandedIndex < It->EndExpanded) 171 return {&File.SpelledTokens[It->BeginSpelled], /*Mapping*/ &*It}; 172 173 // Not part of the mapping, use the index from previous mapping to compute the 174 // corresponding spelled token. 175 return { 176 &File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)], 177 /*Mapping*/ nullptr}; 178 } 179 180 llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const { 181 auto It = Files.find(FID); 182 assert(It != Files.end()); 183 return It->second.SpelledTokens; 184 } 185 186 const syntax::Token *TokenBuffer::spelledTokenAt(SourceLocation Loc) const { 187 assert(Loc.isFileID()); 188 const auto *Tok = llvm::partition_point( 189 spelledTokens(SourceMgr->getFileID(Loc)), 190 [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 191 if (!Tok || Tok->location() != Loc) 192 return nullptr; 193 return Tok; 194 } 195 196 std::string TokenBuffer::Mapping::str() const { 197 return std::string( 198 llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})", 199 BeginSpelled, EndSpelled, BeginExpanded, EndExpanded)); 200 } 201 202 llvm::Optional<llvm::ArrayRef<syntax::Token>> 203 TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const { 204 // Mapping an empty range is ambiguous in case of empty mappings at either end 205 // of the range, bail out in that case. 206 if (Expanded.empty()) 207 return llvm::None; 208 209 // FIXME: also allow changes uniquely mapping to macro arguments. 210 211 const syntax::Token *BeginSpelled; 212 const Mapping *BeginMapping; 213 std::tie(BeginSpelled, BeginMapping) = 214 spelledForExpandedToken(&Expanded.front()); 215 216 const syntax::Token *LastSpelled; 217 const Mapping *LastMapping; 218 std::tie(LastSpelled, LastMapping) = 219 spelledForExpandedToken(&Expanded.back()); 220 221 FileID FID = SourceMgr->getFileID(BeginSpelled->location()); 222 // FIXME: Handle multi-file changes by trying to map onto a common root. 223 if (FID != SourceMgr->getFileID(LastSpelled->location())) 224 return llvm::None; 225 226 const MarkedFile &File = Files.find(FID)->second; 227 228 // Do not allow changes that cross macro expansion boundaries. 229 unsigned BeginExpanded = Expanded.begin() - ExpandedTokens.data(); 230 unsigned EndExpanded = Expanded.end() - ExpandedTokens.data(); 231 if (BeginMapping && BeginMapping->BeginExpanded < BeginExpanded) 232 return llvm::None; 233 if (LastMapping && EndExpanded < LastMapping->EndExpanded) 234 return llvm::None; 235 // All is good, return the result. 236 return llvm::makeArrayRef( 237 BeginMapping ? File.SpelledTokens.data() + BeginMapping->BeginSpelled 238 : BeginSpelled, 239 LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled 240 : LastSpelled + 1); 241 } 242 243 llvm::Optional<TokenBuffer::Expansion> 244 TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const { 245 assert(Spelled); 246 assert(Spelled->location().isFileID() && "not a spelled token"); 247 auto FileIt = Files.find(SourceMgr->getFileID(Spelled->location())); 248 assert(FileIt != Files.end() && "file not tracked by token buffer"); 249 250 auto &File = FileIt->second; 251 assert(File.SpelledTokens.data() <= Spelled && 252 Spelled < (File.SpelledTokens.data() + File.SpelledTokens.size())); 253 254 unsigned SpelledIndex = Spelled - File.SpelledTokens.data(); 255 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 256 return M.BeginSpelled < SpelledIndex; 257 }); 258 if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex) 259 return llvm::None; 260 261 Expansion E; 262 E.Spelled = llvm::makeArrayRef(File.SpelledTokens.data() + M->BeginSpelled, 263 File.SpelledTokens.data() + M->EndSpelled); 264 E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M->BeginExpanded, 265 ExpandedTokens.data() + M->EndExpanded); 266 return E; 267 } 268 llvm::ArrayRef<syntax::Token> 269 syntax::spelledTokensTouching(SourceLocation Loc, 270 llvm::ArrayRef<syntax::Token> Tokens) { 271 assert(Loc.isFileID()); 272 273 auto *Right = llvm::partition_point( 274 Tokens, [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 275 bool AcceptRight = Right != Tokens.end() && Right->location() <= Loc; 276 bool AcceptLeft = 277 Right != Tokens.begin() && (Right - 1)->endLocation() >= Loc; 278 return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0), 279 Right + (AcceptRight ? 1 : 0)); 280 } 281 282 llvm::ArrayRef<syntax::Token> 283 syntax::spelledTokensTouching(SourceLocation Loc, 284 const syntax::TokenBuffer &Tokens) { 285 return spelledTokensTouching( 286 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 287 } 288 289 const syntax::Token * 290 syntax::spelledIdentifierTouching(SourceLocation Loc, 291 llvm::ArrayRef<syntax::Token> Tokens) { 292 for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) { 293 if (Tok.kind() == tok::identifier) 294 return &Tok; 295 } 296 return nullptr; 297 } 298 299 const syntax::Token * 300 syntax::spelledIdentifierTouching(SourceLocation Loc, 301 const syntax::TokenBuffer &Tokens) { 302 return spelledIdentifierTouching( 303 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 304 } 305 306 std::vector<const syntax::Token *> 307 TokenBuffer::macroExpansions(FileID FID) const { 308 auto FileIt = Files.find(FID); 309 assert(FileIt != Files.end() && "file not tracked by token buffer"); 310 auto &File = FileIt->second; 311 std::vector<const syntax::Token *> Expansions; 312 auto &Spelled = File.SpelledTokens; 313 for (auto Mapping : File.Mappings) { 314 const syntax::Token *Token = &Spelled[Mapping.BeginSpelled]; 315 if (Token->kind() == tok::TokenKind::identifier) 316 Expansions.push_back(Token); 317 } 318 return Expansions; 319 } 320 321 std::vector<syntax::Token> syntax::tokenize(const FileRange &FR, 322 const SourceManager &SM, 323 const LangOptions &LO) { 324 std::vector<syntax::Token> Tokens; 325 IdentifierTable Identifiers(LO); 326 auto AddToken = [&](clang::Token T) { 327 // Fill the proper token kind for keywords, etc. 328 if (T.getKind() == tok::raw_identifier && !T.needsCleaning() && 329 !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases. 330 clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier()); 331 T.setIdentifierInfo(&II); 332 T.setKind(II.getTokenID()); 333 } 334 Tokens.push_back(syntax::Token(T)); 335 }; 336 337 auto SrcBuffer = SM.getBufferData(FR.file()); 338 Lexer L(SM.getLocForStartOfFile(FR.file()), LO, SrcBuffer.data(), 339 SrcBuffer.data() + FR.beginOffset(), 340 // We can't make BufEnd point to FR.endOffset, as Lexer requires a 341 // null terminated buffer. 342 SrcBuffer.data() + SrcBuffer.size()); 343 344 clang::Token T; 345 while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < FR.endOffset()) 346 AddToken(T); 347 // LexFromRawLexer returns true when it parses the last token of the file, add 348 // it iff it starts within the range we are interested in. 349 if (SM.getFileOffset(T.getLocation()) < FR.endOffset()) 350 AddToken(T); 351 return Tokens; 352 } 353 354 std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM, 355 const LangOptions &LO) { 356 return tokenize(syntax::FileRange(FID, 0, SM.getFileIDSize(FID)), SM, LO); 357 } 358 359 /// Records information reqired to construct mappings for the token buffer that 360 /// we are collecting. 361 class TokenCollector::CollectPPExpansions : public PPCallbacks { 362 public: 363 CollectPPExpansions(TokenCollector &C) : Collector(&C) {} 364 365 /// Disabled instance will stop reporting anything to TokenCollector. 366 /// This ensures that uses of the preprocessor after TokenCollector::consume() 367 /// is called do not access the (possibly invalid) collector instance. 368 void disable() { Collector = nullptr; } 369 370 void MacroExpands(const clang::Token &MacroNameTok, const MacroDefinition &MD, 371 SourceRange Range, const MacroArgs *Args) override { 372 if (!Collector) 373 return; 374 // Only record top-level expansions, not those where: 375 // - the macro use is inside a macro body, 376 // - the macro appears in an argument to another macro. 377 if (!MacroNameTok.getLocation().isFileID() || 378 (LastExpansionEnd.isValid() && 379 Collector->PP.getSourceManager().isBeforeInTranslationUnit( 380 Range.getBegin(), LastExpansionEnd))) 381 return; 382 Collector->Expansions[Range.getBegin().getRawEncoding()] = Range.getEnd(); 383 LastExpansionEnd = Range.getEnd(); 384 } 385 // FIXME: handle directives like #pragma, #include, etc. 386 private: 387 TokenCollector *Collector; 388 /// Used to detect recursive macro expansions. 389 SourceLocation LastExpansionEnd; 390 }; 391 392 /// Fills in the TokenBuffer by tracing the run of a preprocessor. The 393 /// implementation tracks the tokens, macro expansions and directives coming 394 /// from the preprocessor and: 395 /// - for each token, figures out if it is a part of an expanded token stream, 396 /// spelled token stream or both. Stores the tokens appropriately. 397 /// - records mappings from the spelled to expanded token ranges, e.g. for macro 398 /// expansions. 399 /// FIXME: also properly record: 400 /// - #include directives, 401 /// - #pragma, #line and other PP directives, 402 /// - skipped pp regions, 403 /// - ... 404 405 TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) { 406 // Collect the expanded token stream during preprocessing. 407 PP.setTokenWatcher([this](const clang::Token &T) { 408 if (T.isAnnotation()) 409 return; 410 DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs() 411 << "Token: " 412 << syntax::Token(T).dumpForTests( 413 this->PP.getSourceManager()) 414 << "\n" 415 416 ); 417 Expanded.push_back(syntax::Token(T)); 418 }); 419 // And locations of macro calls, to properly recover boundaries of those in 420 // case of empty expansions. 421 auto CB = std::make_unique<CollectPPExpansions>(*this); 422 this->Collector = CB.get(); 423 PP.addPPCallbacks(std::move(CB)); 424 } 425 426 /// Builds mappings and spelled tokens in the TokenBuffer based on the expanded 427 /// token stream. 428 class TokenCollector::Builder { 429 public: 430 Builder(std::vector<syntax::Token> Expanded, PPExpansions CollectedExpansions, 431 const SourceManager &SM, const LangOptions &LangOpts) 432 : Result(SM), CollectedExpansions(std::move(CollectedExpansions)), SM(SM), 433 LangOpts(LangOpts) { 434 Result.ExpandedTokens = std::move(Expanded); 435 } 436 437 TokenBuffer build() && { 438 buildSpelledTokens(); 439 440 // Walk over expanded tokens and spelled tokens in parallel, building the 441 // mappings between those using source locations. 442 // To correctly recover empty macro expansions, we also take locations 443 // reported to PPCallbacks::MacroExpands into account as we do not have any 444 // expanded tokens with source locations to guide us. 445 446 // The 'eof' token is special, it is not part of spelled token stream. We 447 // handle it separately at the end. 448 assert(!Result.ExpandedTokens.empty()); 449 assert(Result.ExpandedTokens.back().kind() == tok::eof); 450 for (unsigned I = 0; I < Result.ExpandedTokens.size() - 1; ++I) { 451 // (!) I might be updated by the following call. 452 processExpandedToken(I); 453 } 454 455 // 'eof' not handled in the loop, do it here. 456 assert(SM.getMainFileID() == 457 SM.getFileID(Result.ExpandedTokens.back().location())); 458 fillGapUntil(Result.Files[SM.getMainFileID()], 459 Result.ExpandedTokens.back().location(), 460 Result.ExpandedTokens.size() - 1); 461 Result.Files[SM.getMainFileID()].EndExpanded = Result.ExpandedTokens.size(); 462 463 // Some files might have unaccounted spelled tokens at the end, add an empty 464 // mapping for those as they did not have expanded counterparts. 465 fillGapsAtEndOfFiles(); 466 467 return std::move(Result); 468 } 469 470 private: 471 /// Process the next token in an expanded stream and move corresponding 472 /// spelled tokens, record any mapping if needed. 473 /// (!) \p I will be updated if this had to skip tokens, e.g. for macros. 474 void processExpandedToken(unsigned &I) { 475 auto L = Result.ExpandedTokens[I].location(); 476 if (L.isMacroID()) { 477 processMacroExpansion(SM.getExpansionRange(L), I); 478 return; 479 } 480 if (L.isFileID()) { 481 auto FID = SM.getFileID(L); 482 TokenBuffer::MarkedFile &File = Result.Files[FID]; 483 484 fillGapUntil(File, L, I); 485 486 // Skip the token. 487 assert(File.SpelledTokens[NextSpelled[FID]].location() == L && 488 "no corresponding token in the spelled stream"); 489 ++NextSpelled[FID]; 490 return; 491 } 492 } 493 494 /// Skipped expanded and spelled tokens of a macro expansion that covers \p 495 /// SpelledRange. Add a corresponding mapping. 496 /// (!) \p I will be the index of the last token in an expansion after this 497 /// function returns. 498 void processMacroExpansion(CharSourceRange SpelledRange, unsigned &I) { 499 auto FID = SM.getFileID(SpelledRange.getBegin()); 500 assert(FID == SM.getFileID(SpelledRange.getEnd())); 501 TokenBuffer::MarkedFile &File = Result.Files[FID]; 502 503 fillGapUntil(File, SpelledRange.getBegin(), I); 504 505 // Skip all expanded tokens from the same macro expansion. 506 unsigned BeginExpanded = I; 507 for (; I + 1 < Result.ExpandedTokens.size(); ++I) { 508 auto NextL = Result.ExpandedTokens[I + 1].location(); 509 if (!NextL.isMacroID() || 510 SM.getExpansionLoc(NextL) != SpelledRange.getBegin()) 511 break; 512 } 513 unsigned EndExpanded = I + 1; 514 consumeMapping(File, SM.getFileOffset(SpelledRange.getEnd()), BeginExpanded, 515 EndExpanded, NextSpelled[FID]); 516 } 517 518 /// Initializes TokenBuffer::Files and fills spelled tokens and expanded 519 /// ranges for each of the files. 520 void buildSpelledTokens() { 521 for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) { 522 auto FID = 523 SM.getFileID(SM.getExpansionLoc(Result.ExpandedTokens[I].location())); 524 auto It = Result.Files.try_emplace(FID); 525 TokenBuffer::MarkedFile &File = It.first->second; 526 527 File.EndExpanded = I + 1; 528 if (!It.second) 529 continue; // we have seen this file before. 530 531 // This is the first time we see this file. 532 File.BeginExpanded = I; 533 File.SpelledTokens = tokenize(FID, SM, LangOpts); 534 } 535 } 536 537 void consumeEmptyMapping(TokenBuffer::MarkedFile &File, unsigned EndOffset, 538 unsigned ExpandedIndex, unsigned &SpelledIndex) { 539 consumeMapping(File, EndOffset, ExpandedIndex, ExpandedIndex, SpelledIndex); 540 } 541 542 /// Consumes spelled tokens that form a macro expansion and adds a entry to 543 /// the resulting token buffer. 544 /// (!) SpelledIndex is updated in-place. 545 void consumeMapping(TokenBuffer::MarkedFile &File, unsigned EndOffset, 546 unsigned BeginExpanded, unsigned EndExpanded, 547 unsigned &SpelledIndex) { 548 // We need to record this mapping before continuing. 549 unsigned MappingBegin = SpelledIndex; 550 ++SpelledIndex; 551 552 bool HitMapping = 553 tryConsumeSpelledUntil(File, EndOffset + 1, SpelledIndex).hasValue(); 554 (void)HitMapping; 555 assert(!HitMapping && "recursive macro expansion?"); 556 557 TokenBuffer::Mapping M; 558 M.BeginExpanded = BeginExpanded; 559 M.EndExpanded = EndExpanded; 560 M.BeginSpelled = MappingBegin; 561 M.EndSpelled = SpelledIndex; 562 563 File.Mappings.push_back(M); 564 } 565 566 /// Consumes spelled tokens until location \p L is reached and adds a mapping 567 /// covering the consumed tokens. The mapping will point to an empty expanded 568 /// range at position \p ExpandedIndex. 569 void fillGapUntil(TokenBuffer::MarkedFile &File, SourceLocation L, 570 unsigned ExpandedIndex) { 571 assert(L.isFileID()); 572 FileID FID; 573 unsigned Offset; 574 std::tie(FID, Offset) = SM.getDecomposedLoc(L); 575 576 unsigned &SpelledIndex = NextSpelled[FID]; 577 unsigned MappingBegin = SpelledIndex; 578 while (true) { 579 auto EndLoc = tryConsumeSpelledUntil(File, Offset, SpelledIndex); 580 if (SpelledIndex != MappingBegin) { 581 TokenBuffer::Mapping M; 582 M.BeginSpelled = MappingBegin; 583 M.EndSpelled = SpelledIndex; 584 M.BeginExpanded = M.EndExpanded = ExpandedIndex; 585 File.Mappings.push_back(M); 586 } 587 if (!EndLoc) 588 break; 589 consumeEmptyMapping(File, SM.getFileOffset(*EndLoc), ExpandedIndex, 590 SpelledIndex); 591 592 MappingBegin = SpelledIndex; 593 } 594 }; 595 596 /// Consumes spelled tokens until it reaches Offset or a mapping boundary, 597 /// i.e. a name of a macro expansion or the start '#' token of a PP directive. 598 /// (!) NextSpelled is updated in place. 599 /// 600 /// returns None if \p Offset was reached, otherwise returns the end location 601 /// of a mapping that starts at \p NextSpelled. 602 llvm::Optional<SourceLocation> 603 tryConsumeSpelledUntil(TokenBuffer::MarkedFile &File, unsigned Offset, 604 unsigned &NextSpelled) { 605 for (; NextSpelled < File.SpelledTokens.size(); ++NextSpelled) { 606 auto L = File.SpelledTokens[NextSpelled].location(); 607 if (Offset <= SM.getFileOffset(L)) 608 return llvm::None; // reached the offset we are looking for. 609 auto Mapping = CollectedExpansions.find(L.getRawEncoding()); 610 if (Mapping != CollectedExpansions.end()) 611 return Mapping->second; // found a mapping before the offset. 612 } 613 return llvm::None; // no more tokens, we "reached" the offset. 614 } 615 616 /// Adds empty mappings for unconsumed spelled tokens at the end of each file. 617 void fillGapsAtEndOfFiles() { 618 for (auto &F : Result.Files) { 619 if (F.second.SpelledTokens.empty()) 620 continue; 621 fillGapUntil(F.second, F.second.SpelledTokens.back().endLocation(), 622 F.second.EndExpanded); 623 } 624 } 625 626 TokenBuffer Result; 627 /// For each file, a position of the next spelled token we will consume. 628 llvm::DenseMap<FileID, unsigned> NextSpelled; 629 PPExpansions CollectedExpansions; 630 const SourceManager &SM; 631 const LangOptions &LangOpts; 632 }; 633 634 TokenBuffer TokenCollector::consume() && { 635 PP.setTokenWatcher(nullptr); 636 Collector->disable(); 637 return Builder(std::move(Expanded), std::move(Expansions), 638 PP.getSourceManager(), PP.getLangOpts()) 639 .build(); 640 } 641 642 std::string syntax::Token::str() const { 643 return std::string(llvm::formatv("Token({0}, length = {1})", 644 tok::getTokenName(kind()), length())); 645 } 646 647 std::string syntax::Token::dumpForTests(const SourceManager &SM) const { 648 return std::string( 649 llvm::formatv("{0} {1}", tok::getTokenName(kind()), text(SM))); 650 } 651 652 std::string TokenBuffer::dumpForTests() const { 653 auto PrintToken = [this](const syntax::Token &T) -> std::string { 654 if (T.kind() == tok::eof) 655 return "<eof>"; 656 return std::string(T.text(*SourceMgr)); 657 }; 658 659 auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS, 660 llvm::ArrayRef<syntax::Token> Tokens) { 661 if (Tokens.empty()) { 662 OS << "<empty>"; 663 return; 664 } 665 OS << Tokens[0].text(*SourceMgr); 666 for (unsigned I = 1; I < Tokens.size(); ++I) { 667 if (Tokens[I].kind() == tok::eof) 668 continue; 669 OS << " " << PrintToken(Tokens[I]); 670 } 671 }; 672 673 std::string Dump; 674 llvm::raw_string_ostream OS(Dump); 675 676 OS << "expanded tokens:\n" 677 << " "; 678 // (!) we do not show '<eof>'. 679 DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back()); 680 OS << "\n"; 681 682 std::vector<FileID> Keys; 683 for (auto F : Files) 684 Keys.push_back(F.first); 685 llvm::sort(Keys); 686 687 for (FileID ID : Keys) { 688 const MarkedFile &File = Files.find(ID)->second; 689 auto *Entry = SourceMgr->getFileEntryForID(ID); 690 if (!Entry) 691 continue; // Skip builtin files. 692 OS << llvm::formatv("file '{0}'\n", Entry->getName()) 693 << " spelled tokens:\n" 694 << " "; 695 DumpTokens(OS, File.SpelledTokens); 696 OS << "\n"; 697 698 if (File.Mappings.empty()) { 699 OS << " no mappings.\n"; 700 continue; 701 } 702 OS << " mappings:\n"; 703 for (auto &M : File.Mappings) { 704 OS << llvm::formatv( 705 " ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n", 706 PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled, 707 M.EndSpelled == File.SpelledTokens.size() 708 ? "<eof>" 709 : PrintToken(File.SpelledTokens[M.EndSpelled]), 710 M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]), 711 M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]), 712 M.EndExpanded); 713 } 714 } 715 return OS.str(); 716 } 717