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