xref: /llvm-project/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp (revision 484402abaca2b2523487b564c7d5173404b448af)
1 //===-- SourceCodeTests.cpp  ------------------------------------*- C++ -*-===//
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 "Annotations.h"
9 #include "Context.h"
10 #include "Protocol.h"
11 #include "SourceCode.h"
12 #include "TestTU.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Format/Format.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/raw_os_ostream.h"
18 #include "llvm/Testing/Support/Annotations.h"
19 #include "llvm/Testing/Support/Error.h"
20 #include "gmock/gmock.h"
21 #include "gtest/gtest.h"
22 #include <tuple>
23 
24 namespace clang {
25 namespace clangd {
26 namespace {
27 
28 using llvm::Failed;
29 using llvm::HasValue;
30 
31 MATCHER_P2(Pos, Line, Col, "") {
32   return arg.line == int(Line) && arg.character == int(Col);
33 }
34 
35 MATCHER_P(MacroName, Name, "") { return arg.Name == Name; }
36 
37 /// A helper to make tests easier to read.
38 Position position(int Line, int Character) {
39   Position Pos;
40   Pos.line = Line;
41   Pos.character = Character;
42   return Pos;
43 }
44 
45 Range range(const std::pair<int, int> &P1, const std::pair<int, int> &P2) {
46   Range Range;
47   Range.start = position(P1.first, P1.second);
48   Range.end = position(P2.first, P2.second);
49   return Range;
50 }
51 
52 TEST(SourceCodeTests, lspLength) {
53   EXPECT_EQ(lspLength(""), 0UL);
54   EXPECT_EQ(lspLength("ascii"), 5UL);
55   // BMP
56   EXPECT_EQ(lspLength("↓"), 1UL);
57   EXPECT_EQ(lspLength("¥"), 1UL);
58   // astral
59   EXPECT_EQ(lspLength("��"), 2UL);
60 
61   WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
62   EXPECT_EQ(lspLength(""), 0UL);
63   EXPECT_EQ(lspLength("ascii"), 5UL);
64   // BMP
65   EXPECT_EQ(lspLength("↓"), 3UL);
66   EXPECT_EQ(lspLength("¥"), 2UL);
67   // astral
68   EXPECT_EQ(lspLength("��"), 4UL);
69 
70   WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
71   EXPECT_EQ(lspLength(""), 0UL);
72   EXPECT_EQ(lspLength("ascii"), 5UL);
73   // BMP
74   EXPECT_EQ(lspLength("↓"), 1UL);
75   EXPECT_EQ(lspLength("¥"), 1UL);
76   // astral
77   EXPECT_EQ(lspLength("��"), 1UL);
78 }
79 
80 // The = → �� below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
81 const char File[] = R"(0:0 = 0
82 1:0 → 8
83 2:0 �� 18)";
84 struct Line {
85   unsigned Number;
86   unsigned Offset;
87   unsigned Length;
88 };
89 Line FileLines[] = {Line{0, 0, 7}, Line{1, 8, 9}, Line{2, 18, 11}};
90 
91 TEST(SourceCodeTests, PositionToOffset) {
92   // line out of bounds
93   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
94   // first line
95   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
96                        llvm::Failed()); // out of range
97   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
98                        llvm::HasValue(0)); // first character
99   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
100                        llvm::HasValue(3)); // middle character
101   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
102                        llvm::HasValue(6)); // last character
103   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
104                        llvm::HasValue(7)); // the newline itself
105   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
106                        llvm::HasValue(7));
107   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
108                        llvm::HasValue(7)); // out of range
109   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
110                        llvm::Failed()); // out of range
111   // middle line
112   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
113                        llvm::Failed()); // out of range
114   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
115                        llvm::HasValue(8)); // first character
116   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
117                        llvm::HasValue(11)); // middle character
118   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
119                        llvm::HasValue(11));
120   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
121                        llvm::HasValue(16)); // last character
122   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
123                        llvm::HasValue(17)); // the newline itself
124   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
125                        llvm::HasValue(17)); // out of range
126   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
127                        llvm::Failed()); // out of range
128   // last line
129   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
130                        llvm::Failed()); // out of range
131   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
132                        llvm::HasValue(18)); // first character
133   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 3)),
134                        llvm::HasValue(21)); // middle character
135   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
136                        llvm::Failed()); // middle of surrogate pair
137   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5)),
138                        llvm::HasValue(26)); // middle of surrogate pair
139   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 6), false),
140                        llvm::HasValue(26)); // end of surrogate pair
141   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
142                        llvm::HasValue(28)); // last character
143   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9)),
144                        llvm::HasValue(29)); // EOF
145   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 10), false),
146                        llvm::Failed()); // out of range
147   // line out of bounds
148   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
149   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
150 
151   // Codepoints are similar, except near astral characters.
152   WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
153   // line out of bounds
154   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
155   // first line
156   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
157                        llvm::Failed()); // out of range
158   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
159                        llvm::HasValue(0)); // first character
160   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
161                        llvm::HasValue(3)); // middle character
162   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
163                        llvm::HasValue(6)); // last character
164   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
165                        llvm::HasValue(7)); // the newline itself
166   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
167                        llvm::HasValue(7));
168   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
169                        llvm::HasValue(7)); // out of range
170   EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
171                        llvm::Failed()); // out of range
172   // middle line
173   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
174                        llvm::Failed()); // out of range
175   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
176                        llvm::HasValue(8)); // first character
177   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
178                        llvm::HasValue(11)); // middle character
179   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
180                        llvm::HasValue(11));
181   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
182                        llvm::HasValue(16)); // last character
183   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
184                        llvm::HasValue(17)); // the newline itself
185   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
186                        llvm::HasValue(17)); // out of range
187   EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
188                        llvm::Failed()); // out of range
189   // last line
190   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
191                        llvm::Failed()); // out of range
192   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
193                        llvm::HasValue(18)); // first character
194   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 4)),
195                        llvm::HasValue(22)); // Before astral character.
196   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
197                        llvm::HasValue(26)); // after astral character
198   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 7)),
199                        llvm::HasValue(28)); // last character
200   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
201                        llvm::HasValue(29)); // EOF
202   EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9), false),
203                        llvm::Failed()); // out of range
204   // line out of bounds
205   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
206   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
207 
208   // Test UTF-8, where transformations are trivial.
209   WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
210   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
211   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
212   for (Line L : FileLines) {
213     EXPECT_THAT_EXPECTED(positionToOffset(File, position(L.Number, -1)),
214                          llvm::Failed()); // out of range
215     for (unsigned I = 0; I <= L.Length; ++I)
216       EXPECT_THAT_EXPECTED(positionToOffset(File, position(L.Number, I)),
217                            llvm::HasValue(L.Offset + I));
218     EXPECT_THAT_EXPECTED(
219         positionToOffset(File, position(L.Number, L.Length + 1)),
220         llvm::HasValue(L.Offset + L.Length));
221     EXPECT_THAT_EXPECTED(
222         positionToOffset(File, position(L.Number, L.Length + 1), false),
223         llvm::Failed()); // out of range
224   }
225 }
226 
227 TEST(SourceCodeTests, OffsetToPosition) {
228   EXPECT_THAT(offsetToPosition(File, 0), Pos(0, 0)) << "start of file";
229   EXPECT_THAT(offsetToPosition(File, 3), Pos(0, 3)) << "in first line";
230   EXPECT_THAT(offsetToPosition(File, 6), Pos(0, 6)) << "end of first line";
231   EXPECT_THAT(offsetToPosition(File, 7), Pos(0, 7)) << "first newline";
232   EXPECT_THAT(offsetToPosition(File, 8), Pos(1, 0)) << "start of second line";
233   EXPECT_THAT(offsetToPosition(File, 12), Pos(1, 4)) << "before BMP char";
234   EXPECT_THAT(offsetToPosition(File, 13), Pos(1, 5)) << "in BMP char";
235   EXPECT_THAT(offsetToPosition(File, 15), Pos(1, 5)) << "after BMP char";
236   EXPECT_THAT(offsetToPosition(File, 16), Pos(1, 6)) << "end of second line";
237   EXPECT_THAT(offsetToPosition(File, 17), Pos(1, 7)) << "second newline";
238   EXPECT_THAT(offsetToPosition(File, 18), Pos(2, 0)) << "start of last line";
239   EXPECT_THAT(offsetToPosition(File, 21), Pos(2, 3)) << "in last line";
240   EXPECT_THAT(offsetToPosition(File, 22), Pos(2, 4)) << "before astral char";
241   EXPECT_THAT(offsetToPosition(File, 24), Pos(2, 6)) << "in astral char";
242   EXPECT_THAT(offsetToPosition(File, 26), Pos(2, 6)) << "after astral char";
243   EXPECT_THAT(offsetToPosition(File, 28), Pos(2, 8)) << "end of last line";
244   EXPECT_THAT(offsetToPosition(File, 29), Pos(2, 9)) << "EOF";
245   EXPECT_THAT(offsetToPosition(File, 30), Pos(2, 9)) << "out of bounds";
246 
247   // Codepoints are similar, except near astral characters.
248   WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
249   EXPECT_THAT(offsetToPosition(File, 0), Pos(0, 0)) << "start of file";
250   EXPECT_THAT(offsetToPosition(File, 3), Pos(0, 3)) << "in first line";
251   EXPECT_THAT(offsetToPosition(File, 6), Pos(0, 6)) << "end of first line";
252   EXPECT_THAT(offsetToPosition(File, 7), Pos(0, 7)) << "first newline";
253   EXPECT_THAT(offsetToPosition(File, 8), Pos(1, 0)) << "start of second line";
254   EXPECT_THAT(offsetToPosition(File, 12), Pos(1, 4)) << "before BMP char";
255   EXPECT_THAT(offsetToPosition(File, 13), Pos(1, 5)) << "in BMP char";
256   EXPECT_THAT(offsetToPosition(File, 15), Pos(1, 5)) << "after BMP char";
257   EXPECT_THAT(offsetToPosition(File, 16), Pos(1, 6)) << "end of second line";
258   EXPECT_THAT(offsetToPosition(File, 17), Pos(1, 7)) << "second newline";
259   EXPECT_THAT(offsetToPosition(File, 18), Pos(2, 0)) << "start of last line";
260   EXPECT_THAT(offsetToPosition(File, 21), Pos(2, 3)) << "in last line";
261   EXPECT_THAT(offsetToPosition(File, 22), Pos(2, 4)) << "before astral char";
262   EXPECT_THAT(offsetToPosition(File, 24), Pos(2, 5)) << "in astral char";
263   EXPECT_THAT(offsetToPosition(File, 26), Pos(2, 5)) << "after astral char";
264   EXPECT_THAT(offsetToPosition(File, 28), Pos(2, 7)) << "end of last line";
265   EXPECT_THAT(offsetToPosition(File, 29), Pos(2, 8)) << "EOF";
266   EXPECT_THAT(offsetToPosition(File, 30), Pos(2, 8)) << "out of bounds";
267 
268   WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
269   for (Line L : FileLines) {
270     for (unsigned I = 0; I <= L.Length; ++I)
271       EXPECT_THAT(offsetToPosition(File, L.Offset + I), Pos(L.Number, I));
272   }
273   EXPECT_THAT(offsetToPosition(File, 30), Pos(2, 11)) << "out of bounds";
274 }
275 
276 TEST(SourceCodeTests, IsRangeConsecutive) {
277   EXPECT_TRUE(isRangeConsecutive(range({2, 2}, {2, 3}), range({2, 3}, {2, 4})));
278   EXPECT_FALSE(
279       isRangeConsecutive(range({0, 2}, {0, 3}), range({2, 3}, {2, 4})));
280   EXPECT_FALSE(
281       isRangeConsecutive(range({2, 2}, {2, 3}), range({2, 4}, {2, 5})));
282 }
283 
284 TEST(SourceCodeTests, SourceLocationInMainFile) {
285   Annotations Source(R"cpp(
286     ^in^t ^foo
287     ^bar
288     ^baz ^() {}  {} {} {} { }^
289 )cpp");
290 
291   SourceManagerForFile Owner("foo.cpp", Source.code());
292   SourceManager &SM = Owner.get();
293 
294   SourceLocation StartOfFile = SM.getLocForStartOfFile(SM.getMainFileID());
295   EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, position(0, 0)),
296                        HasValue(StartOfFile));
297   // End of file.
298   EXPECT_THAT_EXPECTED(
299       sourceLocationInMainFile(SM, position(4, 0)),
300       HasValue(StartOfFile.getLocWithOffset(Source.code().size())));
301   // Column number is too large.
302   EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, position(0, 1)), Failed());
303   EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, position(0, 100)),
304                        Failed());
305   EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, position(4, 1)), Failed());
306   // Line number is too large.
307   EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, position(5, 0)), Failed());
308   // Check all positions mentioned in the test return valid results.
309   for (auto P : Source.points()) {
310     size_t Offset = llvm::cantFail(positionToOffset(Source.code(), P));
311     EXPECT_THAT_EXPECTED(sourceLocationInMainFile(SM, P),
312                          HasValue(StartOfFile.getLocWithOffset(Offset)));
313   }
314 }
315 
316 TEST(SourceCodeTests, CollectIdentifiers) {
317   auto Style = format::getLLVMStyle();
318   auto IDs = collectIdentifiers(R"cpp(
319   #include "a.h"
320   void foo() { int xyz; int abc = xyz; return foo(); }
321   )cpp",
322                                 Style);
323   EXPECT_EQ(IDs.size(), 7u);
324   EXPECT_EQ(IDs["include"], 1u);
325   EXPECT_EQ(IDs["void"], 1u);
326   EXPECT_EQ(IDs["int"], 2u);
327   EXPECT_EQ(IDs["xyz"], 2u);
328   EXPECT_EQ(IDs["abc"], 1u);
329   EXPECT_EQ(IDs["return"], 1u);
330   EXPECT_EQ(IDs["foo"], 2u);
331 }
332 
333 TEST(SourceCodeTests, CollectWords) {
334   auto Words = collectWords(R"cpp(
335   #define FIZZ_BUZZ
336   // this is a comment
337   std::string getSomeText() { return "magic word"; }
338   )cpp");
339   std::set<StringRef> ActualWords(Words.keys().begin(), Words.keys().end());
340   std::set<StringRef> ExpectedWords = {"define",  "fizz",   "buzz", "this",
341                                        "comment", "string", "some", "text",
342                                        "return",  "magic",  "word"};
343   EXPECT_EQ(ActualWords, ExpectedWords);
344 }
345 
346 TEST(SourceCodeTests, VisibleNamespaces) {
347   std::vector<std::pair<const char *, std::vector<std::string>>> Cases = {
348       {
349           R"cpp(
350             // Using directive resolved against enclosing namespaces.
351             using namespace foo;
352             namespace ns {
353             using namespace bar;
354           )cpp",
355           {"ns", "", "bar", "foo", "ns::bar"},
356       },
357       {
358           R"cpp(
359             // Don't include namespaces we've closed, ignore namespace aliases.
360             using namespace clang;
361             using std::swap;
362             namespace clang {
363             namespace clangd {}
364             namespace ll = ::llvm;
365             }
366             namespace clang {
367           )cpp",
368           {"clang", ""},
369       },
370       {
371           R"cpp(
372             // Using directives visible even if a namespace is reopened.
373             // Ignore anonymous namespaces.
374             namespace foo{ using namespace bar; }
375             namespace foo{ namespace {
376           )cpp",
377           {"foo", "", "bar", "foo::bar"},
378       },
379       {
380           R"cpp(
381             // Mismatched braces
382             namespace foo{}
383             }}}
384             namespace bar{
385           )cpp",
386           {"bar", ""},
387       },
388       {
389           R"cpp(
390             // Namespaces with multiple chunks.
391             namespace a::b {
392               using namespace c::d;
393               namespace e::f {
394           )cpp",
395           {
396               "a::b::e::f",
397               "",
398               "a",
399               "a::b",
400               "a::b::c::d",
401               "a::b::e",
402               "a::c::d",
403               "c::d",
404           },
405       },
406       {
407           "",
408           {""},
409       },
410       {
411           R"cpp(
412             // Parse until EOF
413             namespace bar{})cpp",
414           {""},
415       },
416   };
417   for (const auto &Case : Cases) {
418     EXPECT_EQ(Case.second,
419               visibleNamespaces(Case.first, format::getLLVMStyle()))
420         << Case.first;
421   }
422 }
423 
424 TEST(SourceCodeTests, GetMacros) {
425   Annotations Code(R"cpp(
426      #define MACRO 123
427      int abc = MA^CRO;
428    )cpp");
429   TestTU TU = TestTU::withCode(Code.code());
430   auto AST = TU.build();
431   auto CurLoc = sourceLocationInMainFile(AST.getSourceManager(), Code.point());
432   ASSERT_TRUE(bool(CurLoc));
433   const auto *Id = syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
434   ASSERT_TRUE(Id);
435   auto Result = locateMacroAt(*Id, AST.getPreprocessor());
436   ASSERT_TRUE(Result);
437   EXPECT_THAT(*Result, MacroName("MACRO"));
438 }
439 
440 TEST(SourceCodeTests, WorksAtBeginOfFile) {
441   Annotations Code("^MACRO");
442   TestTU TU = TestTU::withCode(Code.code());
443   TU.HeaderCode = "#define MACRO int x;";
444   auto AST = TU.build();
445   auto CurLoc = sourceLocationInMainFile(AST.getSourceManager(), Code.point());
446   ASSERT_TRUE(bool(CurLoc));
447   const auto *Id = syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
448   ASSERT_TRUE(Id);
449   auto Result = locateMacroAt(*Id, AST.getPreprocessor());
450   ASSERT_TRUE(Result);
451   EXPECT_THAT(*Result, MacroName("MACRO"));
452 }
453 
454 TEST(SourceCodeTests, IsInsideMainFile) {
455   TestTU TU;
456   TU.HeaderCode = R"cpp(
457     #define DEFINE_CLASS(X) class X {};
458     #define DEFINE_YY DEFINE_CLASS(YY)
459 
460     class Header1 {};
461     DEFINE_CLASS(Header2)
462     class Header {};
463   )cpp";
464   TU.Code = R"cpp(
465     #define DEFINE_MAIN4 class Main4{};
466     class Main1 {};
467     DEFINE_CLASS(Main2)
468     DEFINE_YY
469     class Main {};
470     DEFINE_MAIN4
471   )cpp";
472   TU.ExtraArgs.push_back("-DHeader=Header3");
473   TU.ExtraArgs.push_back("-DMain=Main3");
474   auto AST = TU.build();
475   const auto &SM = AST.getSourceManager();
476   auto DeclLoc = [&AST](llvm::StringRef Name) {
477     return findDecl(AST, Name).getLocation();
478   };
479   for (const auto *HeaderDecl : {"Header1", "Header2", "Header3"})
480     EXPECT_FALSE(isInsideMainFile(DeclLoc(HeaderDecl), SM)) << HeaderDecl;
481 
482   for (const auto *MainDecl : {"Main1", "Main2", "Main3", "Main4", "YY"})
483     EXPECT_TRUE(isInsideMainFile(DeclLoc(MainDecl), SM)) << MainDecl;
484 
485   // Main4 is *spelled* in the preamble, but in the main-file part of it.
486   EXPECT_TRUE(isInsideMainFile(SM.getSpellingLoc(DeclLoc("Main4")), SM));
487 }
488 
489 // Test for functions toHalfOpenFileRange and getHalfOpenFileRange
490 TEST(SourceCodeTests, HalfOpenFileRange) {
491   // Each marked range should be the file range of the decl with the same name
492   // and each name should be unique.
493   Annotations Test(R"cpp(
494     #define FOO(X, Y) int Y = ++X
495     #define BAR(X) X + 1
496     #define ECHO(X) X
497 
498     #define BUZZ BAZZ(ADD)
499     #define BAZZ(m) m(1)
500     #define ADD(a) int f = a + 1;
501     template<typename T>
502     class P {};
503 
504     int main() {
505       $a[[P<P<P<P<P<int>>>>> a]];
506       $b[[int b = 1]];
507       $c[[FOO(b, c)]];
508       $d[[FOO(BAR(BAR(b)), d)]];
509       // FIXME: We might want to select everything inside the outer ECHO.
510       ECHO(ECHO($e[[int) ECHO(e]]));
511       // Shouldn't crash.
512       $f[[BUZZ]];
513     }
514   )cpp");
515 
516   ParsedAST AST = TestTU::withCode(Test.code()).build();
517   llvm::errs() << Test.code();
518   const SourceManager &SM = AST.getSourceManager();
519   const LangOptions &LangOpts = AST.getLangOpts();
520   // Turn a SourceLocation into a pair of positions
521   auto SourceRangeToRange = [&SM](SourceRange SrcRange) {
522     return Range{sourceLocToPosition(SM, SrcRange.getBegin()),
523                  sourceLocToPosition(SM, SrcRange.getEnd())};
524   };
525   auto CheckRange = [&](llvm::StringRef Name) {
526     const NamedDecl &Decl = findUnqualifiedDecl(AST, Name);
527     auto FileRange = toHalfOpenFileRange(SM, LangOpts, Decl.getSourceRange());
528     SCOPED_TRACE("Checking range: " + Name);
529     ASSERT_NE(FileRange, llvm::None);
530     Range HalfOpenRange = SourceRangeToRange(*FileRange);
531     EXPECT_EQ(HalfOpenRange, Test.ranges(Name)[0]);
532   };
533 
534   CheckRange("a");
535   CheckRange("b");
536   CheckRange("c");
537   CheckRange("d");
538   CheckRange("e");
539   CheckRange("f");
540 }
541 
542 TEST(SourceCodeTests, HalfOpenFileRangePathologicalPreprocessor) {
543   const char *Case = R"cpp(
544 #define MACRO while(1)
545     void test() {
546 [[#include "Expand.inc"
547         br^eak]];
548     }
549   )cpp";
550   Annotations Test(Case);
551   auto TU = TestTU::withCode(Test.code());
552   TU.AdditionalFiles["Expand.inc"] = "MACRO\n";
553   auto AST = TU.build();
554 
555   const auto &Func = cast<FunctionDecl>(findDecl(AST, "test"));
556   const auto &Body = cast<CompoundStmt>(Func.getBody());
557   const auto &Loop = cast<WhileStmt>(*Body->child_begin());
558   llvm::Optional<SourceRange> Range = toHalfOpenFileRange(
559       AST.getSourceManager(), AST.getLangOpts(), Loop->getSourceRange());
560   ASSERT_TRUE(Range) << "Failed to get file range";
561   EXPECT_EQ(AST.getSourceManager().getFileOffset(Range->getBegin()),
562             Test.llvm::Annotations::range().Begin);
563   EXPECT_EQ(AST.getSourceManager().getFileOffset(Range->getEnd()),
564             Test.llvm::Annotations::range().End);
565 }
566 
567 TEST(SourceCodeTests, IncludeHashLoc) {
568   const char *Case = R"cpp(
569 $foo^#include "foo.inc"
570 #define HEADER "bar.inc"
571   $bar^#  include HEADER
572   )cpp";
573   Annotations Test(Case);
574   auto TU = TestTU::withCode(Test.code());
575   TU.AdditionalFiles["foo.inc"] = "int foo;\n";
576   TU.AdditionalFiles["bar.inc"] = "int bar;\n";
577   auto AST = TU.build();
578   const auto &SM = AST.getSourceManager();
579 
580   FileID Foo = SM.getFileID(findDecl(AST, "foo").getLocation());
581   EXPECT_EQ(SM.getFileOffset(includeHashLoc(Foo, SM)),
582             Test.llvm::Annotations::point("foo"));
583   FileID Bar = SM.getFileID(findDecl(AST, "bar").getLocation());
584   EXPECT_EQ(SM.getFileOffset(includeHashLoc(Bar, SM)),
585             Test.llvm::Annotations::point("bar"));
586 }
587 
588 TEST(SourceCodeTests, GetEligiblePoints) {
589   constexpr struct {
590     const char *Code;
591     const char *FullyQualifiedName;
592     const char *EnclosingNamespace;
593   } Cases[] = {
594       {R"cpp(// FIXME: We should also mark positions before and after
595                  //declarations/definitions as eligible.
596               namespace ns1 {
597               namespace a { namespace ns2 {} }
598               namespace ns2 {^
599               void foo();
600               namespace {}
601               void bar() {}
602               namespace ns3 {}
603               class T {};
604               ^}
605               using namespace ns2;
606               })cpp",
607        "ns1::ns2::symbol", "ns1::ns2::"},
608       {R"cpp(
609               namespace ns1 {^
610               namespace a { namespace ns2 {} }
611               namespace b {}
612               namespace ns {}
613               ^})cpp",
614        "ns1::ns2::symbol", "ns1::"},
615       {R"cpp(
616               namespace x {
617               namespace a { namespace ns2 {} }
618               namespace b {}
619               namespace ns {}
620               }^)cpp",
621        "ns1::ns2::symbol", ""},
622       {R"cpp(
623               namespace ns1 {
624               namespace ns2 {^^}
625               namespace b {}
626               namespace ns2 {^^}
627               }
628               namespace ns1 {namespace ns2 {^^}})cpp",
629        "ns1::ns2::symbol", "ns1::ns2::"},
630       {R"cpp(
631               namespace ns1 {^
632               namespace ns {}
633               namespace b {}
634               namespace ns {}
635               ^}
636               namespace ns1 {^namespace ns {}^})cpp",
637        "ns1::ns2::symbol", "ns1::"},
638   };
639   for (auto Case : Cases) {
640     Annotations Test(Case.Code);
641 
642     auto Res = getEligiblePoints(Test.code(), Case.FullyQualifiedName,
643                                  format::getLLVMStyle());
644     EXPECT_THAT(Res.EligiblePoints, testing::ElementsAreArray(Test.points()))
645         << Test.code();
646     EXPECT_EQ(Res.EnclosingNamespace, Case.EnclosingNamespace) << Test.code();
647   }
648 }
649 
650 TEST(SourceCodeTests, IdentifierRanges) {
651   Annotations Code(R"cpp(
652    class [[Foo]] {};
653    // Foo
654    /* Foo */
655    void f([[Foo]]* foo1) {
656      [[Foo]] foo2;
657      auto S = [[Foo]]();
658 // cross-line identifier is not supported.
659 F\
660 o\
661 o foo2;
662    }
663   )cpp");
664   LangOptions LangOpts;
665   LangOpts.CPlusPlus = true;
666   EXPECT_EQ(Code.ranges(),
667             collectIdentifierRanges("Foo", Code.code(), LangOpts));
668 }
669 
670 TEST(SourceCodeTests, isHeaderFile) {
671   // Without lang options.
672   EXPECT_TRUE(isHeaderFile("foo.h"));
673   EXPECT_TRUE(isHeaderFile("foo.hh"));
674   EXPECT_TRUE(isHeaderFile("foo.hpp"));
675 
676   EXPECT_FALSE(isHeaderFile("foo.cpp"));
677   EXPECT_FALSE(isHeaderFile("foo.c++"));
678   EXPECT_FALSE(isHeaderFile("foo.cxx"));
679   EXPECT_FALSE(isHeaderFile("foo.cc"));
680   EXPECT_FALSE(isHeaderFile("foo.c"));
681   EXPECT_FALSE(isHeaderFile("foo.mm"));
682   EXPECT_FALSE(isHeaderFile("foo.m"));
683 
684   // With lang options
685   LangOptions LangOpts;
686   LangOpts.IsHeaderFile = true;
687   EXPECT_TRUE(isHeaderFile("string", LangOpts));
688   // Emulate cases where there is no "-x header" flag for a .h file, we still
689   // want to treat it as a header.
690   LangOpts.IsHeaderFile = false;
691   EXPECT_TRUE(isHeaderFile("header.h", LangOpts));
692 }
693 
694 } // namespace
695 } // namespace clangd
696 } // namespace clang
697