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   for (const Case &C : Cases) {
459     trace::TestTracer Tracer;
460     Annotations Test(C.Code);
461 
462     TestTU TU;
463     TU.Code = std::string(Test.code());
464 
465     TU.ExtraArgs.push_back("-xobjective-c++");
466 
467     auto AST = TU.build();
468     auto T = makeSelectionTree(C.Code, AST);
469     EXPECT_EQ("TranslationUnitDecl", nodeKind(&T.root())) << C.Code;
470 
471     if (Test.ranges().empty()) {
472       // If no [[range]] is marked in the example, there should be no selection.
473       EXPECT_FALSE(T.commonAncestor()) << C.Code << "\n" << T;
474       EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
475                   testing::IsEmpty());
476     } else {
477       // If there is an expected selection, common ancestor should exist
478       // with the appropriate node type.
479       EXPECT_EQ(C.CommonAncestorKind, nodeKind(T.commonAncestor()))
480           << C.Code << "\n"
481           << T;
482       // Convert the reported common ancestor to a range and verify it.
483       EXPECT_EQ(nodeRange(T.commonAncestor(), AST), Test.range())
484           << C.Code << "\n"
485           << T;
486 
487       // Check that common ancestor is reachable on exactly one path from root,
488       // and no nodes outside it are selected.
489       EXPECT_TRUE(verifyCommonAncestor(T.root(), T.commonAncestor(), C.Code))
490           << C.Code;
491       EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
492                   ElementsAreArray({0}));
493     }
494   }
495 }
496 
497 // Regression test: this used to match the injected X, not the outer X.
TEST(SelectionTest,InjectedClassName)498 TEST(SelectionTest, InjectedClassName) {
499   const char *Code = "struct ^X { int x; };";
500   auto AST = TestTU::withCode(Annotations(Code).code()).build();
501   auto T = makeSelectionTree(Code, AST);
502   ASSERT_EQ("CXXRecordDecl", nodeKind(T.commonAncestor())) << T;
503   auto *D = dyn_cast<CXXRecordDecl>(T.commonAncestor()->ASTNode.get<Decl>());
504   EXPECT_FALSE(D->isInjectedClassName());
505 }
506 
TEST(SelectionTree,Metrics)507 TEST(SelectionTree, Metrics) {
508   const char *Code = R"cpp(
509     // error-ok: testing behavior on recovery expression
510     int foo();
511     int foo(int, int);
512     int x = fo^o(42);
513   )cpp";
514   auto AST = TestTU::withCode(Annotations(Code).code()).build();
515   trace::TestTracer Tracer;
516   auto T = makeSelectionTree(Code, AST);
517   EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
518               ElementsAreArray({1}));
519   EXPECT_THAT(Tracer.takeMetric("selection_recovery_type", "C++"),
520               ElementsAreArray({1}));
521 }
522 
523 // FIXME: Doesn't select the binary operator node in
524 //          #define FOO(X) X + 1
525 //          int a, b = [[FOO(a)]];
TEST(SelectionTest,Selected)526 TEST(SelectionTest, Selected) {
527   // Selection with ^marks^.
528   // Partially selected nodes marked with a [[range]].
529   // Completely selected nodes marked with a $C[[range]].
530   const char *Cases[] = {
531       R"cpp( int abc, xyz = [[^ab^c]]; )cpp",
532       R"cpp( int abc, xyz = [[a^bc^]]; )cpp",
533       R"cpp( int abc, xyz = $C[[^abc^]]; )cpp",
534       R"cpp(
535         void foo() {
536           [[if ([[1^11]]) $C[[{
537             $C[[return]];
538           }]] else [[{^
539           }]]]]
540           char z;
541         }
542       )cpp",
543       R"cpp(
544           template <class T>
545           struct unique_ptr {};
546           void foo(^$C[[unique_ptr<$C[[unique_ptr<$C[[int]]>]]>]]^ a) {}
547       )cpp",
548       R"cpp(int a = [[5 >^> 1]];)cpp",
549       R"cpp(
550         #define ECHO(X) X
551         ECHO(EC^HO($C[[int]]) EC^HO(a));
552       )cpp",
553       R"cpp( $C[[^$C[[int]] a^]]; )cpp",
554       R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
555   };
556   for (const char *C : Cases) {
557     Annotations Test(C);
558     auto AST = TestTU::withCode(Test.code()).build();
559     auto T = makeSelectionTree(C, AST);
560 
561     std::vector<Range> Complete, Partial;
562     for (const SelectionTree::Node *N : allNodes(T))
563       if (N->Selected == SelectionTree::Complete)
564         Complete.push_back(nodeRange(N, AST));
565       else if (N->Selected == SelectionTree::Partial)
566         Partial.push_back(nodeRange(N, AST));
567     EXPECT_THAT(Complete, UnorderedElementsAreArray(Test.ranges("C"))) << C;
568     EXPECT_THAT(Partial, UnorderedElementsAreArray(Test.ranges())) << C;
569   }
570 }
571 
TEST(SelectionTest,PathologicalPreprocessor)572 TEST(SelectionTest, PathologicalPreprocessor) {
573   const char *Case = R"cpp(
574 #define MACRO while(1)
575     void test() {
576 #include "Expand.inc"
577         br^eak;
578     }
579   )cpp";
580   Annotations Test(Case);
581   auto TU = TestTU::withCode(Test.code());
582   TU.AdditionalFiles["Expand.inc"] = "MACRO\n";
583   auto AST = TU.build();
584   EXPECT_THAT(*AST.getDiagnostics(), ::testing::IsEmpty());
585   auto T = makeSelectionTree(Case, AST);
586 
587   EXPECT_EQ("BreakStmt", T.commonAncestor()->kind());
588   EXPECT_EQ("WhileStmt", T.commonAncestor()->Parent->kind());
589 }
590 
TEST(SelectionTest,IncludedFile)591 TEST(SelectionTest, IncludedFile) {
592   const char *Case = R"cpp(
593     void test() {
594 #include "Exp^and.inc"
595         break;
596     }
597   )cpp";
598   Annotations Test(Case);
599   auto TU = TestTU::withCode(Test.code());
600   TU.AdditionalFiles["Expand.inc"] = "while(1)\n";
601   auto AST = TU.build();
602   auto T = makeSelectionTree(Case, AST);
603 
604   EXPECT_EQ(nullptr, T.commonAncestor());
605 }
606 
TEST(SelectionTest,MacroArgExpansion)607 TEST(SelectionTest, MacroArgExpansion) {
608   // If a macro arg is expanded several times, we only consider the first one
609   // selected.
610   const char *Case = R"cpp(
611     int mul(int, int);
612     #define SQUARE(X) mul(X, X);
613     int nine = SQUARE(^3);
614   )cpp";
615   Annotations Test(Case);
616   auto AST = TestTU::withCode(Test.code()).build();
617   auto T = makeSelectionTree(Case, AST);
618   EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
619   EXPECT_TRUE(T.commonAncestor()->Selected);
620 
621   // Verify that the common assert() macro doesn't suffer from this.
622   // (This is because we don't associate the stringified token with the arg).
623   Case = R"cpp(
624     void die(const char*);
625     #define assert(x) (x ? (void)0 : die(#x))
626     void foo() { assert(^42); }
627   )cpp";
628   Test = Annotations(Case);
629   AST = TestTU::withCode(Test.code()).build();
630   T = makeSelectionTree(Case, AST);
631 
632   EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
633 }
634 
TEST(SelectionTest,Implicit)635 TEST(SelectionTest, Implicit) {
636   const char *Test = R"cpp(
637     struct S { S(const char*); };
638     int f(S);
639     int x = f("^");
640   )cpp";
641   auto AST = TestTU::withCode(Annotations(Test).code()).build();
642   auto T = makeSelectionTree(Test, AST);
643 
644   const SelectionTree::Node *Str = T.commonAncestor();
645   EXPECT_EQ("StringLiteral", nodeKind(Str)) << "Implicit selected?";
646   EXPECT_EQ("ImplicitCastExpr", nodeKind(Str->Parent));
647   EXPECT_EQ("CXXConstructExpr", nodeKind(Str->Parent->Parent));
648   EXPECT_EQ(Str, &Str->Parent->Parent->ignoreImplicit())
649       << "Didn't unwrap " << nodeKind(&Str->Parent->Parent->ignoreImplicit());
650 
651   EXPECT_EQ("CXXConstructExpr", nodeKind(&Str->outerImplicit()));
652 }
653 
TEST(SelectionTest,CreateAll)654 TEST(SelectionTest, CreateAll) {
655   llvm::Annotations Test("int$unique^ a=1$ambiguous^+1; $empty^");
656   auto AST = TestTU::withCode(Test.code()).build();
657   unsigned Seen = 0;
658   SelectionTree::createEach(
659       AST.getASTContext(), AST.getTokens(), Test.point("ambiguous"),
660       Test.point("ambiguous"), [&](SelectionTree T) {
661         // Expect to see the right-biased tree first.
662         if (Seen == 0) {
663           EXPECT_EQ("BinaryOperator", nodeKind(T.commonAncestor()));
664         } else if (Seen == 1) {
665           EXPECT_EQ("IntegerLiteral", nodeKind(T.commonAncestor()));
666         }
667         ++Seen;
668         return false;
669       });
670   EXPECT_EQ(2u, Seen);
671 
672   Seen = 0;
673   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
674                             Test.point("ambiguous"), Test.point("ambiguous"),
675                             [&](SelectionTree T) {
676                               ++Seen;
677                               return true;
678                             });
679   EXPECT_EQ(1u, Seen) << "Return true --> stop iterating";
680 
681   Seen = 0;
682   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
683                             Test.point("unique"), Test.point("unique"),
684                             [&](SelectionTree T) {
685                               ++Seen;
686                               return false;
687                             });
688   EXPECT_EQ(1u, Seen) << "no ambiguity --> only one tree";
689 
690   Seen = 0;
691   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
692                             Test.point("empty"), Test.point("empty"),
693                             [&](SelectionTree T) {
694                               EXPECT_FALSE(T.commonAncestor());
695                               ++Seen;
696                               return false;
697                             });
698   EXPECT_EQ(1u, Seen) << "empty tree still created";
699 
700   Seen = 0;
701   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
702                             Test.point("unique"), Test.point("ambiguous"),
703                             [&](SelectionTree T) {
704                               ++Seen;
705                               return false;
706                             });
707   EXPECT_EQ(1u, Seen) << "one tree for nontrivial selection";
708 }
709 
710 } // namespace
711 } // namespace clangd
712 } // namespace clang
713