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