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