1 //===-- SelectionTests.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 #include "Annotations.h"
9 #include "Selection.h"
10 #include "SourceCode.h"
11 #include "TestTU.h"
12 #include "support/TestTracer.h"
13 #include "clang/AST/Decl.h"
14 #include "llvm/Support/Casting.h"
15 #include "gmock/gmock.h"
16 #include "gtest/gtest.h"
17 
18 namespace clang {
19 namespace clangd {
20 namespace {
21 using ::testing::ElementsAreArray;
22 using ::testing::UnorderedElementsAreArray;
23 
24 // Create a selection tree corresponding to a point or pair of points.
25 // This uses the precisely-defined createRight semantics. The fuzzier
26 // createEach is tested separately.
makeSelectionTree(const StringRef MarkedCode,ParsedAST & AST)27 SelectionTree makeSelectionTree(const StringRef MarkedCode, ParsedAST &AST) {
28   Annotations Test(MarkedCode);
29   switch (Test.points().size()) {
30   case 1: { // Point selection.
31     unsigned Offset = cantFail(positionToOffset(Test.code(), Test.point()));
32     return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
33                                       Offset, Offset);
34   }
35   case 2: // Range selection.
36     return SelectionTree::createRight(
37         AST.getASTContext(), AST.getTokens(),
38         cantFail(positionToOffset(Test.code(), Test.points()[0])),
39         cantFail(positionToOffset(Test.code(), Test.points()[1])));
40   default:
41     ADD_FAILURE() << "Expected 1-2 points for selection.\n" << MarkedCode;
42     return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), 0u,
43                                       0u);
44   }
45 }
46 
nodeRange(const SelectionTree::Node * N,ParsedAST & AST)47 Range nodeRange(const SelectionTree::Node *N, ParsedAST &AST) {
48   if (!N)
49     return Range{};
50   const SourceManager &SM = AST.getSourceManager();
51   const LangOptions &LangOpts = AST.getLangOpts();
52   StringRef Buffer = SM.getBufferData(SM.getMainFileID());
53   if (llvm::isa_and_nonnull<TranslationUnitDecl>(N->ASTNode.get<Decl>()))
54     return Range{Position{}, offsetToPosition(Buffer, Buffer.size())};
55   auto FileRange =
56       toHalfOpenFileRange(SM, LangOpts, N->ASTNode.getSourceRange());
57   assert(FileRange && "We should be able to get the File Range");
58   return Range{
59       offsetToPosition(Buffer, SM.getFileOffset(FileRange->getBegin())),
60       offsetToPosition(Buffer, SM.getFileOffset(FileRange->getEnd()))};
61 }
62 
nodeKind(const SelectionTree::Node * N)63 std::string nodeKind(const SelectionTree::Node *N) {
64   return N ? N->kind() : "<null>";
65 }
66 
allNodes(const SelectionTree & T)67 std::vector<const SelectionTree::Node *> allNodes(const SelectionTree &T) {
68   std::vector<const SelectionTree::Node *> Result = {&T.root()};
69   for (unsigned I = 0; I < Result.size(); ++I) {
70     const SelectionTree::Node *N = Result[I];
71     Result.insert(Result.end(), N->Children.begin(), N->Children.end());
72   }
73   return Result;
74 }
75 
76 // Returns true if Common is a descendent of Root.
77 // Verifies nothing is selected above Common.
verifyCommonAncestor(const SelectionTree::Node & Root,const SelectionTree::Node * Common,StringRef MarkedCode)78 bool verifyCommonAncestor(const SelectionTree::Node &Root,
79                           const SelectionTree::Node *Common,
80                           StringRef MarkedCode) {
81   if (&Root == Common)
82     return true;
83   if (Root.Selected)
84     ADD_FAILURE() << "Selected nodes outside common ancestor\n" << MarkedCode;
85   bool Seen = false;
86   for (const SelectionTree::Node *Child : Root.Children)
87     if (verifyCommonAncestor(*Child, Common, MarkedCode)) {
88       if (Seen)
89         ADD_FAILURE() << "Saw common ancestor twice\n" << MarkedCode;
90       Seen = true;
91     }
92   return Seen;
93 }
94 
TEST(SelectionTest,CommonAncestor)95 TEST(SelectionTest, CommonAncestor) {
96   struct Case {
97     // Selection is between ^marks^.
98     // common ancestor marked with a [[range]].
99     const char *Code;
100     const char *CommonAncestorKind;
101   };
102   Case Cases[] = {
103       {
104           R"cpp(
105             template <typename T>
106             int x = [[T::^U::]]ccc();
107           )cpp",
108           "NestedNameSpecifierLoc",
109       },
110       {
111           R"cpp(
112             struct AAA { struct BBB { static int ccc(); };};
113             int x = AAA::[[B^B^B]]::ccc();
114           )cpp",
115           "RecordTypeLoc",
116       },
117       {
118           R"cpp(
119             struct AAA { struct BBB { static int ccc(); };};
120             int x = AAA::[[B^BB^]]::ccc();
121           )cpp",
122           "RecordTypeLoc",
123       },
124       {
125           R"cpp(
126             struct AAA { struct BBB { static int ccc(); };};
127             int x = [[AAA::BBB::c^c^c]]();
128           )cpp",
129           "DeclRefExpr",
130       },
131       {
132           R"cpp(
133             struct AAA { struct BBB { static int ccc(); };};
134             int x = [[AAA::BBB::cc^c(^)]];
135           )cpp",
136           "CallExpr",
137       },
138 
139       {
140           R"cpp(
141             void foo() { [[if (1^11) { return; } else {^ }]] }
142           )cpp",
143           "IfStmt",
144       },
145       {
146           R"cpp(
147             int x(int);
148             #define M(foo) x(foo)
149             int a = 42;
150             int b = M([[^a]]);
151           )cpp",
152           "DeclRefExpr",
153       },
154       {
155           R"cpp(
156             void foo();
157             #define CALL_FUNCTION(X) X()
158             void bar() { CALL_FUNCTION([[f^o^o]]); }
159           )cpp",
160           "DeclRefExpr",
161       },
162       {
163           R"cpp(
164             void foo();
165             #define CALL_FUNCTION(X) X()
166             void bar() { [[CALL_FUNC^TION(fo^o)]]; }
167           )cpp",
168           "CallExpr",
169       },
170       {
171           R"cpp(
172             void foo();
173             #define CALL_FUNCTION(X) X()
174             void bar() { [[C^ALL_FUNC^TION(foo)]]; }
175           )cpp",
176           "CallExpr",
177       },
178       {
179           R"cpp(
180             void foo();
181             #^define CALL_FUNCTION(X) X(^)
182             void bar() { CALL_FUNCTION(foo); }
183           )cpp",
184           nullptr,
185       },
186       {
187           R"cpp(
188             void foo();
189             #define CALL_FUNCTION(X) X()
190             void bar() { CALL_FUNCTION(foo^)^; }
191           )cpp",
192           nullptr,
193       },
194       {
195           R"cpp(
196             namespace ns {
197             #if 0
198             void fo^o() {}
199             #endif
200             }
201           )cpp",
202           nullptr,
203       },
204       {
205           R"cpp(
206             struct S { S(const char*); };
207             S [[s ^= "foo"]];
208           )cpp",
209           "CXXConstructExpr",
210       },
211       {
212           R"cpp(
213             struct S { S(const char*); };
214             [[S ^s = "foo"]];
215           )cpp",
216           "VarDecl",
217       },
218       {
219           R"cpp(
220             [[^void]] (*S)(int) = nullptr;
221           )cpp",
222           "BuiltinTypeLoc",
223       },
224       {
225           R"cpp(
226             [[void (*S)^(int)]] = nullptr;
227           )cpp",
228           "FunctionProtoTypeLoc",
229       },
230       {
231           R"cpp(
232             [[void (^*S)(int)]] = nullptr;
233           )cpp",
234           "FunctionProtoTypeLoc",
235       },
236       {
237           R"cpp(
238             [[void (*^S)(int) = nullptr]];
239           )cpp",
240           "VarDecl",
241       },
242       {
243           R"cpp(
244             [[void ^(*S)(int)]] = nullptr;
245           )cpp",
246           "FunctionProtoTypeLoc",
247       },
248       {
249           R"cpp(
250             struct S {
251               int foo() const;
252               int bar() { return [[f^oo]](); }
253             };
254           )cpp",
255           "MemberExpr", // Not implicit CXXThisExpr, or its implicit cast!
256       },
257       {
258           R"cpp(
259             auto lambda = [](const char*){ return 0; };
260             int x = lambda([["y^"]]);
261           )cpp",
262           "StringLiteral", // Not DeclRefExpr to operator()!
263       },
264       {
265           R"cpp(
266             struct Foo {};
267             struct Bar : [[v^ir^tual private Foo]] {};
268           )cpp",
269           "CXXBaseSpecifier",
270       },
271       {
272           R"cpp(
273             struct Foo {};
274             struct Bar : private [[Fo^o]] {};
275           )cpp",
276           "RecordTypeLoc",
277       },
278       {
279           R"cpp(
280             struct Foo {};
281             struct Bar : [[Fo^o]] {};
282           )cpp",
283           "RecordTypeLoc",
284       },
285 
286       // Point selections.
287       {"void foo() { [[^foo]](); }", "DeclRefExpr"},
288       {"void foo() { [[f^oo]](); }", "DeclRefExpr"},
289       {"void foo() { [[fo^o]](); }", "DeclRefExpr"},
290       {"void foo() { [[foo^()]]; }", "CallExpr"},
291       {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
292       {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
293       {"int x = [[42]]^;", "IntegerLiteral"},
294 
295       // Ignores whitespace, comments, and semicolons in the selection.
296       {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
297 
298       // Tricky case: FunctionTypeLoc in FunctionDecl has a hole in it.
299       {"[[^void]] foo();", "BuiltinTypeLoc"},
300       {"[[void foo^()]];", "FunctionProtoTypeLoc"},
301       {"[[^void foo^()]];", "FunctionDecl"},
302       {"[[void ^foo()]];", "FunctionDecl"},
303       // Tricky case: two VarDecls share a specifier.
304       {"[[int ^a]], b;", "VarDecl"},
305       {"[[int a, ^b]];", "VarDecl"},
306       // Tricky case: CXXConstructExpr wants to claim the whole init range.
307       {
308           R"cpp(
309             struct X { X(int); };
310             class Y {
311               X x;
312               Y() : [[^x(4)]] {}
313             };
314           )cpp",
315           "CXXCtorInitializer", // Not the CXXConstructExpr!
316       },
317       // Tricky case: anonymous struct is a sibling of the VarDecl.
318       {"[[st^ruct {int x;}]] y;", "CXXRecordDecl"},
319       {"[[struct {int x;} ^y]];", "VarDecl"},
320       {"struct {[[int ^x]];} y;", "FieldDecl"},
321       // FIXME: the AST has no location info for qualifiers.
322       {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
323       {"[[co^nst auto x = 42]];", "VarDecl"},
324 
325       {"^", nullptr},
326       {"void foo() { [[foo^^]] (); }", "DeclRefExpr"},
327 
328       // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
329       // This doesn't happen now; the RAV doesn't traverse a node containing ;.
330       {"int x = 42;^", nullptr},
331 
332       // Common ancestor is logically TUDecl, but we never return that.
333       {"^int x; int y;^", nullptr},
334 
335       // Node types that have caused problems in the past.
336       {"template <typename T> void foo() { [[^T]] t; }",
337        "TemplateTypeParmTypeLoc"},
338 
339       // No crash
340       {
341           R"cpp(
342             template <class T> struct Foo {};
343             template <[[template<class> class /*cursor here*/^U]]>
344              struct Foo<U<int>*> {};
345           )cpp",
346           "TemplateTemplateParmDecl"},
347 
348       // Foreach has a weird AST, ensure we can select parts of the range init.
349       // This used to fail, because the DeclStmt for C claimed the whole range.
350       {
351           R"cpp(
352             struct Str {
353               const char *begin();
354               const char *end();
355             };
356             Str makeStr(const char*);
357             void loop() {
358               for (const char C : [[mak^eStr("foo"^)]])
359                 ;
360             }
361           )cpp",
362           "CallExpr"},
363 
364       // User-defined literals are tricky: is 12_i one token or two?
365       // For now we treat it as one, and the UserDefinedLiteral as a leaf.
366       {
367           R"cpp(
368             struct Foo{};
369             Foo operator""_ud(unsigned long long);
370             Foo x = [[^12_ud]];
371           )cpp",
372           "UserDefinedLiteral"},
373 
374       {
375           R"cpp(
376         int a;
377         decltype([[^a]] + a) b;
378         )cpp",
379           "DeclRefExpr"},
380 
381       // Objective-C nullability attributes.
382       {
383           R"cpp(
384             @interface I{}
385             @property(nullable) [[^I]] *x;
386             @end
387           )cpp",
388           "ObjCInterfaceTypeLoc"},
389       {
390           R"cpp(
391             @interface I{}
392             - (void)doSomething:(nonnull [[i^d]])argument;
393             @end
394           )cpp",
395           "TypedefTypeLoc"},
396 
397       // Objective-C OpaqueValueExpr/PseudoObjectExpr has weird ASTs.
398       // Need to traverse the contents of the OpaqueValueExpr to the POE,
399       // and ensure we traverse only the syntactic form of the PseudoObjectExpr.
400       {
401           R"cpp(
402             @interface I{}
403             @property(retain) I*x;
404             @property(retain) I*y;
405             @end
406             void test(I *f) { [[^f]].x.y = 0; }
407           )cpp",
408           "DeclRefExpr"},
409       {
410           R"cpp(
411             @interface I{}
412             @property(retain) I*x;
413             @property(retain) I*y;
414             @end
415             void test(I *f) { [[f.^x]].y = 0; }
416           )cpp",
417           "ObjCPropertyRefExpr"},
418       // Examples with implicit properties.
419       {
420           R"cpp(
421             @interface I{}
422             -(int)foo;
423             @end
424             int test(I *f) { return 42 + [[^f]].foo; }
425           )cpp",
426           "DeclRefExpr"},
427       {
428           R"cpp(
429             @interface I{}
430             -(int)foo;
431             @end
432             int test(I *f) { return 42 + [[f.^foo]]; }
433           )cpp",
434           "ObjCPropertyRefExpr"},
435       {"struct foo { [[int has^h<:32:>]]; };", "FieldDecl"},
436       {"struct foo { [[op^erator int()]]; };", "CXXConversionDecl"},
437       {"struct foo { [[^~foo()]]; };", "CXXDestructorDecl"},
438       // FIXME: The following to should be class itself instead.
439       {"struct foo { [[fo^o(){}]] };", "CXXConstructorDecl"},
440 
441       {R"cpp(
442         struct S1 { void f(); };
443         struct S2 { S1 * operator->(); };
444         void test(S2 s2) {
445           s2[[-^>]]f();
446         }
447       )cpp",
448        "DeclRefExpr"}, // DeclRefExpr to the "operator->" method.
449 
450       // Template template argument.
451       {R"cpp(
452         template <typename> class Vector {};
453         template <template <typename> class Container> class A {};
454         A<[[V^ector]]> a;
455       )cpp",
456        "TemplateArgumentLoc"},
457 
458       // Attributes
459       {R"cpp(
460         void f(int * __attribute__(([[no^nnull]])) );
461       )cpp",
462        "NonNullAttr"},
463 
464       {R"cpp(
465         // Digraph syntax for attributes to avoid accidental annotations.
466         class <:[gsl::Owner([[in^t]])]:> X{};
467       )cpp",
468        "BuiltinTypeLoc"},
469 
470       // This case used to crash - AST has a null Attr
471       {R"cpp(
472         @interface I
473         [[@property(retain, nonnull) <:[My^Object2]:> *x]]; // error-ok
474         @end
475       )cpp",
476        "ObjCPropertyDecl"}};
477 
478   for (const Case &C : Cases) {
479     trace::TestTracer Tracer;
480     Annotations Test(C.Code);
481 
482     TestTU TU;
483     TU.Code = std::string(Test.code());
484 
485     TU.ExtraArgs.push_back("-xobjective-c++");
486 
487     auto AST = TU.build();
488     auto T = makeSelectionTree(C.Code, AST);
489     EXPECT_EQ("TranslationUnitDecl", nodeKind(&T.root())) << C.Code;
490 
491     if (Test.ranges().empty()) {
492       // If no [[range]] is marked in the example, there should be no selection.
493       EXPECT_FALSE(T.commonAncestor()) << C.Code << "\n" << T;
494       EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
495                   testing::IsEmpty());
496     } else {
497       // If there is an expected selection, common ancestor should exist
498       // with the appropriate node type.
499       EXPECT_EQ(C.CommonAncestorKind, nodeKind(T.commonAncestor()))
500           << C.Code << "\n"
501           << T;
502       // Convert the reported common ancestor to a range and verify it.
503       EXPECT_EQ(nodeRange(T.commonAncestor(), AST), Test.range())
504           << C.Code << "\n"
505           << T;
506 
507       // Check that common ancestor is reachable on exactly one path from root,
508       // and no nodes outside it are selected.
509       EXPECT_TRUE(verifyCommonAncestor(T.root(), T.commonAncestor(), C.Code))
510           << C.Code;
511       EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
512                   ElementsAreArray({0}));
513     }
514   }
515 }
516 
517 // Regression test: this used to match the injected X, not the outer X.
TEST(SelectionTest,InjectedClassName)518 TEST(SelectionTest, InjectedClassName) {
519   const char *Code = "struct ^X { int x; };";
520   auto AST = TestTU::withCode(Annotations(Code).code()).build();
521   auto T = makeSelectionTree(Code, AST);
522   ASSERT_EQ("CXXRecordDecl", nodeKind(T.commonAncestor())) << T;
523   auto *D = dyn_cast<CXXRecordDecl>(T.commonAncestor()->ASTNode.get<Decl>());
524   EXPECT_FALSE(D->isInjectedClassName());
525 }
526 
TEST(SelectionTree,Metrics)527 TEST(SelectionTree, Metrics) {
528   const char *Code = R"cpp(
529     // error-ok: testing behavior on recovery expression
530     int foo();
531     int foo(int, int);
532     int x = fo^o(42);
533   )cpp";
534   auto AST = TestTU::withCode(Annotations(Code).code()).build();
535   trace::TestTracer Tracer;
536   auto T = makeSelectionTree(Code, AST);
537   EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
538               ElementsAreArray({1}));
539   EXPECT_THAT(Tracer.takeMetric("selection_recovery_type", "C++"),
540               ElementsAreArray({1}));
541 }
542 
543 // FIXME: Doesn't select the binary operator node in
544 //          #define FOO(X) X + 1
545 //          int a, b = [[FOO(a)]];
TEST(SelectionTest,Selected)546 TEST(SelectionTest, Selected) {
547   // Selection with ^marks^.
548   // Partially selected nodes marked with a [[range]].
549   // Completely selected nodes marked with a $C[[range]].
550   const char *Cases[] = {
551       R"cpp( int abc, xyz = [[^ab^c]]; )cpp",
552       R"cpp( int abc, xyz = [[a^bc^]]; )cpp",
553       R"cpp( int abc, xyz = $C[[^abc^]]; )cpp",
554       R"cpp(
555         void foo() {
556           [[if ([[1^11]]) $C[[{
557             $C[[return]];
558           }]] else [[{^
559           }]]]]
560           char z;
561         }
562       )cpp",
563       R"cpp(
564           template <class T>
565           struct unique_ptr {};
566           void foo(^$C[[unique_ptr<$C[[unique_ptr<$C[[int]]>]]>]]^ a) {}
567       )cpp",
568       R"cpp(int a = [[5 >^> 1]];)cpp",
569       R"cpp(
570         #define ECHO(X) X
571         ECHO(EC^HO($C[[int]]) EC^HO(a));
572       )cpp",
573       R"cpp( $C[[^$C[[int]] a^]]; )cpp",
574       R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
575   };
576   for (const char *C : Cases) {
577     Annotations Test(C);
578     auto AST = TestTU::withCode(Test.code()).build();
579     auto T = makeSelectionTree(C, AST);
580 
581     std::vector<Range> Complete, Partial;
582     for (const SelectionTree::Node *N : allNodes(T))
583       if (N->Selected == SelectionTree::Complete)
584         Complete.push_back(nodeRange(N, AST));
585       else if (N->Selected == SelectionTree::Partial)
586         Partial.push_back(nodeRange(N, AST));
587     EXPECT_THAT(Complete, UnorderedElementsAreArray(Test.ranges("C"))) << C;
588     EXPECT_THAT(Partial, UnorderedElementsAreArray(Test.ranges())) << C;
589   }
590 }
591 
TEST(SelectionTest,PathologicalPreprocessor)592 TEST(SelectionTest, PathologicalPreprocessor) {
593   const char *Case = R"cpp(
594 #define MACRO while(1)
595     void test() {
596 #include "Expand.inc"
597         br^eak;
598     }
599   )cpp";
600   Annotations Test(Case);
601   auto TU = TestTU::withCode(Test.code());
602   TU.AdditionalFiles["Expand.inc"] = "MACRO\n";
603   auto AST = TU.build();
604   EXPECT_THAT(*AST.getDiagnostics(), ::testing::IsEmpty());
605   auto T = makeSelectionTree(Case, AST);
606 
607   EXPECT_EQ("BreakStmt", T.commonAncestor()->kind());
608   EXPECT_EQ("WhileStmt", T.commonAncestor()->Parent->kind());
609 }
610 
TEST(SelectionTest,IncludedFile)611 TEST(SelectionTest, IncludedFile) {
612   const char *Case = R"cpp(
613     void test() {
614 #include "Exp^and.inc"
615         break;
616     }
617   )cpp";
618   Annotations Test(Case);
619   auto TU = TestTU::withCode(Test.code());
620   TU.AdditionalFiles["Expand.inc"] = "while(1)\n";
621   auto AST = TU.build();
622   auto T = makeSelectionTree(Case, AST);
623 
624   EXPECT_EQ(nullptr, T.commonAncestor());
625 }
626 
TEST(SelectionTest,MacroArgExpansion)627 TEST(SelectionTest, MacroArgExpansion) {
628   // If a macro arg is expanded several times, we only consider the first one
629   // selected.
630   const char *Case = R"cpp(
631     int mul(int, int);
632     #define SQUARE(X) mul(X, X);
633     int nine = SQUARE(^3);
634   )cpp";
635   Annotations Test(Case);
636   auto AST = TestTU::withCode(Test.code()).build();
637   auto T = makeSelectionTree(Case, AST);
638   EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
639   EXPECT_TRUE(T.commonAncestor()->Selected);
640 
641   // Verify that the common assert() macro doesn't suffer from this.
642   // (This is because we don't associate the stringified token with the arg).
643   Case = R"cpp(
644     void die(const char*);
645     #define assert(x) (x ? (void)0 : die(#x))
646     void foo() { assert(^42); }
647   )cpp";
648   Test = Annotations(Case);
649   AST = TestTU::withCode(Test.code()).build();
650   T = makeSelectionTree(Case, AST);
651 
652   EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
653 }
654 
TEST(SelectionTest,Implicit)655 TEST(SelectionTest, Implicit) {
656   const char *Test = R"cpp(
657     struct S { S(const char*); };
658     int f(S);
659     int x = f("^");
660   )cpp";
661   auto AST = TestTU::withCode(Annotations(Test).code()).build();
662   auto T = makeSelectionTree(Test, AST);
663 
664   const SelectionTree::Node *Str = T.commonAncestor();
665   EXPECT_EQ("StringLiteral", nodeKind(Str)) << "Implicit selected?";
666   EXPECT_EQ("ImplicitCastExpr", nodeKind(Str->Parent));
667   EXPECT_EQ("CXXConstructExpr", nodeKind(Str->Parent->Parent));
668   EXPECT_EQ(Str, &Str->Parent->Parent->ignoreImplicit())
669       << "Didn't unwrap " << nodeKind(&Str->Parent->Parent->ignoreImplicit());
670 
671   EXPECT_EQ("CXXConstructExpr", nodeKind(&Str->outerImplicit()));
672 }
673 
TEST(SelectionTest,CreateAll)674 TEST(SelectionTest, CreateAll) {
675   llvm::Annotations Test("int$unique^ a=1$ambiguous^+1; $empty^");
676   auto AST = TestTU::withCode(Test.code()).build();
677   unsigned Seen = 0;
678   SelectionTree::createEach(
679       AST.getASTContext(), AST.getTokens(), Test.point("ambiguous"),
680       Test.point("ambiguous"), [&](SelectionTree T) {
681         // Expect to see the right-biased tree first.
682         if (Seen == 0) {
683           EXPECT_EQ("BinaryOperator", nodeKind(T.commonAncestor()));
684         } else if (Seen == 1) {
685           EXPECT_EQ("IntegerLiteral", nodeKind(T.commonAncestor()));
686         }
687         ++Seen;
688         return false;
689       });
690   EXPECT_EQ(2u, Seen);
691 
692   Seen = 0;
693   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
694                             Test.point("ambiguous"), Test.point("ambiguous"),
695                             [&](SelectionTree T) {
696                               ++Seen;
697                               return true;
698                             });
699   EXPECT_EQ(1u, Seen) << "Return true --> stop iterating";
700 
701   Seen = 0;
702   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
703                             Test.point("unique"), Test.point("unique"),
704                             [&](SelectionTree T) {
705                               ++Seen;
706                               return false;
707                             });
708   EXPECT_EQ(1u, Seen) << "no ambiguity --> only one tree";
709 
710   Seen = 0;
711   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
712                             Test.point("empty"), Test.point("empty"),
713                             [&](SelectionTree T) {
714                               EXPECT_FALSE(T.commonAncestor());
715                               ++Seen;
716                               return false;
717                             });
718   EXPECT_EQ(1u, Seen) << "empty tree still created";
719 
720   Seen = 0;
721   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
722                             Test.point("unique"), Test.point("ambiguous"),
723                             [&](SelectionTree T) {
724                               ++Seen;
725                               return false;
726                             });
727   EXPECT_EQ(1u, Seen) << "one tree for nontrivial selection";
728 }
729 
730 } // namespace
731 } // namespace clangd
732 } // namespace clang
733