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