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/Preprocessor.h"
18 #include "clang/Lex/Token.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <iterator>
30 #include <string>
31 #include <utility>
32 #include <vector>
33 
34 using namespace clang;
35 using namespace clang::syntax;
36 
37 syntax::Token::Token(const clang::Token &T)
38     : Token(T.getLocation(), T.getLength(), T.getKind()) {
39   assert(!T.isAnnotation());
40 }
41 
42 llvm::StringRef syntax::Token::text(const SourceManager &SM) const {
43   bool Invalid = false;
44   const char *Start = SM.getCharacterData(location(), &Invalid);
45   assert(!Invalid);
46   return llvm::StringRef(Start, length());
47 }
48 
49 FileRange syntax::Token::range(const SourceManager &SM) const {
50   assert(location().isFileID() && "must be a spelled token");
51   FileID File;
52   unsigned StartOffset;
53   std::tie(File, StartOffset) = SM.getDecomposedLoc(location());
54   return FileRange(File, StartOffset, StartOffset + length());
55 }
56 
57 FileRange syntax::Token::range(const SourceManager &SM,
58                                const syntax::Token &First,
59                                const syntax::Token &Last) {
60   auto F = First.range(SM);
61   auto L = Last.range(SM);
62   assert(F.file() == L.file() && "tokens from different files");
63   assert(F.endOffset() <= L.beginOffset() && "wrong order of tokens");
64   return FileRange(F.file(), F.beginOffset(), L.endOffset());
65 }
66 
67 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) {
68   return OS << T.str();
69 }
70 
71 FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset)
72     : File(File), Begin(BeginOffset), End(EndOffset) {
73       assert(File.isValid());
74       assert(BeginOffset <= EndOffset);
75 }
76 
77 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc,
78                      unsigned Length) {
79   assert(BeginLoc.isValid());
80   assert(BeginLoc.isFileID());
81 
82   std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc);
83   End = Begin + Length;
84 }
85 FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc,
86                      SourceLocation EndLoc) {
87   assert(BeginLoc.isValid());
88   assert(BeginLoc.isFileID());
89   assert(EndLoc.isValid());
90   assert(EndLoc.isFileID());
91   assert(SM.getFileID(BeginLoc) == SM.getFileID(EndLoc));
92   assert(SM.getFileOffset(BeginLoc) <= SM.getFileOffset(EndLoc));
93 
94   std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc);
95   End = SM.getFileOffset(EndLoc);
96 }
97 
98 llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS,
99                                       const FileRange &R) {
100   return OS << llvm::formatv("FileRange(file = {0}, offsets = {1}-{2})",
101                              R.file().getHashValue(), R.beginOffset(),
102                              R.endOffset());
103 }
104 
105 llvm::StringRef FileRange::text(const SourceManager &SM) const {
106   bool Invalid = false;
107   StringRef Text = SM.getBufferData(File, &Invalid);
108   if (Invalid)
109     return "";
110   assert(Begin <= Text.size());
111   assert(End <= Text.size());
112   return Text.substr(Begin, length());
113 }
114 
115 std::pair<const syntax::Token *, const TokenBuffer::Mapping *>
116 TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const {
117   assert(Expanded);
118   assert(ExpandedTokens.data() <= Expanded &&
119          Expanded < ExpandedTokens.data() + ExpandedTokens.size());
120 
121   auto FileIt = Files.find(
122       SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location())));
123   assert(FileIt != Files.end() && "no file for an expanded token");
124 
125   const MarkedFile &File = FileIt->second;
126 
127   unsigned ExpandedIndex = Expanded - ExpandedTokens.data();
128   // Find the first mapping that produced tokens after \p Expanded.
129   auto It = llvm::bsearch(File.Mappings, [&](const Mapping &M) {
130     return ExpandedIndex < M.BeginExpanded;
131   });
132   // Our token could only be produced by the previous mapping.
133   if (It == File.Mappings.begin()) {
134     // No previous mapping, no need to modify offsets.
135     return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded], nullptr};
136   }
137   --It; // 'It' now points to last mapping that started before our token.
138 
139   // Check if the token is part of the mapping.
140   if (ExpandedIndex < It->EndExpanded)
141     return {&File.SpelledTokens[It->BeginSpelled], /*Mapping*/ &*It};
142 
143   // Not part of the mapping, use the index from previous mapping to compute the
144   // corresponding spelled token.
145   return {
146       &File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)],
147       /*Mapping*/ nullptr};
148 }
149 
150 llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const {
151   auto It = Files.find(FID);
152   assert(It != Files.end());
153   return It->second.SpelledTokens;
154 }
155 
156 std::string TokenBuffer::Mapping::str() const {
157   return llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})",
158                        BeginSpelled, EndSpelled, BeginExpanded, EndExpanded);
159 }
160 
161 llvm::Optional<llvm::ArrayRef<syntax::Token>>
162 TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const {
163   // Mapping an empty range is ambiguous in case of empty mappings at either end
164   // of the range, bail out in that case.
165   if (Expanded.empty())
166     return llvm::None;
167 
168   // FIXME: also allow changes uniquely mapping to macro arguments.
169 
170   const syntax::Token *BeginSpelled;
171   const Mapping *BeginMapping;
172   std::tie(BeginSpelled, BeginMapping) =
173       spelledForExpandedToken(&Expanded.front());
174 
175   const syntax::Token *LastSpelled;
176   const Mapping *LastMapping;
177   std::tie(LastSpelled, LastMapping) =
178       spelledForExpandedToken(&Expanded.back());
179 
180   FileID FID = SourceMgr->getFileID(BeginSpelled->location());
181   // FIXME: Handle multi-file changes by trying to map onto a common root.
182   if (FID != SourceMgr->getFileID(LastSpelled->location()))
183     return llvm::None;
184 
185   const MarkedFile &File = Files.find(FID)->second;
186 
187   // Do not allow changes that cross macro expansion boundaries.
188   unsigned BeginExpanded = Expanded.begin() - ExpandedTokens.data();
189   unsigned EndExpanded = Expanded.end() - ExpandedTokens.data();
190   if (BeginMapping && BeginMapping->BeginExpanded < BeginExpanded)
191     return llvm::None;
192   if (LastMapping && EndExpanded < LastMapping->EndExpanded)
193     return llvm::None;
194   // All is good, return the result.
195   return llvm::makeArrayRef(
196       BeginMapping ? File.SpelledTokens.data() + BeginMapping->BeginSpelled
197                    : BeginSpelled,
198       LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled
199                   : LastSpelled + 1);
200 }
201 
202 std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM,
203                                             const LangOptions &LO) {
204   std::vector<syntax::Token> Tokens;
205   IdentifierTable Identifiers(LO);
206   auto AddToken = [&](clang::Token T) {
207     // Fill the proper token kind for keywords, etc.
208     if (T.getKind() == tok::raw_identifier && !T.needsCleaning() &&
209         !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases.
210       clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier());
211       T.setIdentifierInfo(&II);
212       T.setKind(II.getTokenID());
213     }
214     Tokens.push_back(syntax::Token(T));
215   };
216 
217   Lexer L(FID, SM.getBuffer(FID), SM, LO);
218 
219   clang::Token T;
220   while (!L.LexFromRawLexer(T))
221     AddToken(T);
222   // 'eof' is only the last token if the input is null-terminated. Never store
223   // it, for consistency.
224   if (T.getKind() != tok::eof)
225     AddToken(T);
226   return Tokens;
227 }
228 
229 /// Fills in the TokenBuffer by tracing the run of a preprocessor. The
230 /// implementation tracks the tokens, macro expansions and directives coming
231 /// from the preprocessor and:
232 /// - for each token, figures out if it is a part of an expanded token stream,
233 ///   spelled token stream or both. Stores the tokens appropriately.
234 /// - records mappings from the spelled to expanded token ranges, e.g. for macro
235 ///   expansions.
236 /// FIXME: also properly record:
237 ///          - #include directives,
238 ///          - #pragma, #line and other PP directives,
239 ///          - skipped pp regions,
240 ///          - ...
241 
242 TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) {
243   // Collect the expanded token stream during preprocessing.
244   PP.setTokenWatcher([this](const clang::Token &T) {
245     if (T.isAnnotation())
246       return;
247     DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs()
248                                           << "Token: "
249                                           << syntax::Token(T).dumpForTests(
250                                                  this->PP.getSourceManager())
251                                           << "\n"
252 
253     );
254     Expanded.push_back(syntax::Token(T));
255   });
256 }
257 
258 /// Builds mappings and spelled tokens in the TokenBuffer based on the expanded
259 /// token stream.
260 class TokenCollector::Builder {
261 public:
262   Builder(std::vector<syntax::Token> Expanded, const SourceManager &SM,
263           const LangOptions &LangOpts)
264       : Result(SM), SM(SM), LangOpts(LangOpts) {
265     Result.ExpandedTokens = std::move(Expanded);
266   }
267 
268   TokenBuffer build() && {
269     buildSpelledTokens();
270 
271     // Walk over expanded tokens and spelled tokens in parallel, building the
272     // mappings between those using source locations.
273 
274     // The 'eof' token is special, it is not part of spelled token stream. We
275     // handle it separately at the end.
276     assert(!Result.ExpandedTokens.empty());
277     assert(Result.ExpandedTokens.back().kind() == tok::eof);
278     for (unsigned I = 0; I < Result.ExpandedTokens.size() - 1; ++I) {
279       // (!) I might be updated by the following call.
280       processExpandedToken(I);
281     }
282 
283     // 'eof' not handled in the loop, do it here.
284     assert(SM.getMainFileID() ==
285            SM.getFileID(Result.ExpandedTokens.back().location()));
286     fillGapUntil(Result.Files[SM.getMainFileID()],
287                  Result.ExpandedTokens.back().location(),
288                  Result.ExpandedTokens.size() - 1);
289     Result.Files[SM.getMainFileID()].EndExpanded = Result.ExpandedTokens.size();
290 
291     // Some files might have unaccounted spelled tokens at the end, add an empty
292     // mapping for those as they did not have expanded counterparts.
293     fillGapsAtEndOfFiles();
294 
295     return std::move(Result);
296   }
297 
298 private:
299   /// Process the next token in an expanded stream and move corresponding
300   /// spelled tokens, record any mapping if needed.
301   /// (!) \p I will be updated if this had to skip tokens, e.g. for macros.
302   void processExpandedToken(unsigned &I) {
303     auto L = Result.ExpandedTokens[I].location();
304     if (L.isMacroID()) {
305       processMacroExpansion(SM.getExpansionRange(L), I);
306       return;
307     }
308     if (L.isFileID()) {
309       auto FID = SM.getFileID(L);
310       TokenBuffer::MarkedFile &File = Result.Files[FID];
311 
312       fillGapUntil(File, L, I);
313 
314       // Skip the token.
315       assert(File.SpelledTokens[NextSpelled[FID]].location() == L &&
316              "no corresponding token in the spelled stream");
317       ++NextSpelled[FID];
318       return;
319     }
320   }
321 
322   /// Skipped expanded and spelled tokens of a macro expansion that covers \p
323   /// SpelledRange. Add a corresponding mapping.
324   /// (!) \p I will be the index of the last token in an expansion after this
325   /// function returns.
326   void processMacroExpansion(CharSourceRange SpelledRange, unsigned &I) {
327     auto FID = SM.getFileID(SpelledRange.getBegin());
328     assert(FID == SM.getFileID(SpelledRange.getEnd()));
329     TokenBuffer::MarkedFile &File = Result.Files[FID];
330 
331     fillGapUntil(File, SpelledRange.getBegin(), I);
332 
333     TokenBuffer::Mapping M;
334     // Skip the spelled macro tokens.
335     std::tie(M.BeginSpelled, M.EndSpelled) =
336         consumeSpelledUntil(File, SpelledRange.getEnd().getLocWithOffset(1));
337     // Skip all expanded tokens from the same macro expansion.
338     M.BeginExpanded = I;
339     for (; I + 1 < Result.ExpandedTokens.size(); ++I) {
340       auto NextL = Result.ExpandedTokens[I + 1].location();
341       if (!NextL.isMacroID() ||
342           SM.getExpansionLoc(NextL) != SpelledRange.getBegin())
343         break;
344     }
345     M.EndExpanded = I + 1;
346 
347     // Add a resulting mapping.
348     File.Mappings.push_back(M);
349   }
350 
351   /// Initializes TokenBuffer::Files and fills spelled tokens and expanded
352   /// ranges for each of the files.
353   void buildSpelledTokens() {
354     for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) {
355       auto FID =
356           SM.getFileID(SM.getExpansionLoc(Result.ExpandedTokens[I].location()));
357       auto It = Result.Files.try_emplace(FID);
358       TokenBuffer::MarkedFile &File = It.first->second;
359 
360       File.EndExpanded = I + 1;
361       if (!It.second)
362         continue; // we have seen this file before.
363 
364       // This is the first time we see this file.
365       File.BeginExpanded = I;
366       File.SpelledTokens = tokenize(FID, SM, LangOpts);
367     }
368   }
369 
370   /// Consumed spelled tokens until location L is reached (token starting at L
371   /// is not included). Returns the indicies of the consumed range.
372   std::pair</*Begin*/ unsigned, /*End*/ unsigned>
373   consumeSpelledUntil(TokenBuffer::MarkedFile &File, SourceLocation L) {
374     assert(L.isFileID());
375     FileID FID;
376     unsigned Offset;
377     std::tie(FID, Offset) = SM.getDecomposedLoc(L);
378 
379     // (!) we update the index in-place.
380     unsigned &SpelledI = NextSpelled[FID];
381     unsigned Before = SpelledI;
382     for (; SpelledI < File.SpelledTokens.size() &&
383            SM.getFileOffset(File.SpelledTokens[SpelledI].location()) < Offset;
384          ++SpelledI) {
385     }
386     return std::make_pair(Before, /*After*/ SpelledI);
387   };
388 
389   /// Consumes spelled tokens until location \p L is reached and adds a mapping
390   /// covering the consumed tokens. The mapping will point to an empty expanded
391   /// range at position \p ExpandedIndex.
392   void fillGapUntil(TokenBuffer::MarkedFile &File, SourceLocation L,
393                     unsigned ExpandedIndex) {
394     unsigned BeginSpelledGap, EndSpelledGap;
395     std::tie(BeginSpelledGap, EndSpelledGap) = consumeSpelledUntil(File, L);
396     if (BeginSpelledGap == EndSpelledGap)
397       return; // No gap.
398     TokenBuffer::Mapping M;
399     M.BeginSpelled = BeginSpelledGap;
400     M.EndSpelled = EndSpelledGap;
401     M.BeginExpanded = M.EndExpanded = ExpandedIndex;
402     File.Mappings.push_back(M);
403   };
404 
405   /// Adds empty mappings for unconsumed spelled tokens at the end of each file.
406   void fillGapsAtEndOfFiles() {
407     for (auto &F : Result.Files) {
408       unsigned Next = NextSpelled[F.first];
409       if (F.second.SpelledTokens.size() == Next)
410         continue; // All spelled tokens are accounted for.
411 
412       // Record a mapping for the gap at the end of the spelled tokens.
413       TokenBuffer::Mapping M;
414       M.BeginSpelled = Next;
415       M.EndSpelled = F.second.SpelledTokens.size();
416       M.BeginExpanded = F.second.EndExpanded;
417       M.EndExpanded = F.second.EndExpanded;
418 
419       F.second.Mappings.push_back(M);
420     }
421   }
422 
423   TokenBuffer Result;
424   /// For each file, a position of the next spelled token we will consume.
425   llvm::DenseMap<FileID, unsigned> NextSpelled;
426   const SourceManager &SM;
427   const LangOptions &LangOpts;
428 };
429 
430 TokenBuffer TokenCollector::consume() && {
431   PP.setTokenWatcher(nullptr);
432   return Builder(std::move(Expanded), PP.getSourceManager(), PP.getLangOpts())
433       .build();
434 }
435 
436 std::string syntax::Token::str() const {
437   return llvm::formatv("Token({0}, length = {1})", tok::getTokenName(kind()),
438                        length());
439 }
440 
441 std::string syntax::Token::dumpForTests(const SourceManager &SM) const {
442   return llvm::formatv("{0}   {1}", tok::getTokenName(kind()), text(SM));
443 }
444 
445 std::string TokenBuffer::dumpForTests() const {
446   auto PrintToken = [this](const syntax::Token &T) -> std::string {
447     if (T.kind() == tok::eof)
448       return "<eof>";
449     return T.text(*SourceMgr);
450   };
451 
452   auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS,
453                                         llvm::ArrayRef<syntax::Token> Tokens) {
454     if (Tokens.size() == 1) {
455       assert(Tokens[0].kind() == tok::eof);
456       OS << "<empty>";
457       return;
458     }
459     OS << Tokens[0].text(*SourceMgr);
460     for (unsigned I = 1; I < Tokens.size(); ++I) {
461       if (Tokens[I].kind() == tok::eof)
462         continue;
463       OS << " " << PrintToken(Tokens[I]);
464     }
465   };
466 
467   std::string Dump;
468   llvm::raw_string_ostream OS(Dump);
469 
470   OS << "expanded tokens:\n"
471      << "  ";
472   DumpTokens(OS, ExpandedTokens);
473   OS << "\n";
474 
475   std::vector<FileID> Keys;
476   for (auto F : Files)
477     Keys.push_back(F.first);
478   llvm::sort(Keys);
479 
480   for (FileID ID : Keys) {
481     const MarkedFile &File = Files.find(ID)->second;
482     auto *Entry = SourceMgr->getFileEntryForID(ID);
483     if (!Entry)
484       continue; // Skip builtin files.
485     OS << llvm::formatv("file '{0}'\n", Entry->getName())
486        << "  spelled tokens:\n"
487        << "    ";
488     DumpTokens(OS, File.SpelledTokens);
489     OS << "\n";
490 
491     if (File.Mappings.empty()) {
492       OS << "  no mappings.\n";
493       continue;
494     }
495     OS << "  mappings:\n";
496     for (auto &M : File.Mappings) {
497       OS << llvm::formatv(
498           "    ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n",
499           PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled,
500           M.EndSpelled == File.SpelledTokens.size()
501               ? "<eof>"
502               : PrintToken(File.SpelledTokens[M.EndSpelled]),
503           M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]),
504           M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]),
505           M.EndExpanded);
506     }
507   }
508   return OS.str();
509 }
510