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 range within FID corresponding to expanded tokens [First, Last]. 59 // Prev precedes First and Next follows Last, these must *not* be included. 60 // If no range satisfies the criteria, returns an invalid range. 61 // 62 // #define ID(x) x 63 // ID(ID(ID(a1) a2)) 64 // ~~ -> a1 65 // ~~ -> a2 66 // ~~~~~~~~~ -> a1 a2 67 SourceRange spelledForExpandedSlow(SourceLocation First, SourceLocation Last, 68 SourceLocation Prev, SourceLocation Next, 69 FileID TargetFile, 70 const SourceManager &SM) { 71 // There are two main parts to this algorithm: 72 // - identifying which spelled range covers the expanded tokens 73 // - validating that this range doesn't cover any extra tokens (First/Last) 74 // 75 // We do these in order. However as we transform the expanded range into the 76 // spelled one, we adjust First/Last so the validation remains simple. 77 78 assert(SM.getSLocEntry(TargetFile).isFile()); 79 // In most cases, to select First and Last we must return their expansion 80 // range, i.e. the whole of any macros they are included in. 81 // 82 // When First and Last are part of the *same macro arg* of a macro written 83 // in TargetFile, we that slice of the arg, i.e. their spelling range. 84 // 85 // Unwrap such macro calls. If the target file has A(B(C)), the 86 // SourceLocation stack of a token inside C shows us the expansion of A first, 87 // then B, then any macros inside C's body, then C itself. 88 // (This is the reverse of the order the PP applies the expansions in). 89 while (First.isMacroID() && Last.isMacroID()) { 90 auto DecFirst = SM.getDecomposedLoc(First); 91 auto DecLast = SM.getDecomposedLoc(Last); 92 auto &ExpFirst = SM.getSLocEntry(DecFirst.first).getExpansion(); 93 auto &ExpLast = SM.getSLocEntry(DecLast.first).getExpansion(); 94 95 if (!ExpFirst.isMacroArgExpansion() || !ExpLast.isMacroArgExpansion()) 96 break; 97 // Locations are in the same macro arg if they expand to the same place. 98 // (They may still have different FileIDs - an arg can have >1 chunks!) 99 if (ExpFirst.getExpansionLocStart() != ExpLast.getExpansionLocStart()) 100 break; 101 // Careful, given: 102 // #define HIDE ID(ID(a)) 103 // ID(ID(HIDE)) 104 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2. 105 // We distinguish them by whether the macro expands into the target file. 106 // Fortunately, the target file ones will always appear first. 107 auto &ExpMacro = 108 SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart())) 109 .getExpansion(); 110 if (ExpMacro.getExpansionLocStart().isMacroID()) 111 break; 112 // Replace each endpoint with its spelling inside the macro arg. 113 // (This is getImmediateSpellingLoc without repeating lookups). 114 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second); 115 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second); 116 117 // Now: how do we adjust the previous/next bounds? Three cases: 118 // A) If they are also part of the same macro arg, we translate them too. 119 // This will ensure that we don't select any macros nested within the 120 // macro arg that cover extra tokens. Critical case: 121 // #define ID(X) X 122 // ID(prev target) // selecting 'target' succeeds 123 // #define LARGE ID(prev target) 124 // LARGE // selecting 'target' fails. 125 // B) They are not in the macro at all, then their expansion range is a 126 // sibling to it, and we can safely substitute that. 127 // #define PREV prev 128 // #define ID(X) X 129 // PREV ID(target) // selecting 'target' succeeds. 130 // #define LARGE PREV ID(target) 131 // LARGE // selecting 'target' fails. 132 // C) They are in a different arg of this macro, or the macro body. 133 // Now selecting the whole macro arg is fine, but the whole macro is not. 134 // Model this by setting using the edge of the macro call as the bound. 135 // #define ID2(X, Y) X Y 136 // ID2(prev, target) // selecting 'target' succeeds 137 // #define LARGE ID2(prev, target) 138 // LARGE // selecting 'target' fails 139 auto AdjustBound = [&](SourceLocation &Bound) { 140 if (Bound.isInvalid() || !Bound.isMacroID()) // Non-macro must be case B. 141 return; 142 auto DecBound = SM.getDecomposedLoc(Bound); 143 auto &ExpBound = SM.getSLocEntry(DecBound.first).getExpansion(); 144 if (ExpBound.isMacroArgExpansion() && 145 ExpBound.getExpansionLocStart() == ExpFirst.getExpansionLocStart()) { 146 // Case A: translate to (spelling) loc within the macro arg. 147 Bound = ExpBound.getSpellingLoc().getLocWithOffset(DecBound.second); 148 return; 149 } 150 while (Bound.isMacroID()) { 151 SourceRange Exp = SM.getImmediateExpansionRange(Bound).getAsRange(); 152 if (Exp.getBegin() == ExpMacro.getExpansionLocStart()) { 153 // Case B: bounds become the macro call itself. 154 Bound = (&Bound == &Prev) ? Exp.getBegin() : Exp.getEnd(); 155 return; 156 } 157 // Either case C, or expansion location will later find case B. 158 // We choose the upper bound for Prev and the lower one for Next: 159 // ID(prev) target ID(next) 160 // ^ ^ 161 // new-prev new-next 162 Bound = (&Bound == &Prev) ? Exp.getEnd() : Exp.getBegin(); 163 } 164 }; 165 AdjustBound(Prev); 166 AdjustBound(Next); 167 } 168 169 // In all remaining cases we need the full containing macros. 170 // If this overlaps Prev or Next, then no range is possible. 171 SourceRange Candidate = 172 SM.getExpansionRange(SourceRange(First, Last)).getAsRange(); 173 auto DecFirst = SM.getDecomposedExpansionLoc(Candidate.getBegin()); 174 auto DecLast = SM.getDecomposedLoc(Candidate.getEnd()); 175 // Can end up in the wrong file due to bad input or token-pasting shenanigans. 176 if (Candidate.isInvalid() || DecFirst.first != TargetFile || DecLast.first != TargetFile) 177 return SourceRange(); 178 // Check bounds, which may still be inside macros. 179 if (Prev.isValid()) { 180 auto Dec = SM.getDecomposedLoc(SM.getExpansionRange(Prev).getBegin()); 181 if (Dec.first != DecFirst.first || Dec.second >= DecFirst.second) 182 return SourceRange(); 183 } 184 if (Next.isValid()) { 185 auto Dec = SM.getDecomposedLoc(SM.getExpansionRange(Next).getEnd()); 186 if (Dec.first != DecLast.first || Dec.second <= DecLast.second) 187 return SourceRange(); 188 } 189 // Now we know that Candidate is a file range that covers [First, Last] 190 // without encroaching on {Prev, Next}. Ship it! 191 return Candidate; 192 } 193 194 } // namespace 195 196 syntax::Token::Token(SourceLocation Location, unsigned Length, 197 tok::TokenKind Kind) 198 : Location(Location), Length(Length), Kind(Kind) { 199 assert(Location.isValid()); 200 } 201 202 syntax::Token::Token(const clang::Token &T) 203 : Token(T.getLocation(), T.getLength(), T.getKind()) { 204 assert(!T.isAnnotation()); 205 } 206 207 llvm::StringRef syntax::Token::text(const SourceManager &SM) const { 208 bool Invalid = false; 209 const char *Start = SM.getCharacterData(location(), &Invalid); 210 assert(!Invalid); 211 return llvm::StringRef(Start, length()); 212 } 213 214 FileRange syntax::Token::range(const SourceManager &SM) const { 215 assert(location().isFileID() && "must be a spelled token"); 216 FileID File; 217 unsigned StartOffset; 218 std::tie(File, StartOffset) = SM.getDecomposedLoc(location()); 219 return FileRange(File, StartOffset, StartOffset + length()); 220 } 221 222 FileRange syntax::Token::range(const SourceManager &SM, 223 const syntax::Token &First, 224 const syntax::Token &Last) { 225 auto F = First.range(SM); 226 auto L = Last.range(SM); 227 assert(F.file() == L.file() && "tokens from different files"); 228 assert((F == L || F.endOffset() <= L.beginOffset()) && 229 "wrong order of tokens"); 230 return FileRange(F.file(), F.beginOffset(), L.endOffset()); 231 } 232 233 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) { 234 return OS << T.str(); 235 } 236 237 FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset) 238 : File(File), Begin(BeginOffset), End(EndOffset) { 239 assert(File.isValid()); 240 assert(BeginOffset <= EndOffset); 241 } 242 243 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 244 unsigned Length) { 245 assert(BeginLoc.isValid()); 246 assert(BeginLoc.isFileID()); 247 248 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 249 End = Begin + Length; 250 } 251 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc, 252 SourceLocation EndLoc) { 253 assert(BeginLoc.isValid()); 254 assert(BeginLoc.isFileID()); 255 assert(EndLoc.isValid()); 256 assert(EndLoc.isFileID()); 257 assert(SM.getFileID(BeginLoc) == SM.getFileID(EndLoc)); 258 assert(SM.getFileOffset(BeginLoc) <= SM.getFileOffset(EndLoc)); 259 260 std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc); 261 End = SM.getFileOffset(EndLoc); 262 } 263 264 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, 265 const FileRange &R) { 266 return OS << llvm::formatv("FileRange(file = {0}, offsets = {1}-{2})", 267 R.file().getHashValue(), R.beginOffset(), 268 R.endOffset()); 269 } 270 271 llvm::StringRef FileRange::text(const SourceManager &SM) const { 272 bool Invalid = false; 273 StringRef Text = SM.getBufferData(File, &Invalid); 274 if (Invalid) 275 return ""; 276 assert(Begin <= Text.size()); 277 assert(End <= Text.size()); 278 return Text.substr(Begin, length()); 279 } 280 281 void TokenBuffer::indexExpandedTokens() { 282 // No-op if the index is already created. 283 if (!ExpandedTokIndex.empty()) 284 return; 285 ExpandedTokIndex.reserve(ExpandedTokens.size()); 286 // Index ExpandedTokens for faster lookups by SourceLocation. 287 for (size_t I = 0, E = ExpandedTokens.size(); I != E; ++I) { 288 SourceLocation Loc = ExpandedTokens[I].location(); 289 if (Loc.isValid()) 290 ExpandedTokIndex[Loc] = I; 291 } 292 } 293 294 llvm::ArrayRef<syntax::Token> TokenBuffer::expandedTokens(SourceRange R) const { 295 if (R.isInvalid()) 296 return {}; 297 if (!ExpandedTokIndex.empty()) { 298 // Quick lookup if `R` is a token range. 299 // This is a huge win since majority of the users use ranges provided by an 300 // AST. Ranges in AST are token ranges from expanded token stream. 301 const auto B = ExpandedTokIndex.find(R.getBegin()); 302 const auto E = ExpandedTokIndex.find(R.getEnd()); 303 if (B != ExpandedTokIndex.end() && E != ExpandedTokIndex.end()) { 304 const Token *L = ExpandedTokens.data() + B->getSecond(); 305 // Add 1 to End to make a half-open range. 306 const Token *R = ExpandedTokens.data() + E->getSecond() + 1; 307 if (L > R) 308 return {}; 309 return {L, R}; 310 } 311 } 312 // Slow case. Use `isBeforeInTranslationUnit` to binary search for the 313 // required range. 314 return getTokensCovering(expandedTokens(), R, *SourceMgr); 315 } 316 317 CharSourceRange FileRange::toCharRange(const SourceManager &SM) const { 318 return CharSourceRange( 319 SourceRange(SM.getComposedLoc(File, Begin), SM.getComposedLoc(File, End)), 320 /*IsTokenRange=*/false); 321 } 322 323 std::pair<const syntax::Token *, const TokenBuffer::Mapping *> 324 TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const { 325 assert(Expanded); 326 assert(ExpandedTokens.data() <= Expanded && 327 Expanded < ExpandedTokens.data() + ExpandedTokens.size()); 328 329 auto FileIt = Files.find( 330 SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location()))); 331 assert(FileIt != Files.end() && "no file for an expanded token"); 332 333 const MarkedFile &File = FileIt->second; 334 335 unsigned ExpandedIndex = Expanded - ExpandedTokens.data(); 336 // Find the first mapping that produced tokens after \p Expanded. 337 auto It = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 338 return M.BeginExpanded <= ExpandedIndex; 339 }); 340 // Our token could only be produced by the previous mapping. 341 if (It == File.Mappings.begin()) { 342 // No previous mapping, no need to modify offsets. 343 return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded], 344 /*Mapping=*/nullptr}; 345 } 346 --It; // 'It' now points to last mapping that started before our token. 347 348 // Check if the token is part of the mapping. 349 if (ExpandedIndex < It->EndExpanded) 350 return {&File.SpelledTokens[It->BeginSpelled], /*Mapping=*/&*It}; 351 352 // Not part of the mapping, use the index from previous mapping to compute the 353 // corresponding spelled token. 354 return { 355 &File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)], 356 /*Mapping=*/nullptr}; 357 } 358 359 const TokenBuffer::Mapping * 360 TokenBuffer::mappingStartingBeforeSpelled(const MarkedFile &F, 361 const syntax::Token *Spelled) { 362 assert(F.SpelledTokens.data() <= Spelled); 363 unsigned SpelledI = Spelled - F.SpelledTokens.data(); 364 assert(SpelledI < F.SpelledTokens.size()); 365 366 auto It = llvm::partition_point(F.Mappings, [SpelledI](const Mapping &M) { 367 return M.BeginSpelled <= SpelledI; 368 }); 369 if (It == F.Mappings.begin()) 370 return nullptr; 371 --It; 372 return &*It; 373 } 374 375 llvm::SmallVector<llvm::ArrayRef<syntax::Token>, 1> 376 TokenBuffer::expandedForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const { 377 if (Spelled.empty()) 378 return {}; 379 const auto &File = fileForSpelled(Spelled); 380 381 auto *FrontMapping = mappingStartingBeforeSpelled(File, &Spelled.front()); 382 unsigned SpelledFrontI = &Spelled.front() - File.SpelledTokens.data(); 383 assert(SpelledFrontI < File.SpelledTokens.size()); 384 unsigned ExpandedBegin; 385 if (!FrontMapping) { 386 // No mapping that starts before the first token of Spelled, we don't have 387 // to modify offsets. 388 ExpandedBegin = File.BeginExpanded + SpelledFrontI; 389 } else if (SpelledFrontI < FrontMapping->EndSpelled) { 390 // This mapping applies to Spelled tokens. 391 if (SpelledFrontI != FrontMapping->BeginSpelled) { 392 // Spelled tokens don't cover the entire mapping, returning empty result. 393 return {}; // FIXME: support macro arguments. 394 } 395 // Spelled tokens start at the beginning of this mapping. 396 ExpandedBegin = FrontMapping->BeginExpanded; 397 } else { 398 // Spelled tokens start after the mapping ends (they start in the hole 399 // between 2 mappings, or between a mapping and end of the file). 400 ExpandedBegin = 401 FrontMapping->EndExpanded + (SpelledFrontI - FrontMapping->EndSpelled); 402 } 403 404 auto *BackMapping = mappingStartingBeforeSpelled(File, &Spelled.back()); 405 unsigned SpelledBackI = &Spelled.back() - File.SpelledTokens.data(); 406 unsigned ExpandedEnd; 407 if (!BackMapping) { 408 // No mapping that starts before the last token of Spelled, we don't have to 409 // modify offsets. 410 ExpandedEnd = File.BeginExpanded + SpelledBackI + 1; 411 } else if (SpelledBackI < BackMapping->EndSpelled) { 412 // This mapping applies to Spelled tokens. 413 if (SpelledBackI + 1 != BackMapping->EndSpelled) { 414 // Spelled tokens don't cover the entire mapping, returning empty result. 415 return {}; // FIXME: support macro arguments. 416 } 417 ExpandedEnd = BackMapping->EndExpanded; 418 } else { 419 // Spelled tokens end after the mapping ends. 420 ExpandedEnd = 421 BackMapping->EndExpanded + (SpelledBackI - BackMapping->EndSpelled) + 1; 422 } 423 424 assert(ExpandedBegin < ExpandedTokens.size()); 425 assert(ExpandedEnd < ExpandedTokens.size()); 426 // Avoid returning empty ranges. 427 if (ExpandedBegin == ExpandedEnd) 428 return {}; 429 return {llvm::makeArrayRef(ExpandedTokens.data() + ExpandedBegin, 430 ExpandedTokens.data() + ExpandedEnd)}; 431 } 432 433 llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const { 434 auto It = Files.find(FID); 435 assert(It != Files.end()); 436 return It->second.SpelledTokens; 437 } 438 439 const syntax::Token *TokenBuffer::spelledTokenAt(SourceLocation Loc) const { 440 assert(Loc.isFileID()); 441 const auto *Tok = llvm::partition_point( 442 spelledTokens(SourceMgr->getFileID(Loc)), 443 [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 444 if (!Tok || Tok->location() != Loc) 445 return nullptr; 446 return Tok; 447 } 448 449 std::string TokenBuffer::Mapping::str() const { 450 return std::string( 451 llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})", 452 BeginSpelled, EndSpelled, BeginExpanded, EndExpanded)); 453 } 454 455 llvm::Optional<llvm::ArrayRef<syntax::Token>> 456 TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const { 457 // Mapping an empty range is ambiguous in case of empty mappings at either end 458 // of the range, bail out in that case. 459 if (Expanded.empty()) 460 return llvm::None; 461 const syntax::Token *First = &Expanded.front(); 462 const syntax::Token *Last = &Expanded.back(); 463 auto [FirstSpelled, FirstMapping] = spelledForExpandedToken(First); 464 auto [LastSpelled, LastMapping] = spelledForExpandedToken(Last); 465 466 FileID FID = SourceMgr->getFileID(FirstSpelled->location()); 467 // FIXME: Handle multi-file changes by trying to map onto a common root. 468 if (FID != SourceMgr->getFileID(LastSpelled->location())) 469 return llvm::None; 470 471 const MarkedFile &File = Files.find(FID)->second; 472 473 // If the range is within one macro argument, the result may be only part of a 474 // Mapping. We must use the general (SourceManager-based) algorithm. 475 if (FirstMapping && FirstMapping == LastMapping && 476 SourceMgr->isMacroArgExpansion(First->location()) && 477 SourceMgr->isMacroArgExpansion(Last->location())) { 478 // We use excluded Prev/Next token for bounds checking. 479 SourceLocation Prev = (First == &ExpandedTokens.front()) 480 ? SourceLocation() 481 : (First - 1)->location(); 482 SourceLocation Next = (Last == &ExpandedTokens.back()) 483 ? SourceLocation() 484 : (Last + 1)->location(); 485 SourceRange Range = spelledForExpandedSlow( 486 First->location(), Last->location(), Prev, Next, FID, *SourceMgr); 487 if (Range.isInvalid()) 488 return llvm::None; 489 return getTokensCovering(File.SpelledTokens, Range, *SourceMgr); 490 } 491 492 // Otherwise, use the fast version based on Mappings. 493 // Do not allow changes that doesn't cover full expansion. 494 unsigned FirstExpanded = Expanded.begin() - ExpandedTokens.data(); 495 unsigned LastExpanded = Expanded.end() - ExpandedTokens.data(); 496 if (FirstMapping && FirstExpanded != FirstMapping->BeginExpanded) 497 return llvm::None; 498 if (LastMapping && LastMapping->EndExpanded != LastExpanded) 499 return llvm::None; 500 return llvm::makeArrayRef( 501 FirstMapping ? File.SpelledTokens.data() + FirstMapping->BeginSpelled 502 : FirstSpelled, 503 LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled 504 : LastSpelled + 1); 505 } 506 507 TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F, 508 const Mapping &M) const { 509 Expansion E; 510 E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled, 511 F.SpelledTokens.data() + M.EndSpelled); 512 E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded, 513 ExpandedTokens.data() + M.EndExpanded); 514 return E; 515 } 516 517 const TokenBuffer::MarkedFile & 518 TokenBuffer::fileForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const { 519 assert(!Spelled.empty()); 520 assert(Spelled.front().location().isFileID() && "not a spelled token"); 521 auto FileIt = Files.find(SourceMgr->getFileID(Spelled.front().location())); 522 assert(FileIt != Files.end() && "file not tracked by token buffer"); 523 const auto &File = FileIt->second; 524 assert(File.SpelledTokens.data() <= Spelled.data() && 525 Spelled.end() <= 526 (File.SpelledTokens.data() + File.SpelledTokens.size()) && 527 "Tokens not in spelled range"); 528 #ifndef NDEBUG 529 auto T1 = Spelled.back().location(); 530 auto T2 = File.SpelledTokens.back().location(); 531 assert(T1 == T2 || sourceManager().isBeforeInTranslationUnit(T1, T2)); 532 #endif 533 return File; 534 } 535 536 llvm::Optional<TokenBuffer::Expansion> 537 TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const { 538 assert(Spelled); 539 const auto &File = fileForSpelled(*Spelled); 540 541 unsigned SpelledIndex = Spelled - File.SpelledTokens.data(); 542 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 543 return M.BeginSpelled < SpelledIndex; 544 }); 545 if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex) 546 return llvm::None; 547 return makeExpansion(File, *M); 548 } 549 550 std::vector<TokenBuffer::Expansion> TokenBuffer::expansionsOverlapping( 551 llvm::ArrayRef<syntax::Token> Spelled) const { 552 if (Spelled.empty()) 553 return {}; 554 const auto &File = fileForSpelled(Spelled); 555 556 // Find the first overlapping range, and then copy until we stop overlapping. 557 unsigned SpelledBeginIndex = Spelled.begin() - File.SpelledTokens.data(); 558 unsigned SpelledEndIndex = Spelled.end() - File.SpelledTokens.data(); 559 auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) { 560 return M.EndSpelled <= SpelledBeginIndex; 561 }); 562 std::vector<TokenBuffer::Expansion> Expansions; 563 for (; M != File.Mappings.end() && M->BeginSpelled < SpelledEndIndex; ++M) 564 Expansions.push_back(makeExpansion(File, *M)); 565 return Expansions; 566 } 567 568 llvm::ArrayRef<syntax::Token> 569 syntax::spelledTokensTouching(SourceLocation Loc, 570 llvm::ArrayRef<syntax::Token> Tokens) { 571 assert(Loc.isFileID()); 572 573 auto *Right = llvm::partition_point( 574 Tokens, [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); 575 bool AcceptRight = Right != Tokens.end() && Right->location() <= Loc; 576 bool AcceptLeft = 577 Right != Tokens.begin() && (Right - 1)->endLocation() >= Loc; 578 return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0), 579 Right + (AcceptRight ? 1 : 0)); 580 } 581 582 llvm::ArrayRef<syntax::Token> 583 syntax::spelledTokensTouching(SourceLocation Loc, 584 const syntax::TokenBuffer &Tokens) { 585 return spelledTokensTouching( 586 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 587 } 588 589 const syntax::Token * 590 syntax::spelledIdentifierTouching(SourceLocation Loc, 591 llvm::ArrayRef<syntax::Token> Tokens) { 592 for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) { 593 if (Tok.kind() == tok::identifier) 594 return &Tok; 595 } 596 return nullptr; 597 } 598 599 const syntax::Token * 600 syntax::spelledIdentifierTouching(SourceLocation Loc, 601 const syntax::TokenBuffer &Tokens) { 602 return spelledIdentifierTouching( 603 Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc))); 604 } 605 606 std::vector<const syntax::Token *> 607 TokenBuffer::macroExpansions(FileID FID) const { 608 auto FileIt = Files.find(FID); 609 assert(FileIt != Files.end() && "file not tracked by token buffer"); 610 auto &File = FileIt->second; 611 std::vector<const syntax::Token *> Expansions; 612 auto &Spelled = File.SpelledTokens; 613 for (auto Mapping : File.Mappings) { 614 const syntax::Token *Token = &Spelled[Mapping.BeginSpelled]; 615 if (Token->kind() == tok::TokenKind::identifier) 616 Expansions.push_back(Token); 617 } 618 return Expansions; 619 } 620 621 std::vector<syntax::Token> syntax::tokenize(const FileRange &FR, 622 const SourceManager &SM, 623 const LangOptions &LO) { 624 std::vector<syntax::Token> Tokens; 625 IdentifierTable Identifiers(LO); 626 auto AddToken = [&](clang::Token T) { 627 // Fill the proper token kind for keywords, etc. 628 if (T.getKind() == tok::raw_identifier && !T.needsCleaning() && 629 !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases. 630 clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier()); 631 T.setIdentifierInfo(&II); 632 T.setKind(II.getTokenID()); 633 } 634 Tokens.push_back(syntax::Token(T)); 635 }; 636 637 auto SrcBuffer = SM.getBufferData(FR.file()); 638 Lexer L(SM.getLocForStartOfFile(FR.file()), LO, SrcBuffer.data(), 639 SrcBuffer.data() + FR.beginOffset(), 640 // We can't make BufEnd point to FR.endOffset, as Lexer requires a 641 // null terminated buffer. 642 SrcBuffer.data() + SrcBuffer.size()); 643 644 clang::Token T; 645 while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < FR.endOffset()) 646 AddToken(T); 647 // LexFromRawLexer returns true when it parses the last token of the file, add 648 // it iff it starts within the range we are interested in. 649 if (SM.getFileOffset(T.getLocation()) < FR.endOffset()) 650 AddToken(T); 651 return Tokens; 652 } 653 654 std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM, 655 const LangOptions &LO) { 656 return tokenize(syntax::FileRange(FID, 0, SM.getFileIDSize(FID)), SM, LO); 657 } 658 659 /// Records information reqired to construct mappings for the token buffer that 660 /// we are collecting. 661 class TokenCollector::CollectPPExpansions : public PPCallbacks { 662 public: 663 CollectPPExpansions(TokenCollector &C) : Collector(&C) {} 664 665 /// Disabled instance will stop reporting anything to TokenCollector. 666 /// This ensures that uses of the preprocessor after TokenCollector::consume() 667 /// is called do not access the (possibly invalid) collector instance. 668 void disable() { Collector = nullptr; } 669 670 void MacroExpands(const clang::Token &MacroNameTok, const MacroDefinition &MD, 671 SourceRange Range, const MacroArgs *Args) override { 672 if (!Collector) 673 return; 674 const auto &SM = Collector->PP.getSourceManager(); 675 // Only record top-level expansions that directly produce expanded tokens. 676 // This excludes those where: 677 // - the macro use is inside a macro body, 678 // - the macro appears in an argument to another macro. 679 // However macro expansion isn't really a tree, it's token rewrite rules, 680 // so there are other cases, e.g. 681 // #define B(X) X 682 // #define A 1 + B 683 // A(2) 684 // Both A and B produce expanded tokens, though the macro name 'B' comes 685 // from an expansion. The best we can do is merge the mappings for both. 686 687 // The *last* token of any top-level macro expansion must be in a file. 688 // (In the example above, see the closing paren of the expansion of B). 689 if (!Range.getEnd().isFileID()) 690 return; 691 // If there's a current expansion that encloses this one, this one can't be 692 // top-level. 693 if (LastExpansionEnd.isValid() && 694 !SM.isBeforeInTranslationUnit(LastExpansionEnd, Range.getEnd())) 695 return; 696 697 // If the macro invocation (B) starts in a macro (A) but ends in a file, 698 // we'll create a merged mapping for A + B by overwriting the endpoint for 699 // A's startpoint. 700 if (!Range.getBegin().isFileID()) { 701 Range.setBegin(SM.getExpansionLoc(Range.getBegin())); 702 assert(Collector->Expansions.count(Range.getBegin()) && 703 "Overlapping macros should have same expansion location"); 704 } 705 706 Collector->Expansions[Range.getBegin()] = Range.getEnd(); 707 LastExpansionEnd = Range.getEnd(); 708 } 709 // FIXME: handle directives like #pragma, #include, etc. 710 private: 711 TokenCollector *Collector; 712 /// Used to detect recursive macro expansions. 713 SourceLocation LastExpansionEnd; 714 }; 715 716 /// Fills in the TokenBuffer by tracing the run of a preprocessor. The 717 /// implementation tracks the tokens, macro expansions and directives coming 718 /// from the preprocessor and: 719 /// - for each token, figures out if it is a part of an expanded token stream, 720 /// spelled token stream or both. Stores the tokens appropriately. 721 /// - records mappings from the spelled to expanded token ranges, e.g. for macro 722 /// expansions. 723 /// FIXME: also properly record: 724 /// - #include directives, 725 /// - #pragma, #line and other PP directives, 726 /// - skipped pp regions, 727 /// - ... 728 729 TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) { 730 // Collect the expanded token stream during preprocessing. 731 PP.setTokenWatcher([this](const clang::Token &T) { 732 if (T.isAnnotation()) 733 return; 734 DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs() 735 << "Token: " 736 << syntax::Token(T).dumpForTests( 737 this->PP.getSourceManager()) 738 << "\n" 739 740 ); 741 Expanded.push_back(syntax::Token(T)); 742 }); 743 // And locations of macro calls, to properly recover boundaries of those in 744 // case of empty expansions. 745 auto CB = std::make_unique<CollectPPExpansions>(*this); 746 this->Collector = CB.get(); 747 PP.addPPCallbacks(std::move(CB)); 748 } 749 750 /// Builds mappings and spelled tokens in the TokenBuffer based on the expanded 751 /// token stream. 752 class TokenCollector::Builder { 753 public: 754 Builder(std::vector<syntax::Token> Expanded, PPExpansions CollectedExpansions, 755 const SourceManager &SM, const LangOptions &LangOpts) 756 : Result(SM), CollectedExpansions(std::move(CollectedExpansions)), SM(SM), 757 LangOpts(LangOpts) { 758 Result.ExpandedTokens = std::move(Expanded); 759 } 760 761 TokenBuffer build() && { 762 assert(!Result.ExpandedTokens.empty()); 763 assert(Result.ExpandedTokens.back().kind() == tok::eof); 764 765 // Tokenize every file that contributed tokens to the expanded stream. 766 buildSpelledTokens(); 767 768 // The expanded token stream consists of runs of tokens that came from 769 // the same source (a macro expansion, part of a file etc). 770 // Between these runs are the logical positions of spelled tokens that 771 // didn't expand to anything. 772 while (NextExpanded < Result.ExpandedTokens.size() - 1 /* eof */) { 773 // Create empty mappings for spelled tokens that expanded to nothing here. 774 // May advance NextSpelled, but NextExpanded is unchanged. 775 discard(); 776 // Create mapping for a contiguous run of expanded tokens. 777 // Advances NextExpanded past the run, and NextSpelled accordingly. 778 unsigned OldPosition = NextExpanded; 779 advance(); 780 if (NextExpanded == OldPosition) 781 diagnoseAdvanceFailure(); 782 } 783 // If any tokens remain in any of the files, they didn't expand to anything. 784 // Create empty mappings up until the end of the file. 785 for (const auto &File : Result.Files) 786 discard(File.first); 787 788 #ifndef NDEBUG 789 for (auto &pair : Result.Files) { 790 auto &mappings = pair.second.Mappings; 791 assert(llvm::is_sorted(mappings, [](const TokenBuffer::Mapping &M1, 792 const TokenBuffer::Mapping &M2) { 793 return M1.BeginSpelled < M2.BeginSpelled && 794 M1.EndSpelled < M2.EndSpelled && 795 M1.BeginExpanded < M2.BeginExpanded && 796 M1.EndExpanded < M2.EndExpanded; 797 })); 798 } 799 #endif 800 801 return std::move(Result); 802 } 803 804 private: 805 // Consume a sequence of spelled tokens that didn't expand to anything. 806 // In the simplest case, skips spelled tokens until finding one that produced 807 // the NextExpanded token, and creates an empty mapping for them. 808 // If Drain is provided, skips remaining tokens from that file instead. 809 void discard(llvm::Optional<FileID> Drain = llvm::None) { 810 SourceLocation Target = 811 Drain ? SM.getLocForEndOfFile(*Drain) 812 : SM.getExpansionLoc( 813 Result.ExpandedTokens[NextExpanded].location()); 814 FileID File = SM.getFileID(Target); 815 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 816 auto &NextSpelled = this->NextSpelled[File]; 817 818 TokenBuffer::Mapping Mapping; 819 Mapping.BeginSpelled = NextSpelled; 820 // When dropping trailing tokens from a file, the empty mapping should 821 // be positioned within the file's expanded-token range (at the end). 822 Mapping.BeginExpanded = Mapping.EndExpanded = 823 Drain ? Result.Files[*Drain].EndExpanded : NextExpanded; 824 // We may want to split into several adjacent empty mappings. 825 // FlushMapping() emits the current mapping and starts a new one. 826 auto FlushMapping = [&, this] { 827 Mapping.EndSpelled = NextSpelled; 828 if (Mapping.BeginSpelled != Mapping.EndSpelled) 829 Result.Files[File].Mappings.push_back(Mapping); 830 Mapping.BeginSpelled = NextSpelled; 831 }; 832 833 while (NextSpelled < SpelledTokens.size() && 834 SpelledTokens[NextSpelled].location() < Target) { 835 // If we know mapping bounds at [NextSpelled, KnownEnd] (macro expansion) 836 // then we want to partition our (empty) mapping. 837 // [Start, NextSpelled) [NextSpelled, KnownEnd] (KnownEnd, Target) 838 SourceLocation KnownEnd = 839 CollectedExpansions.lookup(SpelledTokens[NextSpelled].location()); 840 if (KnownEnd.isValid()) { 841 FlushMapping(); // Emits [Start, NextSpelled) 842 while (NextSpelled < SpelledTokens.size() && 843 SpelledTokens[NextSpelled].location() <= KnownEnd) 844 ++NextSpelled; 845 FlushMapping(); // Emits [NextSpelled, KnownEnd] 846 // Now the loop contitues and will emit (KnownEnd, Target). 847 } else { 848 ++NextSpelled; 849 } 850 } 851 FlushMapping(); 852 } 853 854 // Consumes the NextExpanded token and others that are part of the same run. 855 // Increases NextExpanded and NextSpelled by at least one, and adds a mapping 856 // (unless this is a run of file tokens, which we represent with no mapping). 857 void advance() { 858 const syntax::Token &Tok = Result.ExpandedTokens[NextExpanded]; 859 SourceLocation Expansion = SM.getExpansionLoc(Tok.location()); 860 FileID File = SM.getFileID(Expansion); 861 const auto &SpelledTokens = Result.Files[File].SpelledTokens; 862 auto &NextSpelled = this->NextSpelled[File]; 863 864 if (Tok.location().isFileID()) { 865 // A run of file tokens continues while the expanded/spelled tokens match. 866 while (NextSpelled < SpelledTokens.size() && 867 NextExpanded < Result.ExpandedTokens.size() && 868 SpelledTokens[NextSpelled].location() == 869 Result.ExpandedTokens[NextExpanded].location()) { 870 ++NextSpelled; 871 ++NextExpanded; 872 } 873 // We need no mapping for file tokens copied to the expanded stream. 874 } else { 875 // We found a new macro expansion. We should have its spelling bounds. 876 auto End = CollectedExpansions.lookup(Expansion); 877 assert(End.isValid() && "Macro expansion wasn't captured?"); 878 879 // Mapping starts here... 880 TokenBuffer::Mapping Mapping; 881 Mapping.BeginExpanded = NextExpanded; 882 Mapping.BeginSpelled = NextSpelled; 883 // ... consumes spelled tokens within bounds we captured ... 884 while (NextSpelled < SpelledTokens.size() && 885 SpelledTokens[NextSpelled].location() <= End) 886 ++NextSpelled; 887 // ... consumes expanded tokens rooted at the same expansion ... 888 while (NextExpanded < Result.ExpandedTokens.size() && 889 SM.getExpansionLoc( 890 Result.ExpandedTokens[NextExpanded].location()) == Expansion) 891 ++NextExpanded; 892 // ... and ends here. 893 Mapping.EndExpanded = NextExpanded; 894 Mapping.EndSpelled = NextSpelled; 895 Result.Files[File].Mappings.push_back(Mapping); 896 } 897 } 898 899 // advance() is supposed to consume at least one token - if not, we crash. 900 void diagnoseAdvanceFailure() { 901 #ifndef NDEBUG 902 // Show the failed-to-map token in context. 903 for (unsigned I = (NextExpanded < 10) ? 0 : NextExpanded - 10; 904 I < NextExpanded + 5 && I < Result.ExpandedTokens.size(); ++I) { 905 const char *L = 906 (I == NextExpanded) ? "!! " : (I < NextExpanded) ? "ok " : " "; 907 llvm::errs() << L << Result.ExpandedTokens[I].dumpForTests(SM) << "\n"; 908 } 909 #endif 910 llvm_unreachable("Couldn't map expanded token to spelled tokens!"); 911 } 912 913 /// Initializes TokenBuffer::Files and fills spelled tokens and expanded 914 /// ranges for each of the files. 915 void buildSpelledTokens() { 916 for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) { 917 const auto &Tok = Result.ExpandedTokens[I]; 918 auto FID = SM.getFileID(SM.getExpansionLoc(Tok.location())); 919 auto It = Result.Files.try_emplace(FID); 920 TokenBuffer::MarkedFile &File = It.first->second; 921 922 // The eof token should not be considered part of the main-file's range. 923 File.EndExpanded = Tok.kind() == tok::eof ? I : I + 1; 924 925 if (!It.second) 926 continue; // we have seen this file before. 927 // This is the first time we see this file. 928 File.BeginExpanded = I; 929 File.SpelledTokens = tokenize(FID, SM, LangOpts); 930 } 931 } 932 933 TokenBuffer Result; 934 unsigned NextExpanded = 0; // cursor in ExpandedTokens 935 llvm::DenseMap<FileID, unsigned> NextSpelled; // cursor in SpelledTokens 936 PPExpansions CollectedExpansions; 937 const SourceManager &SM; 938 const LangOptions &LangOpts; 939 }; 940 941 TokenBuffer TokenCollector::consume() && { 942 PP.setTokenWatcher(nullptr); 943 Collector->disable(); 944 return Builder(std::move(Expanded), std::move(Expansions), 945 PP.getSourceManager(), PP.getLangOpts()) 946 .build(); 947 } 948 949 std::string syntax::Token::str() const { 950 return std::string(llvm::formatv("Token({0}, length = {1})", 951 tok::getTokenName(kind()), length())); 952 } 953 954 std::string syntax::Token::dumpForTests(const SourceManager &SM) const { 955 return std::string(llvm::formatv("Token(`{0}`, {1}, length = {2})", text(SM), 956 tok::getTokenName(kind()), length())); 957 } 958 959 std::string TokenBuffer::dumpForTests() const { 960 auto PrintToken = [this](const syntax::Token &T) -> std::string { 961 if (T.kind() == tok::eof) 962 return "<eof>"; 963 return std::string(T.text(*SourceMgr)); 964 }; 965 966 auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS, 967 llvm::ArrayRef<syntax::Token> Tokens) { 968 if (Tokens.empty()) { 969 OS << "<empty>"; 970 return; 971 } 972 OS << Tokens[0].text(*SourceMgr); 973 for (unsigned I = 1; I < Tokens.size(); ++I) { 974 if (Tokens[I].kind() == tok::eof) 975 continue; 976 OS << " " << PrintToken(Tokens[I]); 977 } 978 }; 979 980 std::string Dump; 981 llvm::raw_string_ostream OS(Dump); 982 983 OS << "expanded tokens:\n" 984 << " "; 985 // (!) we do not show '<eof>'. 986 DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back()); 987 OS << "\n"; 988 989 std::vector<FileID> Keys; 990 for (auto F : Files) 991 Keys.push_back(F.first); 992 llvm::sort(Keys); 993 994 for (FileID ID : Keys) { 995 const MarkedFile &File = Files.find(ID)->second; 996 auto *Entry = SourceMgr->getFileEntryForID(ID); 997 if (!Entry) 998 continue; // Skip builtin files. 999 OS << llvm::formatv("file '{0}'\n", Entry->getName()) 1000 << " spelled tokens:\n" 1001 << " "; 1002 DumpTokens(OS, File.SpelledTokens); 1003 OS << "\n"; 1004 1005 if (File.Mappings.empty()) { 1006 OS << " no mappings.\n"; 1007 continue; 1008 } 1009 OS << " mappings:\n"; 1010 for (auto &M : File.Mappings) { 1011 OS << llvm::formatv( 1012 " ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n", 1013 PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled, 1014 M.EndSpelled == File.SpelledTokens.size() 1015 ? "<eof>" 1016 : PrintToken(File.SpelledTokens[M.EndSpelled]), 1017 M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]), 1018 M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]), 1019 M.EndExpanded); 1020 } 1021 } 1022 return Dump; 1023 } 1024