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