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 void TokenBuffer::indexExpandedTokens() { 187 // No-op if the index is already created. 188 if (!ExpandedTokIndex.empty()) 189 return; 190 ExpandedTokIndex.reserve(ExpandedTokens.size()); 191 // Index ExpandedTokens for faster lookups by SourceLocation. 192 for (size_t I = 0, E = ExpandedTokens.size(); I != E; ++I) 193 ExpandedTokIndex[ExpandedTokens[I].location()] = I; 194 } 195 196 llvm::ArrayRef<syntax::Token> TokenBuffer::expandedTokens(SourceRange R) const { 197 if (!ExpandedTokIndex.empty()) { 198 // Quick lookup if `R` is a token range. 199 // This is a huge win since majority of the users use ranges provided by an 200 // AST. Ranges in AST are token ranges from expanded token stream. 201 const auto B = ExpandedTokIndex.find(R.getBegin()); 202 const auto E = ExpandedTokIndex.find(R.getEnd()); 203 if (B != ExpandedTokIndex.end() && E != ExpandedTokIndex.end()) { 204 // Add 1 to End to make a half-open range. 205 return {ExpandedTokens.data() + B->getSecond(), 206 ExpandedTokens.data() + E->getSecond() + 1}; 207 } 208 } 209 // Slow case. Use `isBeforeInTranslationUnit` to binary search for the 210 // required range. 211 return getTokensCovering(expandedTokens(), R, *SourceMgr); 212 } 213 214 CharSourceRange FileRange::toCharRange(const SourceManager &SM) const { 215 return CharSourceRange( 216 SourceRange(SM.getComposedLoc(File, Begin), SM.getComposedLoc(File, End)), 217 /*IsTokenRange=*/false); 218 } 219 220 std::pair<const syntax::Token *, const TokenBuffer::Mapping *> 221 TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const { 222 assert(Expanded); 223 assert(ExpandedTokens.data() <= Expanded && 224 Expanded < ExpandedTokens.data() + ExpandedTokens.size()); 225 226 auto FileIt = Files.find( 227 SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location()))); 228 assert(FileIt != Files.end() && "no file for an expanded token"); 229 230 const MarkedFile &File = FileIt->second; 231 232 unsigned ExpandedIndex = Expanded - ExpandedTokens.data(); 233 // Find the first mapping that produced tokens after \p Expanded. 234 auto It = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 235 return M.BeginExpanded <= ExpandedIndex; 236 }); 237 // Our token could only be produced by the previous mapping. 238 if (It == File.Mappings.begin()) { 239 // No previous mapping, no need to modify offsets. 240 return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded], 241 /*Mapping=*/nullptr}; 242 } 243 --It; // 'It' now points to last mapping that started before our token. 244 245 // Check if the token is part of the mapping. 246 if (ExpandedIndex < It->EndExpanded) 247 return {&File.SpelledTokens[It->BeginSpelled], /*Mapping=*/&*It}; 248 249 // Not part of the mapping, use the index from previous mapping to compute the 250 // corresponding spelled token. 251 return { 252 &File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)], 253 /*Mapping=*/nullptr}; 254 } 255 256 const TokenBuffer::Mapping * 257 TokenBuffer::mappingStartingBeforeSpelled(const MarkedFile &F, 258 const syntax::Token *Spelled) { 259 assert(F.SpelledTokens.data() <= Spelled); 260 unsigned SpelledI = Spelled - F.SpelledTokens.data(); 261 assert(SpelledI < F.SpelledTokens.size()); 262 263 auto It = llvm::partition_point(F.Mappings, [SpelledI](const Mapping &M) { 264 return M.BeginSpelled <= SpelledI; 265 }); 266 if (It == F.Mappings.begin()) 267 return nullptr; 268 --It; 269 return &*It; 270 } 271 272 llvm::SmallVector<llvm::ArrayRef<syntax::Token>, 1> 273 TokenBuffer::expandedForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const { 274 if (Spelled.empty()) 275 return {}; 276 const auto &File = fileForSpelled(Spelled); 277 278 auto *FrontMapping = mappingStartingBeforeSpelled(File, &Spelled.front()); 279 unsigned SpelledFrontI = &Spelled.front() - File.SpelledTokens.data(); 280 assert(SpelledFrontI < File.SpelledTokens.size()); 281 unsigned ExpandedBegin; 282 if (!FrontMapping) { 283 // No mapping that starts before the first token of Spelled, we don't have 284 // to modify offsets. 285 ExpandedBegin = File.BeginExpanded + SpelledFrontI; 286 } else if (SpelledFrontI < FrontMapping->EndSpelled) { 287 // This mapping applies to Spelled tokens. 288 if (SpelledFrontI != FrontMapping->BeginSpelled) { 289 // Spelled tokens don't cover the entire mapping, returning empty result. 290 return {}; // FIXME: support macro arguments. 291 } 292 // Spelled tokens start at the beginning of this mapping. 293 ExpandedBegin = FrontMapping->BeginExpanded; 294 } else { 295 // Spelled tokens start after the mapping ends (they start in the hole 296 // between 2 mappings, or between a mapping and end of the file). 297 ExpandedBegin = 298 FrontMapping->EndExpanded + (SpelledFrontI - FrontMapping->EndSpelled); 299 } 300 301 auto *BackMapping = mappingStartingBeforeSpelled(File, &Spelled.back()); 302 unsigned SpelledBackI = &Spelled.back() - File.SpelledTokens.data(); 303 unsigned ExpandedEnd; 304 if (!BackMapping) { 305 // No mapping that starts before the last token of Spelled, we don't have to 306 // modify offsets. 307 ExpandedEnd = File.BeginExpanded + SpelledBackI + 1; 308 } else if (SpelledBackI < BackMapping->EndSpelled) { 309 // This mapping applies to Spelled tokens. 310 if (SpelledBackI + 1 != BackMapping->EndSpelled) { 311 // Spelled tokens don't cover the entire mapping, returning empty result. 312 return {}; // FIXME: support macro arguments. 313 } 314 ExpandedEnd = BackMapping->EndExpanded; 315 } else { 316 // Spelled tokens end after the mapping ends. 317 ExpandedEnd = 318 BackMapping->EndExpanded + (SpelledBackI - BackMapping->EndSpelled) + 1; 319 } 320 321 assert(ExpandedBegin < ExpandedTokens.size()); 322 assert(ExpandedEnd < ExpandedTokens.size()); 323 // Avoid returning empty ranges. 324 if (ExpandedBegin == ExpandedEnd) 325 return {}; 326 return {llvm::makeArrayRef(ExpandedTokens.data() + ExpandedBegin, 327 ExpandedTokens.data() + ExpandedEnd)}; 328 } 329 330 llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const { 331 auto It = Files.find(FID); 332 assert(It != Files.end()); 333 return It->second.SpelledTokens; 334 } 335 336 const syntax::Token *TokenBuffer::spelledTokenAt(SourceLocation Loc) const { 337 assert(Loc.isFileID()); 338 const auto *Tok = llvm::partition_point( 339 spelledTokens(SourceMgr->getFileID(Loc)), 340 [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 341 if (!Tok || Tok->location() != Loc) 342 return nullptr; 343 return Tok; 344 } 345 346 std::string TokenBuffer::Mapping::str() const { 347 return std::string( 348 llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})", 349 BeginSpelled, EndSpelled, BeginExpanded, EndExpanded)); 350 } 351 352 llvm::Optional<llvm::ArrayRef<syntax::Token>> 353 TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const { 354 // Mapping an empty range is ambiguous in case of empty mappings at either end 355 // of the range, bail out in that case. 356 if (Expanded.empty()) 357 return llvm::None; 358 359 const syntax::Token *BeginSpelled; 360 const Mapping *BeginMapping; 361 std::tie(BeginSpelled, BeginMapping) = 362 spelledForExpandedToken(&Expanded.front()); 363 364 const syntax::Token *LastSpelled; 365 const Mapping *LastMapping; 366 std::tie(LastSpelled, LastMapping) = 367 spelledForExpandedToken(&Expanded.back()); 368 369 FileID FID = SourceMgr->getFileID(BeginSpelled->location()); 370 // FIXME: Handle multi-file changes by trying to map onto a common root. 371 if (FID != SourceMgr->getFileID(LastSpelled->location())) 372 return llvm::None; 373 374 const MarkedFile &File = Files.find(FID)->second; 375 376 // If both tokens are coming from a macro argument expansion, try and map to 377 // smallest part of the macro argument. BeginMapping && LastMapping check is 378 // only for performance, they are a prerequisite for Expanded.front() and 379 // Expanded.back() being part of a macro arg expansion. 380 if (BeginMapping && LastMapping && 381 SourceMgr->isMacroArgExpansion(Expanded.front().location()) && 382 SourceMgr->isMacroArgExpansion(Expanded.back().location())) { 383 auto CommonRange = findCommonRangeForMacroArgs(Expanded.front(), 384 Expanded.back(), *SourceMgr); 385 // It might be the case that tokens are arguments of different macro calls, 386 // in that case we should continue with the logic below instead of returning 387 // an empty range. 388 if (CommonRange.isValid()) 389 return getTokensCovering(File.SpelledTokens, CommonRange, *SourceMgr); 390 } 391 392 // Do not allow changes that doesn't cover full expansion. 393 unsigned BeginExpanded = Expanded.begin() - ExpandedTokens.data(); 394 unsigned EndExpanded = Expanded.end() - ExpandedTokens.data(); 395 if (BeginMapping && BeginExpanded != BeginMapping->BeginExpanded) 396 return llvm::None; 397 if (LastMapping && LastMapping->EndExpanded != EndExpanded) 398 return llvm::None; 399 // All is good, return the result. 400 return llvm::makeArrayRef( 401 BeginMapping ? File.SpelledTokens.data() + BeginMapping->BeginSpelled 402 : BeginSpelled, 403 LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled 404 : LastSpelled + 1); 405 } 406 407 TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F, 408 const Mapping &M) const { 409 Expansion E; 410 E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled, 411 F.SpelledTokens.data() + M.EndSpelled); 412 E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded, 413 ExpandedTokens.data() + M.EndExpanded); 414 return E; 415 } 416 417 const TokenBuffer::MarkedFile & 418 TokenBuffer::fileForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const { 419 assert(!Spelled.empty()); 420 assert(Spelled.front().location().isFileID() && "not a spelled token"); 421 auto FileIt = Files.find(SourceMgr->getFileID(Spelled.front().location())); 422 assert(FileIt != Files.end() && "file not tracked by token buffer"); 423 const auto &File = FileIt->second; 424 assert(File.SpelledTokens.data() <= Spelled.data() && 425 Spelled.end() <= 426 (File.SpelledTokens.data() + File.SpelledTokens.size()) && 427 "Tokens not in spelled range"); 428 #ifndef NDEBUG 429 auto T1 = Spelled.back().location(); 430 auto T2 = File.SpelledTokens.back().location(); 431 assert(T1 == T2 || sourceManager().isBeforeInTranslationUnit(T1, T2)); 432 #endif 433 return File; 434 } 435 436 llvm::Optional<TokenBuffer::Expansion> 437 TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const { 438 assert(Spelled); 439 const auto &File = fileForSpelled(*Spelled); 440 441 unsigned SpelledIndex = Spelled - File.SpelledTokens.data(); 442 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 443 return M.BeginSpelled < SpelledIndex; 444 }); 445 if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex) 446 return llvm::None; 447 return makeExpansion(File, *M); 448 } 449 450 std::vector<TokenBuffer::Expansion> TokenBuffer::expansionsOverlapping( 451 llvm::ArrayRef<syntax::Token> Spelled) const { 452 if (Spelled.empty()) 453 return {}; 454 const auto &File = fileForSpelled(Spelled); 455 456 // Find the first overlapping range, and then copy until we stop overlapping. 457 unsigned SpelledBeginIndex = Spelled.begin() - File.SpelledTokens.data(); 458 unsigned SpelledEndIndex = Spelled.end() - File.SpelledTokens.data(); 459 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 460 return M.EndSpelled <= SpelledBeginIndex; 461 }); 462 std::vector<TokenBuffer::Expansion> Expansions; 463 for (; M != File.Mappings.end() && M->BeginSpelled < SpelledEndIndex; ++M) 464 Expansions.push_back(makeExpansion(File, *M)); 465 return Expansions; 466 } 467 468 llvm::ArrayRef<syntax::Token> 469 syntax::spelledTokensTouching(SourceLocation Loc, 470 llvm::ArrayRef<syntax::Token> Tokens) { 471 assert(Loc.isFileID()); 472 473 auto *Right = llvm::partition_point( 474 Tokens, [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 475 bool AcceptRight = Right != Tokens.end() && Right->location() <= Loc; 476 bool AcceptLeft = 477 Right != Tokens.begin() && (Right - 1)->endLocation() >= Loc; 478 return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0), 479 Right + (AcceptRight ? 1 : 0)); 480 } 481 482 llvm::ArrayRef<syntax::Token> 483 syntax::spelledTokensTouching(SourceLocation Loc, 484 const syntax::TokenBuffer &Tokens) { 485 return spelledTokensTouching( 486 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 487 } 488 489 const syntax::Token * 490 syntax::spelledIdentifierTouching(SourceLocation Loc, 491 llvm::ArrayRef<syntax::Token> Tokens) { 492 for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) { 493 if (Tok.kind() == tok::identifier) 494 return &Tok; 495 } 496 return nullptr; 497 } 498 499 const syntax::Token * 500 syntax::spelledIdentifierTouching(SourceLocation Loc, 501 const syntax::TokenBuffer &Tokens) { 502 return spelledIdentifierTouching( 503 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 504 } 505 506 std::vector<const syntax::Token *> 507 TokenBuffer::macroExpansions(FileID FID) const { 508 auto FileIt = Files.find(FID); 509 assert(FileIt != Files.end() && "file not tracked by token buffer"); 510 auto &File = FileIt->second; 511 std::vector<const syntax::Token *> Expansions; 512 auto &Spelled = File.SpelledTokens; 513 for (auto Mapping : File.Mappings) { 514 const syntax::Token *Token = &Spelled[Mapping.BeginSpelled]; 515 if (Token->kind() == tok::TokenKind::identifier) 516 Expansions.push_back(Token); 517 } 518 return Expansions; 519 } 520 521 std::vector<syntax::Token> syntax::tokenize(const FileRange &FR, 522 const SourceManager &SM, 523 const LangOptions &LO) { 524 std::vector<syntax::Token> Tokens; 525 IdentifierTable Identifiers(LO); 526 auto AddToken = [&](clang::Token T) { 527 // Fill the proper token kind for keywords, etc. 528 if (T.getKind() == tok::raw_identifier && !T.needsCleaning() && 529 !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases. 530 clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier()); 531 T.setIdentifierInfo(&II); 532 T.setKind(II.getTokenID()); 533 } 534 Tokens.push_back(syntax::Token(T)); 535 }; 536 537 auto SrcBuffer = SM.getBufferData(FR.file()); 538 Lexer L(SM.getLocForStartOfFile(FR.file()), LO, SrcBuffer.data(), 539 SrcBuffer.data() + FR.beginOffset(), 540 // We can't make BufEnd point to FR.endOffset, as Lexer requires a 541 // null terminated buffer. 542 SrcBuffer.data() + SrcBuffer.size()); 543 544 clang::Token T; 545 while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < FR.endOffset()) 546 AddToken(T); 547 // LexFromRawLexer returns true when it parses the last token of the file, add 548 // it iff it starts within the range we are interested in. 549 if (SM.getFileOffset(T.getLocation()) < FR.endOffset()) 550 AddToken(T); 551 return Tokens; 552 } 553 554 std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM, 555 const LangOptions &LO) { 556 return tokenize(syntax::FileRange(FID, 0, SM.getFileIDSize(FID)), SM, LO); 557 } 558 559 /// Records information reqired to construct mappings for the token buffer that 560 /// we are collecting. 561 class TokenCollector::CollectPPExpansions : public PPCallbacks { 562 public: 563 CollectPPExpansions(TokenCollector &C) : Collector(&C) {} 564 565 /// Disabled instance will stop reporting anything to TokenCollector. 566 /// This ensures that uses of the preprocessor after TokenCollector::consume() 567 /// is called do not access the (possibly invalid) collector instance. 568 void disable() { Collector = nullptr; } 569 570 void MacroExpands(const clang::Token &MacroNameTok, const MacroDefinition &MD, 571 SourceRange Range, const MacroArgs *Args) override { 572 if (!Collector) 573 return; 574 const auto &SM = Collector->PP.getSourceManager(); 575 // Only record top-level expansions that directly produce expanded tokens. 576 // This excludes those where: 577 // - the macro use is inside a macro body, 578 // - the macro appears in an argument to another macro. 579 // However macro expansion isn't really a tree, it's token rewrite rules, 580 // so there are other cases, e.g. 581 // #define B(X) X 582 // #define A 1 + B 583 // A(2) 584 // Both A and B produce expanded tokens, though the macro name 'B' comes 585 // from an expansion. The best we can do is merge the mappings for both. 586 587 // The *last* token of any top-level macro expansion must be in a file. 588 // (In the example above, see the closing paren of the expansion of B). 589 if (!Range.getEnd().isFileID()) 590 return; 591 // If there's a current expansion that encloses this one, this one can't be 592 // top-level. 593 if (LastExpansionEnd.isValid() && 594 !SM.isBeforeInTranslationUnit(LastExpansionEnd, Range.getEnd())) 595 return; 596 597 // If the macro invocation (B) starts in a macro (A) but ends in a file, 598 // we'll create a merged mapping for A + B by overwriting the endpoint for 599 // A's startpoint. 600 if (!Range.getBegin().isFileID()) { 601 Range.setBegin(SM.getExpansionLoc(Range.getBegin())); 602 assert(Collector->Expansions.count(Range.getBegin()) && 603 "Overlapping macros should have same expansion location"); 604 } 605 606 Collector->Expansions[Range.getBegin()] = Range.getEnd(); 607 LastExpansionEnd = Range.getEnd(); 608 } 609 // FIXME: handle directives like #pragma, #include, etc. 610 private: 611 TokenCollector *Collector; 612 /// Used to detect recursive macro expansions. 613 SourceLocation LastExpansionEnd; 614 }; 615 616 /// Fills in the TokenBuffer by tracing the run of a preprocessor. The 617 /// implementation tracks the tokens, macro expansions and directives coming 618 /// from the preprocessor and: 619 /// - for each token, figures out if it is a part of an expanded token stream, 620 /// spelled token stream or both. Stores the tokens appropriately. 621 /// - records mappings from the spelled to expanded token ranges, e.g. for macro 622 /// expansions. 623 /// FIXME: also properly record: 624 /// - #include directives, 625 /// - #pragma, #line and other PP directives, 626 /// - skipped pp regions, 627 /// - ... 628 629 TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) { 630 // Collect the expanded token stream during preprocessing. 631 PP.setTokenWatcher([this](const clang::Token &T) { 632 if (T.isAnnotation()) 633 return; 634 DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs() 635 << "Token: " 636 << syntax::Token(T).dumpForTests( 637 this->PP.getSourceManager()) 638 << "\n" 639 640 ); 641 Expanded.push_back(syntax::Token(T)); 642 }); 643 // And locations of macro calls, to properly recover boundaries of those in 644 // case of empty expansions. 645 auto CB = std::make_unique<CollectPPExpansions>(*this); 646 this->Collector = CB.get(); 647 PP.addPPCallbacks(std::move(CB)); 648 } 649 650 /// Builds mappings and spelled tokens in the TokenBuffer based on the expanded 651 /// token stream. 652 class TokenCollector::Builder { 653 public: 654 Builder(std::vector<syntax::Token> Expanded, PPExpansions CollectedExpansions, 655 const SourceManager &SM, const LangOptions &LangOpts) 656 : Result(SM), CollectedExpansions(std::move(CollectedExpansions)), SM(SM), 657 LangOpts(LangOpts) { 658 Result.ExpandedTokens = std::move(Expanded); 659 } 660 661 TokenBuffer build() && { 662 assert(!Result.ExpandedTokens.empty()); 663 assert(Result.ExpandedTokens.back().kind() == tok::eof); 664 665 // Tokenize every file that contributed tokens to the expanded stream. 666 buildSpelledTokens(); 667 668 // The expanded token stream consists of runs of tokens that came from 669 // the same source (a macro expansion, part of a file etc). 670 // Between these runs are the logical positions of spelled tokens that 671 // didn't expand to anything. 672 while (NextExpanded < Result.ExpandedTokens.size() - 1 /* eof */) { 673 // Create empty mappings for spelled tokens that expanded to nothing here. 674 // May advance NextSpelled, but NextExpanded is unchanged. 675 discard(); 676 // Create mapping for a contiguous run of expanded tokens. 677 // Advances NextExpanded past the run, and NextSpelled accordingly. 678 unsigned OldPosition = NextExpanded; 679 advance(); 680 if (NextExpanded == OldPosition) 681 diagnoseAdvanceFailure(); 682 } 683 // If any tokens remain in any of the files, they didn't expand to anything. 684 // Create empty mappings up until the end of the file. 685 for (const auto &File : Result.Files) 686 discard(File.first); 687 688 #ifndef NDEBUG 689 for (auto &pair : Result.Files) { 690 auto &mappings = pair.second.Mappings; 691 assert(llvm::is_sorted(mappings, [](const TokenBuffer::Mapping &M1, 692 const TokenBuffer::Mapping &M2) { 693 return M1.BeginSpelled < M2.BeginSpelled && 694 M1.EndSpelled < M2.EndSpelled && 695 M1.BeginExpanded < M2.BeginExpanded && 696 M1.EndExpanded < M2.EndExpanded; 697 })); 698 } 699 #endif 700 701 return std::move(Result); 702 } 703 704 private: 705 // Consume a sequence of spelled tokens that didn't expand to anything. 706 // In the simplest case, skips spelled tokens until finding one that produced 707 // the NextExpanded token, and creates an empty mapping for them. 708 // If Drain is provided, skips remaining tokens from that file instead. 709 void discard(llvm::Optional<FileID> Drain = llvm::None) { 710 SourceLocation Target = 711 Drain ? SM.getLocForEndOfFile(*Drain) 712 : SM.getExpansionLoc( 713 Result.ExpandedTokens[NextExpanded].location()); 714 FileID File = SM.getFileID(Target); 715 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 716 auto &NextSpelled = this->NextSpelled[File]; 717 718 TokenBuffer::Mapping Mapping; 719 Mapping.BeginSpelled = NextSpelled; 720 // When dropping trailing tokens from a file, the empty mapping should 721 // be positioned within the file's expanded-token range (at the end). 722 Mapping.BeginExpanded = Mapping.EndExpanded = 723 Drain ? Result.Files[*Drain].EndExpanded : NextExpanded; 724 // We may want to split into several adjacent empty mappings. 725 // FlushMapping() emits the current mapping and starts a new one. 726 auto FlushMapping = [&, this] { 727 Mapping.EndSpelled = NextSpelled; 728 if (Mapping.BeginSpelled != Mapping.EndSpelled) 729 Result.Files[File].Mappings.push_back(Mapping); 730 Mapping.BeginSpelled = NextSpelled; 731 }; 732 733 while (NextSpelled < SpelledTokens.size() && 734 SpelledTokens[NextSpelled].location() < Target) { 735 // If we know mapping bounds at [NextSpelled, KnownEnd] (macro expansion) 736 // then we want to partition our (empty) mapping. 737 // [Start, NextSpelled) [NextSpelled, KnownEnd] (KnownEnd, Target) 738 SourceLocation KnownEnd = 739 CollectedExpansions.lookup(SpelledTokens[NextSpelled].location()); 740 if (KnownEnd.isValid()) { 741 FlushMapping(); // Emits [Start, NextSpelled) 742 while (NextSpelled < SpelledTokens.size() && 743 SpelledTokens[NextSpelled].location() <= KnownEnd) 744 ++NextSpelled; 745 FlushMapping(); // Emits [NextSpelled, KnownEnd] 746 // Now the loop contitues and will emit (KnownEnd, Target). 747 } else { 748 ++NextSpelled; 749 } 750 } 751 FlushMapping(); 752 } 753 754 // Consumes the NextExpanded token and others that are part of the same run. 755 // Increases NextExpanded and NextSpelled by at least one, and adds a mapping 756 // (unless this is a run of file tokens, which we represent with no mapping). 757 void advance() { 758 const syntax::Token &Tok = Result.ExpandedTokens[NextExpanded]; 759 SourceLocation Expansion = SM.getExpansionLoc(Tok.location()); 760 FileID File = SM.getFileID(Expansion); 761 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 762 auto &NextSpelled = this->NextSpelled[File]; 763 764 if (Tok.location().isFileID()) { 765 // A run of file tokens continues while the expanded/spelled tokens match. 766 while (NextSpelled < SpelledTokens.size() && 767 NextExpanded < Result.ExpandedTokens.size() && 768 SpelledTokens[NextSpelled].location() == 769 Result.ExpandedTokens[NextExpanded].location()) { 770 ++NextSpelled; 771 ++NextExpanded; 772 } 773 // We need no mapping for file tokens copied to the expanded stream. 774 } else { 775 // We found a new macro expansion. We should have its spelling bounds. 776 auto End = CollectedExpansions.lookup(Expansion); 777 assert(End.isValid() && "Macro expansion wasn't captured?"); 778 779 // Mapping starts here... 780 TokenBuffer::Mapping Mapping; 781 Mapping.BeginExpanded = NextExpanded; 782 Mapping.BeginSpelled = NextSpelled; 783 // ... consumes spelled tokens within bounds we captured ... 784 while (NextSpelled < SpelledTokens.size() && 785 SpelledTokens[NextSpelled].location() <= End) 786 ++NextSpelled; 787 // ... consumes expanded tokens rooted at the same expansion ... 788 while (NextExpanded < Result.ExpandedTokens.size() && 789 SM.getExpansionLoc( 790 Result.ExpandedTokens[NextExpanded].location()) == Expansion) 791 ++NextExpanded; 792 // ... and ends here. 793 Mapping.EndExpanded = NextExpanded; 794 Mapping.EndSpelled = NextSpelled; 795 Result.Files[File].Mappings.push_back(Mapping); 796 } 797 } 798 799 // advance() is supposed to consume at least one token - if not, we crash. 800 void diagnoseAdvanceFailure() { 801 #ifndef NDEBUG 802 // Show the failed-to-map token in context. 803 for (unsigned I = (NextExpanded < 10) ? 0 : NextExpanded - 10; 804 I < NextExpanded + 5 && I < Result.ExpandedTokens.size(); ++I) { 805 const char *L = 806 (I == NextExpanded) ? "!! " : (I < NextExpanded) ? "ok " : " "; 807 llvm::errs() << L << Result.ExpandedTokens[I].dumpForTests(SM) << "\n"; 808 } 809 #endif 810 llvm_unreachable("Couldn't map expanded token to spelled tokens!"); 811 } 812 813 /// Initializes TokenBuffer::Files and fills spelled tokens and expanded 814 /// ranges for each of the files. 815 void buildSpelledTokens() { 816 for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) { 817 const auto &Tok = Result.ExpandedTokens[I]; 818 auto FID = SM.getFileID(SM.getExpansionLoc(Tok.location())); 819 auto It = Result.Files.try_emplace(FID); 820 TokenBuffer::MarkedFile &File = It.first->second; 821 822 // The eof token should not be considered part of the main-file's range. 823 File.EndExpanded = Tok.kind() == tok::eof ? I : I + 1; 824 825 if (!It.second) 826 continue; // we have seen this file before. 827 // This is the first time we see this file. 828 File.BeginExpanded = I; 829 File.SpelledTokens = tokenize(FID, SM, LangOpts); 830 } 831 } 832 833 TokenBuffer Result; 834 unsigned NextExpanded = 0; // cursor in ExpandedTokens 835 llvm::DenseMap<FileID, unsigned> NextSpelled; // cursor in SpelledTokens 836 PPExpansions CollectedExpansions; 837 const SourceManager &SM; 838 const LangOptions &LangOpts; 839 }; 840 841 TokenBuffer TokenCollector::consume() && { 842 PP.setTokenWatcher(nullptr); 843 Collector->disable(); 844 return Builder(std::move(Expanded), std::move(Expansions), 845 PP.getSourceManager(), PP.getLangOpts()) 846 .build(); 847 } 848 849 std::string syntax::Token::str() const { 850 return std::string(llvm::formatv("Token({0}, length = {1})", 851 tok::getTokenName(kind()), length())); 852 } 853 854 std::string syntax::Token::dumpForTests(const SourceManager &SM) const { 855 return std::string(llvm::formatv("Token(`{0}`, {1}, length = {2})", text(SM), 856 tok::getTokenName(kind()), length())); 857 } 858 859 std::string TokenBuffer::dumpForTests() const { 860 auto PrintToken = [this](const syntax::Token &T) -> std::string { 861 if (T.kind() == tok::eof) 862 return "<eof>"; 863 return std::string(T.text(*SourceMgr)); 864 }; 865 866 auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS, 867 llvm::ArrayRef<syntax::Token> Tokens) { 868 if (Tokens.empty()) { 869 OS << "<empty>"; 870 return; 871 } 872 OS << Tokens[0].text(*SourceMgr); 873 for (unsigned I = 1; I < Tokens.size(); ++I) { 874 if (Tokens[I].kind() == tok::eof) 875 continue; 876 OS << " " << PrintToken(Tokens[I]); 877 } 878 }; 879 880 std::string Dump; 881 llvm::raw_string_ostream OS(Dump); 882 883 OS << "expanded tokens:\n" 884 << " "; 885 // (!) we do not show '<eof>'. 886 DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back()); 887 OS << "\n"; 888 889 std::vector<FileID> Keys; 890 for (auto F : Files) 891 Keys.push_back(F.first); 892 llvm::sort(Keys); 893 894 for (FileID ID : Keys) { 895 const MarkedFile &File = Files.find(ID)->second; 896 auto *Entry = SourceMgr->getFileEntryForID(ID); 897 if (!Entry) 898 continue; // Skip builtin files. 899 OS << llvm::formatv("file '{0}'\n", Entry->getName()) 900 << " spelled tokens:\n" 901 << " "; 902 DumpTokens(OS, File.SpelledTokens); 903 OS << "\n"; 904 905 if (File.Mappings.empty()) { 906 OS << " no mappings.\n"; 907 continue; 908 } 909 OS << " mappings:\n"; 910 for (auto &M : File.Mappings) { 911 OS << llvm::formatv( 912 " ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n", 913 PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled, 914 M.EndSpelled == File.SpelledTokens.size() 915 ? "<eof>" 916 : PrintToken(File.SpelledTokens[M.EndSpelled]), 917 M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]), 918 M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]), 919 M.EndExpanded); 920 } 921 } 922 return OS.str(); 923 } 924