Tokens.cpp 23 KB

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