xref: /llvm-project/clang/unittests/Tooling/Syntax/TokensTest.cpp (revision cd9b2e18bd69503e8d624d427caa3a0157b34e52)
1 //===- TokensTest.cpp -----------------------------------------------------===//
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 
9 #include "clang/Tooling/Syntax/Tokens.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/Expr.h"
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/DiagnosticIDs.h"
14 #include "clang/Basic/DiagnosticOptions.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/FileSystemOptions.h"
17 #include "clang/Basic/LLVM.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.def"
22 #include "clang/Basic/TokenKinds.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/Utils.h"
26 #include "clang/Lex/Lexer.h"
27 #include "clang/Lex/PreprocessorOptions.h"
28 #include "clang/Lex/Token.h"
29 #include "clang/Tooling/Tooling.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/IntrusiveRefCntPtr.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/FormatVariadic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/VirtualFileSystem.h"
39 #include "llvm/Support/raw_os_ostream.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Testing/Support/Annotations.h"
42 #include "llvm/Testing/Support/SupportHelpers.h"
43 #include "gmock/gmock.h"
44 #include <cassert>
45 #include <cstdlib>
46 #include <gmock/gmock.h>
47 #include <gtest/gtest.h>
48 #include <memory>
49 #include <ostream>
50 #include <string>
51 
52 using namespace clang;
53 using namespace clang::syntax;
54 
55 using llvm::ValueIs;
56 using ::testing::AllOf;
57 using ::testing::Contains;
58 using ::testing::ElementsAre;
59 using ::testing::Field;
60 using ::testing::Matcher;
61 using ::testing::Not;
62 using ::testing::Pointee;
63 using ::testing::StartsWith;
64 
65 namespace {
66 // Checks the passed ArrayRef<T> has the same begin() and end() iterators as the
67 // argument.
68 MATCHER_P(SameRange, A, "") {
69   return A.begin() == arg.begin() && A.end() == arg.end();
70 }
71 
72 Matcher<TokenBuffer::Expansion>
73 IsExpansion(Matcher<llvm::ArrayRef<syntax::Token>> Spelled,
74             Matcher<llvm::ArrayRef<syntax::Token>> Expanded) {
75   return AllOf(Field(&TokenBuffer::Expansion::Spelled, Spelled),
76                Field(&TokenBuffer::Expansion::Expanded, Expanded));
77 }
78 // Matchers for syntax::Token.
79 MATCHER_P(Kind, K, "") { return arg.kind() == K; }
80 MATCHER_P2(HasText, Text, SourceMgr, "") {
81   return arg.text(*SourceMgr) == Text;
82 }
83 /// Checks the start and end location of a token are equal to SourceRng.
84 MATCHER_P(RangeIs, SourceRng, "") {
85   return arg.location() == SourceRng.first &&
86          arg.endLocation() == SourceRng.second;
87 }
88 
89 class TokenCollectorTest : public ::testing::Test {
90 public:
91   /// Run the clang frontend, collect the preprocessed tokens from the frontend
92   /// invocation and store them in this->Buffer.
93   /// This also clears SourceManager before running the compiler.
94   void recordTokens(llvm::StringRef Code) {
95     class RecordTokens : public ASTFrontendAction {
96     public:
97       explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
98 
99       bool BeginSourceFileAction(CompilerInstance &CI) override {
100         assert(!Collector && "expected only a single call to BeginSourceFile");
101         Collector.emplace(CI.getPreprocessor());
102         return true;
103       }
104       void EndSourceFileAction() override {
105         assert(Collector && "BeginSourceFileAction was never called");
106         Result = std::move(*Collector).consume();
107       }
108 
109       std::unique_ptr<ASTConsumer>
110       CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
111         return std::make_unique<ASTConsumer>();
112       }
113 
114     private:
115       TokenBuffer &Result;
116       llvm::Optional<TokenCollector> Collector;
117     };
118 
119     constexpr const char *FileName = "./input.cpp";
120     FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
121     // Prepare to run a compiler.
122     if (!Diags->getClient())
123       Diags->setClient(new IgnoringDiagConsumer);
124     std::vector<const char *> Args = {"tok-test", "-std=c++03", "-fsyntax-only",
125                                       FileName};
126     auto CI = createInvocationFromCommandLine(Args, Diags, FS);
127     assert(CI);
128     CI->getFrontendOpts().DisableFree = false;
129     CI->getPreprocessorOpts().addRemappedFile(
130         FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release());
131     CompilerInstance Compiler;
132     Compiler.setInvocation(std::move(CI));
133     Compiler.setDiagnostics(Diags.get());
134     Compiler.setFileManager(FileMgr.get());
135     Compiler.setSourceManager(SourceMgr.get());
136 
137     this->Buffer = TokenBuffer(*SourceMgr);
138     RecordTokens Recorder(this->Buffer);
139     ASSERT_TRUE(Compiler.ExecuteAction(Recorder))
140         << "failed to run the frontend";
141   }
142 
143   /// Record the tokens and return a test dump of the resulting buffer.
144   std::string collectAndDump(llvm::StringRef Code) {
145     recordTokens(Code);
146     return Buffer.dumpForTests();
147   }
148 
149   // Adds a file to the test VFS.
150   void addFile(llvm::StringRef Path, llvm::StringRef Contents) {
151     if (!FS->addFile(Path, time_t(),
152                      llvm::MemoryBuffer::getMemBufferCopy(Contents))) {
153       ADD_FAILURE() << "could not add a file to VFS: " << Path;
154     }
155   }
156 
157   /// Add a new file, run syntax::tokenize() on the range if any, run it on the
158   /// whole file otherwise and return the results.
159   std::vector<syntax::Token> tokenize(llvm::StringRef Text) {
160     llvm::Annotations Annot(Text);
161     auto FID = SourceMgr->createFileID(
162         llvm::MemoryBuffer::getMemBufferCopy(Annot.code()));
163     // FIXME: pass proper LangOptions.
164     if (Annot.ranges().empty())
165       return syntax::tokenize(FID, *SourceMgr, LangOptions());
166     return syntax::tokenize(
167         syntax::FileRange(FID, Annot.range().Begin, Annot.range().End),
168         *SourceMgr, LangOptions());
169   }
170 
171   // Specialized versions of matchers that hide the SourceManager from clients.
172   Matcher<syntax::Token> HasText(std::string Text) const {
173     return ::HasText(Text, SourceMgr.get());
174   }
175   Matcher<syntax::Token> RangeIs(llvm::Annotations::Range R) const {
176     std::pair<SourceLocation, SourceLocation> Ls;
177     Ls.first = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID())
178                    .getLocWithOffset(R.Begin);
179     Ls.second = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID())
180                     .getLocWithOffset(R.End);
181     return ::RangeIs(Ls);
182   }
183 
184   /// Finds a subrange in O(n * m).
185   template <class T, class U, class Eq>
186   llvm::ArrayRef<T> findSubrange(llvm::ArrayRef<U> Subrange,
187                                  llvm::ArrayRef<T> Range, Eq F) {
188     for (auto Begin = Range.begin(); Begin < Range.end(); ++Begin) {
189       auto It = Begin;
190       for (auto ItSub = Subrange.begin();
191            ItSub != Subrange.end() && It != Range.end(); ++ItSub, ++It) {
192         if (!F(*ItSub, *It))
193           goto continue_outer;
194       }
195       return llvm::makeArrayRef(Begin, It);
196     continue_outer:;
197     }
198     return llvm::makeArrayRef(Range.end(), Range.end());
199   }
200 
201   /// Finds a subrange in \p Tokens that match the tokens specified in \p Query.
202   /// The match should be unique. \p Query is a whitespace-separated list of
203   /// tokens to search for.
204   llvm::ArrayRef<syntax::Token>
205   findTokenRange(llvm::StringRef Query, llvm::ArrayRef<syntax::Token> Tokens) {
206     llvm::SmallVector<llvm::StringRef, 8> QueryTokens;
207     Query.split(QueryTokens, ' ', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
208     if (QueryTokens.empty()) {
209       ADD_FAILURE() << "will not look for an empty list of tokens";
210       std::abort();
211     }
212     // An equality test for search.
213     auto TextMatches = [this](llvm::StringRef Q, const syntax::Token &T) {
214       return Q == T.text(*SourceMgr);
215     };
216     // Find a match.
217     auto Found =
218         findSubrange(llvm::makeArrayRef(QueryTokens), Tokens, TextMatches);
219     if (Found.begin() == Tokens.end()) {
220       ADD_FAILURE() << "could not find the subrange for " << Query;
221       std::abort();
222     }
223     // Check that the match is unique.
224     if (findSubrange(llvm::makeArrayRef(QueryTokens),
225                      llvm::makeArrayRef(Found.end(), Tokens.end()), TextMatches)
226             .begin() != Tokens.end()) {
227       ADD_FAILURE() << "match is not unique for " << Query;
228       std::abort();
229     }
230     return Found;
231   };
232 
233   // Specialized versions of findTokenRange for expanded and spelled tokens.
234   llvm::ArrayRef<syntax::Token> findExpanded(llvm::StringRef Query) {
235     return findTokenRange(Query, Buffer.expandedTokens());
236   }
237   llvm::ArrayRef<syntax::Token> findSpelled(llvm::StringRef Query,
238                                             FileID File = FileID()) {
239     if (!File.isValid())
240       File = SourceMgr->getMainFileID();
241     return findTokenRange(Query, Buffer.spelledTokens(File));
242   }
243 
244   // Data fields.
245   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
246       new DiagnosticsEngine(new DiagnosticIDs, new DiagnosticOptions);
247   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> FS =
248       new llvm::vfs::InMemoryFileSystem;
249   llvm::IntrusiveRefCntPtr<FileManager> FileMgr =
250       new FileManager(FileSystemOptions(), FS);
251   llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr =
252       new SourceManager(*Diags, *FileMgr);
253   /// Contains last result of calling recordTokens().
254   TokenBuffer Buffer = TokenBuffer(*SourceMgr);
255 };
256 
257 TEST_F(TokenCollectorTest, RawMode) {
258   EXPECT_THAT(tokenize("int main() {}"),
259               ElementsAre(Kind(tok::kw_int),
260                           AllOf(HasText("main"), Kind(tok::identifier)),
261                           Kind(tok::l_paren), Kind(tok::r_paren),
262                           Kind(tok::l_brace), Kind(tok::r_brace)));
263   // Comments are ignored for now.
264   EXPECT_THAT(tokenize("/* foo */int a; // more comments"),
265               ElementsAre(Kind(tok::kw_int),
266                           AllOf(HasText("a"), Kind(tok::identifier)),
267                           Kind(tok::semi)));
268   EXPECT_THAT(tokenize("int [[main() {]]}"),
269               ElementsAre(AllOf(HasText("main"), Kind(tok::identifier)),
270                           Kind(tok::l_paren), Kind(tok::r_paren),
271                           Kind(tok::l_brace)));
272   EXPECT_THAT(tokenize("int [[main() {   ]]}"),
273               ElementsAre(AllOf(HasText("main"), Kind(tok::identifier)),
274                           Kind(tok::l_paren), Kind(tok::r_paren),
275                           Kind(tok::l_brace)));
276   // First token is partially parsed, last token is fully included even though
277   // only a part of it is contained in the range.
278   EXPECT_THAT(tokenize("int m[[ain() {ret]]urn 0;}"),
279               ElementsAre(AllOf(HasText("ain"), Kind(tok::identifier)),
280                           Kind(tok::l_paren), Kind(tok::r_paren),
281                           Kind(tok::l_brace), Kind(tok::kw_return)));
282 }
283 
284 TEST_F(TokenCollectorTest, Basic) {
285   std::pair</*Input*/ std::string, /*Expected*/ std::string> TestCases[] = {
286       {"int main() {}",
287        R"(expanded tokens:
288   int main ( ) { }
289 file './input.cpp'
290   spelled tokens:
291     int main ( ) { }
292   no mappings.
293 )"},
294       // All kinds of whitespace are ignored.
295       {"\t\n  int\t\n  main\t\n  (\t\n  )\t\n{\t\n  }\t\n",
296        R"(expanded tokens:
297   int main ( ) { }
298 file './input.cpp'
299   spelled tokens:
300     int main ( ) { }
301   no mappings.
302 )"},
303       // Annotation tokens are ignored.
304       {R"cpp(
305         #pragma GCC visibility push (public)
306         #pragma GCC visibility pop
307       )cpp",
308        R"(expanded tokens:
309   <empty>
310 file './input.cpp'
311   spelled tokens:
312     # pragma GCC visibility push ( public ) # pragma GCC visibility pop
313   mappings:
314     ['#'_0, '<eof>'_13) => ['<eof>'_0, '<eof>'_0)
315 )"},
316       // Empty files should not crash.
317       {R"cpp()cpp", R"(expanded tokens:
318   <empty>
319 file './input.cpp'
320   spelled tokens:
321     <empty>
322   no mappings.
323 )"},
324       // Should not crash on errors inside '#define' directives. Error is that
325       // stringification (#B) does not refer to a macro parameter.
326       {
327           R"cpp(
328 a
329 #define MACRO() A #B
330 )cpp",
331           R"(expanded tokens:
332   a
333 file './input.cpp'
334   spelled tokens:
335     a # define MACRO ( ) A # B
336   mappings:
337     ['#'_1, '<eof>'_9) => ['<eof>'_1, '<eof>'_1)
338 )"}};
339   for (auto &Test : TestCases)
340     EXPECT_EQ(collectAndDump(Test.first), Test.second)
341         << collectAndDump(Test.first);
342 }
343 
344 TEST_F(TokenCollectorTest, Locations) {
345   // Check locations of the tokens.
346   llvm::Annotations Code(R"cpp(
347     $r1[[int]] $r2[[a]] $r3[[=]] $r4[["foo bar baz"]] $r5[[;]]
348   )cpp");
349   recordTokens(Code.code());
350   // Check expanded tokens.
351   EXPECT_THAT(
352       Buffer.expandedTokens(),
353       ElementsAre(AllOf(Kind(tok::kw_int), RangeIs(Code.range("r1"))),
354                   AllOf(Kind(tok::identifier), RangeIs(Code.range("r2"))),
355                   AllOf(Kind(tok::equal), RangeIs(Code.range("r3"))),
356                   AllOf(Kind(tok::string_literal), RangeIs(Code.range("r4"))),
357                   AllOf(Kind(tok::semi), RangeIs(Code.range("r5"))),
358                   Kind(tok::eof)));
359   // Check spelled tokens.
360   EXPECT_THAT(
361       Buffer.spelledTokens(SourceMgr->getMainFileID()),
362       ElementsAre(AllOf(Kind(tok::kw_int), RangeIs(Code.range("r1"))),
363                   AllOf(Kind(tok::identifier), RangeIs(Code.range("r2"))),
364                   AllOf(Kind(tok::equal), RangeIs(Code.range("r3"))),
365                   AllOf(Kind(tok::string_literal), RangeIs(Code.range("r4"))),
366                   AllOf(Kind(tok::semi), RangeIs(Code.range("r5")))));
367 
368   auto StartLoc = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
369   for (auto &R : Code.ranges()) {
370     EXPECT_THAT(Buffer.spelledTokenAt(StartLoc.getLocWithOffset(R.Begin)),
371                 Pointee(RangeIs(R)));
372   }
373 }
374 
375 TEST_F(TokenCollectorTest, MacroDirectives) {
376   // Macro directives are not stored anywhere at the moment.
377   std::string Code = R"cpp(
378     #define FOO a
379     #include "unresolved_file.h"
380     #undef FOO
381     #ifdef X
382     #else
383     #endif
384     #ifndef Y
385     #endif
386     #if 1
387     #elif 2
388     #else
389     #endif
390     #pragma once
391     #pragma something lalala
392 
393     int a;
394   )cpp";
395   std::string Expected =
396       "expanded tokens:\n"
397       "  int a ;\n"
398       "file './input.cpp'\n"
399       "  spelled tokens:\n"
400       "    # define FOO a # include \"unresolved_file.h\" # undef FOO "
401       "# ifdef X # else # endif # ifndef Y # endif # if 1 # elif 2 # else "
402       "# endif # pragma once # pragma something lalala int a ;\n"
403       "  mappings:\n"
404       "    ['#'_0, 'int'_39) => ['int'_0, 'int'_0)\n";
405   EXPECT_EQ(collectAndDump(Code), Expected);
406 }
407 
408 TEST_F(TokenCollectorTest, MacroReplacements) {
409   std::pair</*Input*/ std::string, /*Expected*/ std::string> TestCases[] = {
410       // A simple object-like macro.
411       {R"cpp(
412     #define INT int const
413     INT a;
414   )cpp",
415        R"(expanded tokens:
416   int const a ;
417 file './input.cpp'
418   spelled tokens:
419     # define INT int const INT a ;
420   mappings:
421     ['#'_0, 'INT'_5) => ['int'_0, 'int'_0)
422     ['INT'_5, 'a'_6) => ['int'_0, 'a'_2)
423 )"},
424       // A simple function-like macro.
425       {R"cpp(
426     #define INT(a) const int
427     INT(10+10) a;
428   )cpp",
429        R"(expanded tokens:
430   const int a ;
431 file './input.cpp'
432   spelled tokens:
433     # define INT ( a ) const int INT ( 10 + 10 ) a ;
434   mappings:
435     ['#'_0, 'INT'_8) => ['const'_0, 'const'_0)
436     ['INT'_8, 'a'_14) => ['const'_0, 'a'_2)
437 )"},
438       // Recursive macro replacements.
439       {R"cpp(
440     #define ID(X) X
441     #define INT int const
442     ID(ID(INT)) a;
443   )cpp",
444        R"(expanded tokens:
445   int const a ;
446 file './input.cpp'
447   spelled tokens:
448     # define ID ( X ) X # define INT int const ID ( ID ( INT ) ) a ;
449   mappings:
450     ['#'_0, 'ID'_12) => ['int'_0, 'int'_0)
451     ['ID'_12, 'a'_19) => ['int'_0, 'a'_2)
452 )"},
453       // A little more complicated recursive macro replacements.
454       {R"cpp(
455     #define ADD(X, Y) X+Y
456     #define MULT(X, Y) X*Y
457 
458     int a = ADD(MULT(1,2), MULT(3,ADD(4,5)));
459   )cpp",
460        "expanded tokens:\n"
461        "  int a = 1 * 2 + 3 * 4 + 5 ;\n"
462        "file './input.cpp'\n"
463        "  spelled tokens:\n"
464        "    # define ADD ( X , Y ) X + Y # define MULT ( X , Y ) X * Y int "
465        "a = ADD ( MULT ( 1 , 2 ) , MULT ( 3 , ADD ( 4 , 5 ) ) ) ;\n"
466        "  mappings:\n"
467        "    ['#'_0, 'int'_22) => ['int'_0, 'int'_0)\n"
468        "    ['ADD'_25, ';'_46) => ['1'_3, ';'_12)\n"},
469       // Empty macro replacement.
470       // FIXME: the #define directives should not be glued together.
471       {R"cpp(
472     #define EMPTY
473     #define EMPTY_FUNC(X)
474     EMPTY
475     EMPTY_FUNC(1+2+3)
476     )cpp",
477        R"(expanded tokens:
478   <empty>
479 file './input.cpp'
480   spelled tokens:
481     # define EMPTY # define EMPTY_FUNC ( X ) EMPTY EMPTY_FUNC ( 1 + 2 + 3 )
482   mappings:
483     ['#'_0, 'EMPTY'_9) => ['<eof>'_0, '<eof>'_0)
484     ['EMPTY'_9, 'EMPTY_FUNC'_10) => ['<eof>'_0, '<eof>'_0)
485     ['EMPTY_FUNC'_10, '<eof>'_18) => ['<eof>'_0, '<eof>'_0)
486 )"},
487       // File ends with a macro replacement.
488       {R"cpp(
489     #define FOO 10+10;
490     int a = FOO
491     )cpp",
492        R"(expanded tokens:
493   int a = 10 + 10 ;
494 file './input.cpp'
495   spelled tokens:
496     # define FOO 10 + 10 ; int a = FOO
497   mappings:
498     ['#'_0, 'int'_7) => ['int'_0, 'int'_0)
499     ['FOO'_10, '<eof>'_11) => ['10'_3, '<eof>'_7)
500 )"}};
501 
502   for (auto &Test : TestCases)
503     EXPECT_EQ(Test.second, collectAndDump(Test.first))
504         << collectAndDump(Test.first);
505 }
506 
507 TEST_F(TokenCollectorTest, SpecialTokens) {
508   // Tokens coming from concatenations.
509   recordTokens(R"cpp(
510     #define CONCAT(a, b) a ## b
511     int a = CONCAT(1, 2);
512   )cpp");
513   EXPECT_THAT(std::vector<syntax::Token>(Buffer.expandedTokens()),
514               Contains(HasText("12")));
515   // Multi-line tokens with slashes at the end.
516   recordTokens("i\\\nn\\\nt");
517   EXPECT_THAT(Buffer.expandedTokens(),
518               ElementsAre(AllOf(Kind(tok::kw_int), HasText("i\\\nn\\\nt")),
519                           Kind(tok::eof)));
520   // FIXME: test tokens with digraphs and UCN identifiers.
521 }
522 
523 TEST_F(TokenCollectorTest, LateBoundTokens) {
524   // The parser eventually breaks the first '>>' into two tokens ('>' and '>'),
525   // but we choose to record them as a single token (for now).
526   llvm::Annotations Code(R"cpp(
527     template <class T>
528     struct foo { int a; };
529     int bar = foo<foo<int$br[[>>]]().a;
530     int baz = 10 $op[[>>]] 2;
531   )cpp");
532   recordTokens(Code.code());
533   EXPECT_THAT(std::vector<syntax::Token>(Buffer.expandedTokens()),
534               AllOf(Contains(AllOf(Kind(tok::greatergreater),
535                                    RangeIs(Code.range("br")))),
536                     Contains(AllOf(Kind(tok::greatergreater),
537                                    RangeIs(Code.range("op"))))));
538 }
539 
540 TEST_F(TokenCollectorTest, DelayedParsing) {
541   llvm::StringLiteral Code = R"cpp(
542     struct Foo {
543       int method() {
544         // Parser will visit method bodies and initializers multiple times, but
545         // TokenBuffer should only record the first walk over the tokens;
546         return 100;
547       }
548       int a = 10;
549 
550       struct Subclass {
551         void foo() {
552           Foo().method();
553         }
554       };
555     };
556   )cpp";
557   std::string ExpectedTokens =
558       "expanded tokens:\n"
559       "  struct Foo { int method ( ) { return 100 ; } int a = 10 ; struct "
560       "Subclass { void foo ( ) { Foo ( ) . method ( ) ; } } ; } ;\n";
561   EXPECT_THAT(collectAndDump(Code), StartsWith(ExpectedTokens));
562 }
563 
564 TEST_F(TokenCollectorTest, MultiFile) {
565   addFile("./foo.h", R"cpp(
566     #define ADD(X, Y) X+Y
567     int a = 100;
568     #include "bar.h"
569   )cpp");
570   addFile("./bar.h", R"cpp(
571     int b = ADD(1, 2);
572     #define MULT(X, Y) X*Y
573   )cpp");
574   llvm::StringLiteral Code = R"cpp(
575     #include "foo.h"
576     int c = ADD(1, MULT(2,3));
577   )cpp";
578 
579   std::string Expected = R"(expanded tokens:
580   int a = 100 ; int b = 1 + 2 ; int c = 1 + 2 * 3 ;
581 file './input.cpp'
582   spelled tokens:
583     # include "foo.h" int c = ADD ( 1 , MULT ( 2 , 3 ) ) ;
584   mappings:
585     ['#'_0, 'int'_3) => ['int'_12, 'int'_12)
586     ['ADD'_6, ';'_17) => ['1'_15, ';'_20)
587 file './foo.h'
588   spelled tokens:
589     # define ADD ( X , Y ) X + Y int a = 100 ; # include "bar.h"
590   mappings:
591     ['#'_0, 'int'_11) => ['int'_0, 'int'_0)
592     ['#'_16, '<eof>'_19) => ['int'_5, 'int'_5)
593 file './bar.h'
594   spelled tokens:
595     int b = ADD ( 1 , 2 ) ; # define MULT ( X , Y ) X * Y
596   mappings:
597     ['ADD'_3, ';'_9) => ['1'_8, ';'_11)
598     ['#'_10, '<eof>'_21) => ['int'_12, 'int'_12)
599 )";
600 
601   EXPECT_EQ(Expected, collectAndDump(Code))
602       << "input: " << Code << "\nresults: " << collectAndDump(Code);
603 }
604 
605 class TokenBufferTest : public TokenCollectorTest {};
606 
607 TEST_F(TokenBufferTest, SpelledByExpanded) {
608   recordTokens(R"cpp(
609     a1 a2 a3 b1 b2
610   )cpp");
611 
612   // Sanity check: expanded and spelled tokens are stored separately.
613   EXPECT_THAT(findExpanded("a1 a2"), Not(SameRange(findSpelled("a1 a2"))));
614   // Searching for subranges of expanded tokens should give the corresponding
615   // spelled ones.
616   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3 b1 b2")),
617               ValueIs(SameRange(findSpelled("a1 a2 a3 b1 b2"))));
618   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3")),
619               ValueIs(SameRange(findSpelled("a1 a2 a3"))));
620   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("b1 b2")),
621               ValueIs(SameRange(findSpelled("b1 b2"))));
622 
623   // Test search on simple macro expansions.
624   recordTokens(R"cpp(
625     #define A a1 a2 a3
626     #define B b1 b2
627 
628     A split B
629   )cpp");
630   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3 split b1 b2")),
631               ValueIs(SameRange(findSpelled("A split B"))));
632   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3")),
633               ValueIs(SameRange(findSpelled("A split").drop_back())));
634   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("b1 b2")),
635               ValueIs(SameRange(findSpelled("split B").drop_front())));
636   // Ranges not fully covering macro invocations should fail.
637   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a1 a2")), llvm::None);
638   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("b2")), llvm::None);
639   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a2 a3 split b1 b2")),
640             llvm::None);
641 
642   // Recursive macro invocations.
643   recordTokens(R"cpp(
644     #define ID(x) x
645     #define B b1 b2
646 
647     ID(ID(ID(a1) a2 a3)) split ID(B)
648   )cpp");
649 
650   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3")),
651               ValueIs(SameRange(findSpelled("ID ( ID ( ID ( a1 ) a2 a3 ) )"))));
652   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("b1 b2")),
653               ValueIs(SameRange(findSpelled("ID ( B )"))));
654   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("a1 a2 a3 split b1 b2")),
655               ValueIs(SameRange(findSpelled(
656                   "ID ( ID ( ID ( a1 ) a2 a3 ) ) split ID ( B )"))));
657   // Ranges crossing macro call boundaries.
658   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a1 a2 a3 split b1")),
659             llvm::None);
660   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a2 a3 split b1")),
661             llvm::None);
662   // FIXME: next two examples should map to macro arguments, but currently they
663   //        fail.
664   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a2")), llvm::None);
665   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a1 a2")), llvm::None);
666 
667   // Empty macro expansions.
668   recordTokens(R"cpp(
669     #define EMPTY
670     #define ID(X) X
671 
672     EMPTY EMPTY ID(1 2 3) EMPTY EMPTY split1
673     EMPTY EMPTY ID(4 5 6) split2
674     ID(7 8 9) EMPTY EMPTY
675   )cpp");
676   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("1 2 3")),
677               ValueIs(SameRange(findSpelled("ID ( 1 2 3 )"))));
678   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("4 5 6")),
679               ValueIs(SameRange(findSpelled("ID ( 4 5 6 )"))));
680   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("7 8 9")),
681               ValueIs(SameRange(findSpelled("ID ( 7 8 9 )"))));
682 
683   // Empty mappings coming from various directives.
684   recordTokens(R"cpp(
685     #define ID(X) X
686     ID(1)
687     #pragma lalala
688     not_mapped
689   )cpp");
690   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("not_mapped")),
691               ValueIs(SameRange(findSpelled("not_mapped"))));
692 }
693 
694 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
695   recordTokens(R"cpp(
696     #define SIGN(X) X##_washere
697     A SIGN(B) C SIGN(D) E SIGN(F) G
698   )cpp");
699 
700   SourceRange R(findExpanded("C").front().location(),
701                 findExpanded("F_washere").front().location());
702   // Sanity check: expanded and spelled tokens are stored separately.
703   EXPECT_THAT(Buffer.expandedTokens(R),
704               SameRange(findExpanded("C D_washere E F_washere")));
705   EXPECT_THAT(Buffer.expandedTokens(SourceRange()), testing::IsEmpty());
706 }
707 
708 TEST_F(TokenBufferTest, ExpansionStartingAt) {
709   // Object-like macro expansions.
710   recordTokens(R"cpp(
711     #define FOO 3+4
712     int a = FOO 1;
713     int b = FOO 2;
714   )cpp");
715 
716   llvm::ArrayRef<syntax::Token> Foo1 = findSpelled("FOO 1").drop_back();
717   EXPECT_THAT(
718       Buffer.expansionStartingAt(Foo1.data()),
719       ValueIs(IsExpansion(SameRange(Foo1),
720                           SameRange(findExpanded("3 + 4 1").drop_back()))));
721 
722   llvm::ArrayRef<syntax::Token> Foo2 = findSpelled("FOO 2").drop_back();
723   EXPECT_THAT(
724       Buffer.expansionStartingAt(Foo2.data()),
725       ValueIs(IsExpansion(SameRange(Foo2),
726                           SameRange(findExpanded("3 + 4 2").drop_back()))));
727 
728   // Function-like macro expansions.
729   recordTokens(R"cpp(
730     #define ID(X) X
731     int a = ID(1+2+3);
732     int b = ID(ID(2+3+4));
733   )cpp");
734 
735   llvm::ArrayRef<syntax::Token> ID1 = findSpelled("ID ( 1 + 2 + 3 )");
736   EXPECT_THAT(Buffer.expansionStartingAt(&ID1.front()),
737               ValueIs(IsExpansion(SameRange(ID1),
738                                   SameRange(findExpanded("1 + 2 + 3")))));
739   // Only the first spelled token should be found.
740   for (const auto &T : ID1.drop_front())
741     EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
742 
743   llvm::ArrayRef<syntax::Token> ID2 = findSpelled("ID ( ID ( 2 + 3 + 4 ) )");
744   EXPECT_THAT(Buffer.expansionStartingAt(&ID2.front()),
745               ValueIs(IsExpansion(SameRange(ID2),
746                                   SameRange(findExpanded("2 + 3 + 4")))));
747   // Only the first spelled token should be found.
748   for (const auto &T : ID2.drop_front())
749     EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
750 
751   // PP directives.
752   recordTokens(R"cpp(
753 #define FOO 1
754 int a = FOO;
755 #pragma once
756 int b = 1;
757   )cpp");
758 
759   llvm::ArrayRef<syntax::Token> DefineFoo = findSpelled("# define FOO 1");
760   EXPECT_THAT(
761       Buffer.expansionStartingAt(&DefineFoo.front()),
762       ValueIs(IsExpansion(SameRange(DefineFoo),
763                           SameRange(findExpanded("int a").take_front(0)))));
764   // Only the first spelled token should be found.
765   for (const auto &T : DefineFoo.drop_front())
766     EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
767 
768   llvm::ArrayRef<syntax::Token> PragmaOnce = findSpelled("# pragma once");
769   EXPECT_THAT(
770       Buffer.expansionStartingAt(&PragmaOnce.front()),
771       ValueIs(IsExpansion(SameRange(PragmaOnce),
772                           SameRange(findExpanded("int b").take_front(0)))));
773   // Only the first spelled token should be found.
774   for (const auto &T : PragmaOnce.drop_front())
775     EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
776 }
777 
778 TEST_F(TokenBufferTest, TokensToFileRange) {
779   addFile("./foo.h", "token_from_header");
780   llvm::Annotations Code(R"cpp(
781     #define FOO token_from_expansion
782     #include "./foo.h"
783     $all[[$i[[int]] a = FOO;]]
784   )cpp");
785   recordTokens(Code.code());
786 
787   auto &SM = *SourceMgr;
788 
789   // Two simple examples.
790   auto Int = findExpanded("int").front();
791   auto Semi = findExpanded(";").front();
792   EXPECT_EQ(Int.range(SM), FileRange(SM.getMainFileID(), Code.range("i").Begin,
793                                      Code.range("i").End));
794   EXPECT_EQ(syntax::Token::range(SM, Int, Semi),
795             FileRange(SM.getMainFileID(), Code.range("all").Begin,
796                       Code.range("all").End));
797   // We don't test assertion failures because death tests are slow.
798 }
799 
800 TEST_F(TokenBufferTest, MacroExpansions) {
801   llvm::Annotations Code(R"cpp(
802     #define FOO B
803     #define FOO2 BA
804     #define CALL(X) int X
805     #define G CALL(FOO2)
806     int B;
807     $macro[[FOO]];
808     $macro[[CALL]](A);
809     $macro[[G]];
810   )cpp");
811   recordTokens(Code.code());
812   auto &SM = *SourceMgr;
813   auto Expansions = Buffer.macroExpansions(SM.getMainFileID());
814   std::vector<FileRange> ExpectedMacroRanges;
815   for (auto Range : Code.ranges("macro"))
816     ExpectedMacroRanges.push_back(
817         FileRange(SM.getMainFileID(), Range.Begin, Range.End));
818   std::vector<FileRange> ActualMacroRanges;
819   for (auto Expansion : Expansions)
820     ActualMacroRanges.push_back(Expansion->range(SM));
821   EXPECT_EQ(ExpectedMacroRanges, ActualMacroRanges);
822 }
823 
824 TEST_F(TokenBufferTest, Touching) {
825   llvm::Annotations Code("^i^nt^ ^a^b^=^1;^");
826   recordTokens(Code.code());
827 
828   auto Touching = [&](int Index) {
829     SourceLocation Loc = SourceMgr->getComposedLoc(SourceMgr->getMainFileID(),
830                                                    Code.points()[Index]);
831     return spelledTokensTouching(Loc, Buffer);
832   };
833   auto Identifier = [&](int Index) {
834     SourceLocation Loc = SourceMgr->getComposedLoc(SourceMgr->getMainFileID(),
835                                                    Code.points()[Index]);
836     const syntax::Token *Tok = spelledIdentifierTouching(Loc, Buffer);
837     return Tok ? Tok->text(*SourceMgr) : "";
838   };
839 
840   EXPECT_THAT(Touching(0), SameRange(findSpelled("int")));
841   EXPECT_EQ(Identifier(0), "");
842   EXPECT_THAT(Touching(1), SameRange(findSpelled("int")));
843   EXPECT_EQ(Identifier(1), "");
844   EXPECT_THAT(Touching(2), SameRange(findSpelled("int")));
845   EXPECT_EQ(Identifier(2), "");
846 
847   EXPECT_THAT(Touching(3), SameRange(findSpelled("ab")));
848   EXPECT_EQ(Identifier(3), "ab");
849   EXPECT_THAT(Touching(4), SameRange(findSpelled("ab")));
850   EXPECT_EQ(Identifier(4), "ab");
851 
852   EXPECT_THAT(Touching(5), SameRange(findSpelled("ab =")));
853   EXPECT_EQ(Identifier(5), "ab");
854 
855   EXPECT_THAT(Touching(6), SameRange(findSpelled("= 1")));
856   EXPECT_EQ(Identifier(6), "");
857 
858   EXPECT_THAT(Touching(7), SameRange(findSpelled(";")));
859   EXPECT_EQ(Identifier(7), "");
860 
861   ASSERT_EQ(Code.points().size(), 8u);
862 }
863 
864 } // namespace
865