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