blob: b4ecb8524839bc30f3ad94bab8d525764b594b6a [file] [log] [blame]
Ilya Biryukove7230ea2019-05-22 14:44:45 +00001//===- 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
34using namespace clang;
35using namespace clang::syntax;
36
37syntax::Token::Token(const clang::Token &T)
38 : Token(T.getLocation(), T.getLength(), T.getKind()) {
39 assert(!T.isAnnotation());
40}
41
42llvm::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
49FileRange 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
57FileRange 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
67llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) {
68 return OS << T.str();
69}
70
71FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset)
72 : File(File), Begin(BeginOffset), End(EndOffset) {
73 assert(File.isValid());
74 assert(BeginOffset <= EndOffset);
75}
76
77FileRange::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}
85FileRange::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
98llvm::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
105llvm::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
115std::pair<const syntax::Token *, const TokenBuffer::Mapping *>
116TokenBuffer::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
150llvm::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
156std::string TokenBuffer::Mapping::str() const {
157 return llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})",
158 BeginSpelled, EndSpelled, BeginExpanded, EndExpanded);
159}
160
161llvm::Optional<llvm::ArrayRef<syntax::Token>>
162TokenBuffer::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
Ilya Biryukov5aed3092019-06-18 16:27:27 +0000202llvm::Optional<TokenBuffer::Expansion>
203TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const {
204 assert(Spelled);
205 assert(Spelled->location().isFileID() && "not a spelled token");
206 auto FileIt = Files.find(SourceMgr->getFileID(Spelled->location()));
207 assert(FileIt != Files.end() && "file not tracked by token buffer");
208
209 auto &File = FileIt->second;
210 assert(File.SpelledTokens.data() <= Spelled &&
211 Spelled < (File.SpelledTokens.data() + File.SpelledTokens.size()));
212
213 unsigned SpelledIndex = Spelled - File.SpelledTokens.data();
214 auto M = llvm::bsearch(File.Mappings, [&](const Mapping &M) {
215 return SpelledIndex <= M.BeginSpelled;
216 });
217 if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex)
218 return llvm::None;
219
220 Expansion E;
221 E.Spelled = llvm::makeArrayRef(File.SpelledTokens.data() + M->BeginSpelled,
222 File.SpelledTokens.data() + M->EndSpelled);
223 E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M->BeginExpanded,
224 ExpandedTokens.data() + M->EndExpanded);
225 return E;
226}
227
Ilya Biryukove7230ea2019-05-22 14:44:45 +0000228std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM,
229 const LangOptions &LO) {
230 std::vector<syntax::Token> Tokens;
231 IdentifierTable Identifiers(LO);
232 auto AddToken = [&](clang::Token T) {
233 // Fill the proper token kind for keywords, etc.
234 if (T.getKind() == tok::raw_identifier && !T.needsCleaning() &&
235 !T.hasUCN()) { // FIXME: support needsCleaning and hasUCN cases.
236 clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier());
237 T.setIdentifierInfo(&II);
238 T.setKind(II.getTokenID());
239 }
240 Tokens.push_back(syntax::Token(T));
241 };
242
243 Lexer L(FID, SM.getBuffer(FID), SM, LO);
244
245 clang::Token T;
246 while (!L.LexFromRawLexer(T))
247 AddToken(T);
248 // 'eof' is only the last token if the input is null-terminated. Never store
249 // it, for consistency.
250 if (T.getKind() != tok::eof)
251 AddToken(T);
252 return Tokens;
253}
254
255/// Fills in the TokenBuffer by tracing the run of a preprocessor. The
256/// implementation tracks the tokens, macro expansions and directives coming
257/// from the preprocessor and:
258/// - for each token, figures out if it is a part of an expanded token stream,
259/// spelled token stream or both. Stores the tokens appropriately.
260/// - records mappings from the spelled to expanded token ranges, e.g. for macro
261/// expansions.
262/// FIXME: also properly record:
263/// - #include directives,
264/// - #pragma, #line and other PP directives,
265/// - skipped pp regions,
266/// - ...
267
268TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) {
269 // Collect the expanded token stream during preprocessing.
270 PP.setTokenWatcher([this](const clang::Token &T) {
271 if (T.isAnnotation())
272 return;
273 DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs()
274 << "Token: "
275 << syntax::Token(T).dumpForTests(
276 this->PP.getSourceManager())
277 << "\n"
278
279 );
280 Expanded.push_back(syntax::Token(T));
281 });
282}
283
284/// Builds mappings and spelled tokens in the TokenBuffer based on the expanded
285/// token stream.
286class TokenCollector::Builder {
287public:
288 Builder(std::vector<syntax::Token> Expanded, const SourceManager &SM,
289 const LangOptions &LangOpts)
290 : Result(SM), SM(SM), LangOpts(LangOpts) {
291 Result.ExpandedTokens = std::move(Expanded);
292 }
293
294 TokenBuffer build() && {
295 buildSpelledTokens();
296
297 // Walk over expanded tokens and spelled tokens in parallel, building the
298 // mappings between those using source locations.
299
300 // The 'eof' token is special, it is not part of spelled token stream. We
301 // handle it separately at the end.
302 assert(!Result.ExpandedTokens.empty());
303 assert(Result.ExpandedTokens.back().kind() == tok::eof);
304 for (unsigned I = 0; I < Result.ExpandedTokens.size() - 1; ++I) {
305 // (!) I might be updated by the following call.
306 processExpandedToken(I);
307 }
308
309 // 'eof' not handled in the loop, do it here.
310 assert(SM.getMainFileID() ==
311 SM.getFileID(Result.ExpandedTokens.back().location()));
312 fillGapUntil(Result.Files[SM.getMainFileID()],
313 Result.ExpandedTokens.back().location(),
314 Result.ExpandedTokens.size() - 1);
315 Result.Files[SM.getMainFileID()].EndExpanded = Result.ExpandedTokens.size();
316
317 // Some files might have unaccounted spelled tokens at the end, add an empty
318 // mapping for those as they did not have expanded counterparts.
319 fillGapsAtEndOfFiles();
320
321 return std::move(Result);
322 }
323
324private:
325 /// Process the next token in an expanded stream and move corresponding
326 /// spelled tokens, record any mapping if needed.
327 /// (!) \p I will be updated if this had to skip tokens, e.g. for macros.
328 void processExpandedToken(unsigned &I) {
329 auto L = Result.ExpandedTokens[I].location();
330 if (L.isMacroID()) {
331 processMacroExpansion(SM.getExpansionRange(L), I);
332 return;
333 }
334 if (L.isFileID()) {
335 auto FID = SM.getFileID(L);
336 TokenBuffer::MarkedFile &File = Result.Files[FID];
337
338 fillGapUntil(File, L, I);
339
340 // Skip the token.
341 assert(File.SpelledTokens[NextSpelled[FID]].location() == L &&
342 "no corresponding token in the spelled stream");
343 ++NextSpelled[FID];
344 return;
345 }
346 }
347
348 /// Skipped expanded and spelled tokens of a macro expansion that covers \p
349 /// SpelledRange. Add a corresponding mapping.
350 /// (!) \p I will be the index of the last token in an expansion after this
351 /// function returns.
352 void processMacroExpansion(CharSourceRange SpelledRange, unsigned &I) {
353 auto FID = SM.getFileID(SpelledRange.getBegin());
354 assert(FID == SM.getFileID(SpelledRange.getEnd()));
355 TokenBuffer::MarkedFile &File = Result.Files[FID];
356
357 fillGapUntil(File, SpelledRange.getBegin(), I);
358
359 TokenBuffer::Mapping M;
360 // Skip the spelled macro tokens.
361 std::tie(M.BeginSpelled, M.EndSpelled) =
362 consumeSpelledUntil(File, SpelledRange.getEnd().getLocWithOffset(1));
363 // Skip all expanded tokens from the same macro expansion.
364 M.BeginExpanded = I;
365 for (; I + 1 < Result.ExpandedTokens.size(); ++I) {
366 auto NextL = Result.ExpandedTokens[I + 1].location();
367 if (!NextL.isMacroID() ||
368 SM.getExpansionLoc(NextL) != SpelledRange.getBegin())
369 break;
370 }
371 M.EndExpanded = I + 1;
372
373 // Add a resulting mapping.
374 File.Mappings.push_back(M);
375 }
376
377 /// Initializes TokenBuffer::Files and fills spelled tokens and expanded
378 /// ranges for each of the files.
379 void buildSpelledTokens() {
380 for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) {
381 auto FID =
382 SM.getFileID(SM.getExpansionLoc(Result.ExpandedTokens[I].location()));
383 auto It = Result.Files.try_emplace(FID);
384 TokenBuffer::MarkedFile &File = It.first->second;
385
386 File.EndExpanded = I + 1;
387 if (!It.second)
388 continue; // we have seen this file before.
389
390 // This is the first time we see this file.
391 File.BeginExpanded = I;
392 File.SpelledTokens = tokenize(FID, SM, LangOpts);
393 }
394 }
395
396 /// Consumed spelled tokens until location L is reached (token starting at L
397 /// is not included). Returns the indicies of the consumed range.
398 std::pair</*Begin*/ unsigned, /*End*/ unsigned>
399 consumeSpelledUntil(TokenBuffer::MarkedFile &File, SourceLocation L) {
400 assert(L.isFileID());
401 FileID FID;
402 unsigned Offset;
403 std::tie(FID, Offset) = SM.getDecomposedLoc(L);
404
405 // (!) we update the index in-place.
406 unsigned &SpelledI = NextSpelled[FID];
407 unsigned Before = SpelledI;
408 for (; SpelledI < File.SpelledTokens.size() &&
409 SM.getFileOffset(File.SpelledTokens[SpelledI].location()) < Offset;
410 ++SpelledI) {
411 }
412 return std::make_pair(Before, /*After*/ SpelledI);
413 };
414
415 /// Consumes spelled tokens until location \p L is reached and adds a mapping
416 /// covering the consumed tokens. The mapping will point to an empty expanded
417 /// range at position \p ExpandedIndex.
418 void fillGapUntil(TokenBuffer::MarkedFile &File, SourceLocation L,
419 unsigned ExpandedIndex) {
420 unsigned BeginSpelledGap, EndSpelledGap;
421 std::tie(BeginSpelledGap, EndSpelledGap) = consumeSpelledUntil(File, L);
422 if (BeginSpelledGap == EndSpelledGap)
423 return; // No gap.
424 TokenBuffer::Mapping M;
425 M.BeginSpelled = BeginSpelledGap;
426 M.EndSpelled = EndSpelledGap;
427 M.BeginExpanded = M.EndExpanded = ExpandedIndex;
428 File.Mappings.push_back(M);
429 };
430
431 /// Adds empty mappings for unconsumed spelled tokens at the end of each file.
432 void fillGapsAtEndOfFiles() {
433 for (auto &F : Result.Files) {
434 unsigned Next = NextSpelled[F.first];
435 if (F.second.SpelledTokens.size() == Next)
436 continue; // All spelled tokens are accounted for.
437
438 // Record a mapping for the gap at the end of the spelled tokens.
439 TokenBuffer::Mapping M;
440 M.BeginSpelled = Next;
441 M.EndSpelled = F.second.SpelledTokens.size();
442 M.BeginExpanded = F.second.EndExpanded;
443 M.EndExpanded = F.second.EndExpanded;
444
445 F.second.Mappings.push_back(M);
446 }
447 }
448
449 TokenBuffer Result;
450 /// For each file, a position of the next spelled token we will consume.
451 llvm::DenseMap<FileID, unsigned> NextSpelled;
452 const SourceManager &SM;
453 const LangOptions &LangOpts;
454};
455
456TokenBuffer TokenCollector::consume() && {
457 PP.setTokenWatcher(nullptr);
458 return Builder(std::move(Expanded), PP.getSourceManager(), PP.getLangOpts())
459 .build();
460}
461
462std::string syntax::Token::str() const {
463 return llvm::formatv("Token({0}, length = {1})", tok::getTokenName(kind()),
464 length());
465}
466
467std::string syntax::Token::dumpForTests(const SourceManager &SM) const {
468 return llvm::formatv("{0} {1}", tok::getTokenName(kind()), text(SM));
469}
470
471std::string TokenBuffer::dumpForTests() const {
472 auto PrintToken = [this](const syntax::Token &T) -> std::string {
473 if (T.kind() == tok::eof)
474 return "<eof>";
475 return T.text(*SourceMgr);
476 };
477
478 auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS,
479 llvm::ArrayRef<syntax::Token> Tokens) {
Ilya Biryukov26c066d2019-06-19 13:56:36 +0000480 if (Tokens.empty()) {
Ilya Biryukove7230ea2019-05-22 14:44:45 +0000481 OS << "<empty>";
482 return;
483 }
484 OS << Tokens[0].text(*SourceMgr);
485 for (unsigned I = 1; I < Tokens.size(); ++I) {
486 if (Tokens[I].kind() == tok::eof)
487 continue;
488 OS << " " << PrintToken(Tokens[I]);
489 }
490 };
491
492 std::string Dump;
493 llvm::raw_string_ostream OS(Dump);
494
495 OS << "expanded tokens:\n"
496 << " ";
Ilya Biryukov26c066d2019-06-19 13:56:36 +0000497 // (!) we do not show '<eof>'.
498 DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back());
Ilya Biryukove7230ea2019-05-22 14:44:45 +0000499 OS << "\n";
500
501 std::vector<FileID> Keys;
502 for (auto F : Files)
503 Keys.push_back(F.first);
504 llvm::sort(Keys);
505
506 for (FileID ID : Keys) {
507 const MarkedFile &File = Files.find(ID)->second;
508 auto *Entry = SourceMgr->getFileEntryForID(ID);
509 if (!Entry)
510 continue; // Skip builtin files.
511 OS << llvm::formatv("file '{0}'\n", Entry->getName())
512 << " spelled tokens:\n"
513 << " ";
514 DumpTokens(OS, File.SpelledTokens);
515 OS << "\n";
516
517 if (File.Mappings.empty()) {
518 OS << " no mappings.\n";
519 continue;
520 }
521 OS << " mappings:\n";
522 for (auto &M : File.Mappings) {
523 OS << llvm::formatv(
524 " ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n",
525 PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled,
526 M.EndSpelled == File.SpelledTokens.size()
527 ? "<eof>"
528 : PrintToken(File.SpelledTokens[M.EndSpelled]),
529 M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]),
530 M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]),
531 M.EndExpanded);
532 }
533 }
534 return OS.str();
535}