13#include "clang/AST/ASTConcept.h"
14#include "clang/AST/Decl.h"
15#include "llvm/Support/Casting.h"
16#include "gmock/gmock.h"
17#include "gtest/gtest.h"
22using ::testing::ElementsAreArray;
23using ::testing::UnorderedElementsAreArray;
30 switch (Test.points().size()) {
38 AST.getASTContext(),
AST.getTokens(),
42 ADD_FAILURE() <<
"Expected 1-2 points for selection.\n" << MarkedCode;
51 const SourceManager &SM =
AST.getSourceManager();
52 const LangOptions &LangOpts =
AST.getLangOpts();
53 StringRef Buffer = SM.getBufferData(SM.getMainFileID());
54 if (llvm::isa_and_nonnull<TranslationUnitDecl>(N->ASTNode.get<Decl>()))
58 assert(FileRange &&
"We should be able to get the File Range");
65 return N ? N->kind() :
"<null>";
68std::vector<const SelectionTree::Node *> allNodes(
const SelectionTree &T) {
69 std::vector<const SelectionTree::Node *> Result = {&
T.root()};
70 for (
unsigned I = 0; I < Result.size(); ++I) {
72 Result.insert(Result.end(), N->Children.begin(), N->Children.end());
81 StringRef MarkedCode) {
85 ADD_FAILURE() <<
"Selected nodes outside common ancestor\n" << MarkedCode;
88 if (verifyCommonAncestor(*Child, Common, MarkedCode)) {
90 ADD_FAILURE() <<
"Saw common ancestor twice\n" << MarkedCode;
96TEST(SelectionTest, CommonAncestor) {
101 const char *CommonAncestorKind;
106 template <typename T>
107 int x = T::[[^U]]::ccc();
109 "DependentNameTypeLoc",
113 struct AAA { struct BBB { static int ccc(); };};
114 int x = AAA::[[B^B^B]]::ccc();
120 struct AAA { struct BBB { static int ccc(); };};
121 int x = AAA::[[B^BB^]]::ccc();
127 struct AAA { struct BBB { static int ccc(); };};
128 int x = [[AAA::BBB::c^c^c]]();
134 struct AAA { struct BBB { static int ccc(); };};
135 int x = [[AAA::BBB::cc^c(^)]];
142 void foo() { [[if (1^11) { return; } else {^ }]] }
149 #define M(foo) x(foo)
158 #define CALL_FUNCTION(X) X()
159 void bar() { CALL_FUNCTION([[f^o^o]]); }
166 #define CALL_FUNCTION(X) X()
167 void bar() { [[CALL_FUNC^TION(fo^o)]]; }
174 #define CALL_FUNCTION(X) X()
175 void bar() { [[C^ALL_FUNC^TION(foo)]]; }
182 #^define CALL_FUNCTION(X) X(^)
183 void bar() { CALL_FUNCTION(foo); }
190 #define CALL_FUNCTION(X) X()
191 void bar() { CALL_FUNCTION(foo^)^; }
207 #define TARGET void foo()
208 [[TAR^GET{ return; }]]
214 struct S { S(const char*); };
224 struct S { S(const char*); };
231 [[^void]] (*S)(int) = nullptr;
237 [[void (*S)^(int)]] = nullptr;
239 "FunctionProtoTypeLoc",
243 [[void (^*S)(int)]] = nullptr;
249 [[void (*^S)(int) = nullptr]];
255 [[void ^(*S)(int)]] = nullptr;
263 int bar() { return [[f^oo]](); }
270 auto lambda = [](const char*){ return 0; };
271 int x = lambda([["y^"]]);
278 struct Bar : [[v^ir^tual private Foo]] {};
285 struct Bar : private [[Fo^o]] {};
292 struct Bar : [[Fo^o]] {};
298 {
"void foo() { [[^foo]](); }",
"DeclRefExpr"},
299 {
"void foo() { [[f^oo]](); }",
"DeclRefExpr"},
300 {
"void foo() { [[fo^o]](); }",
"DeclRefExpr"},
301 {
"void foo() { [[foo^()]]; }",
"CallExpr"},
302 {
"void foo() { [[foo^]] (); }",
"DeclRefExpr"},
303 {
"int bar; void foo() [[{ foo (); }]]^",
"CompoundStmt"},
304 {
"int x = [[42]]^;",
"IntegerLiteral"},
307 {
"void foo() { [[foo^()]]; /*comment*/^}",
"CallExpr"},
310 {
"[[^void]] foo();",
"BuiltinTypeLoc"},
311 {
"[[void foo^()]];",
"FunctionProtoTypeLoc"},
312 {
"[[^void foo^()]];",
"FunctionDecl"},
313 {
"[[void ^foo()]];",
"FunctionDecl"},
317 {
"struct X { [[const int* ^Get() const <:[clang::lifetimebound]:> "
318 "{return nullptr;}]]; };",
324 {
"struct X { const [[int* Foo() const <:<:clang::life^timebound]]:>:> "
325 "{return nullptr;}; };",
326 "AttributedTypeLoc"},
328 {
"[[int ^a]], b;",
"VarDecl"},
329 {
"[[int a, ^b]];",
"VarDecl"},
333 struct X { X(int); };
339 "CXXCtorInitializer",
342 {
"[[st^ruct {int x;}]] y;",
"CXXRecordDecl"},
343 {
"[[struct {int x;} ^y]];",
"VarDecl"},
344 {
"struct {[[int ^x]];} y;",
"FieldDecl"},
347 {
"const int x = 1, y = 2; int array[^[[x]]][10][y];",
"DeclRefExpr"},
348 {
"const int x = 1, y = 2; int array[x][10][^[[y]]];",
"DeclRefExpr"},
349 {
"const int x = 1, y = 2; int array[x][^[[10]]][y];",
"IntegerLiteral"},
350 {
"const int x = 1, y = 2; [[i^nt]] array[x][10][y];",
"BuiltinTypeLoc"},
351 {
"void func(int x) { int v_array[^[[x]]][10]; }",
"DeclRefExpr"},
353 {
"int (*getFunc([[do^uble]]))(int);",
"BuiltinTypeLoc"},
357 {
"class X{}; [[int X::^*]]y[10];",
"MemberPointerTypeLoc"},
358 {
"template<typename ...T> void foo([[T*^...]]x);",
359 "PackExpansionTypeLoc"},
360 {
"template<typename ...T> void foo([[^T]]*...x);",
361 "TemplateTypeParmTypeLoc"},
364 {
"const [[a^uto]] x = 42;",
"AutoTypeLoc"},
365 {
"co^nst auto x = 42;",
nullptr},
368 {
"void foo() { [[foo^^]] (); }",
"DeclRefExpr"},
372 {
"int x = 42;^",
nullptr},
375 {
"^int x; int y;^",
nullptr},
378 {
"template <typename T> void foo() { [[^T]] t; }",
379 "TemplateTypeParmTypeLoc"},
384 template <class T> struct Foo {};
385 template <[[template<class> class /*cursor here*/^U]]>
386 struct Foo<U<int>*> {};
388 "TemplateTemplateParmDecl"},
398 Str makeStr(const char*);
400 for (const char C : [[mak^eStr("foo"^)]])
411 Foo operator""_ud(unsigned long long);
414 "UserDefinedLiteral"},
419 decltype([[^a]] + a) b;
422 {
"[[decltype^(1)]] b;",
"DecltypeTypeLoc"},
424 {
"[[de^cltype(a^uto)]] a = 1;",
"AutoTypeLoc"},
430 @property(nullable) [[^I]] *x;
433 "ObjCInterfaceTypeLoc"},
437 - (void)doSomething:(nonnull [[i^d]])argument;
448 @property(retain) I*x;
449 @property(retain) I*y;
451 void test(I *f) { [[^f]].x.y = 0; }
457 @property(retain) I*x;
458 @property(retain) I*y;
460 void test(I *f) { [[f.^x]].y = 0; }
462 "ObjCPropertyRefExpr"},
469 int test(I *f) { return 42 + [[^f]].foo; }
477 int test(I *f) { return 42 + [[f.^foo]]; }
479 "ObjCPropertyRefExpr"},
480 {
"struct foo { [[int has^h<:32:>]]; };",
"FieldDecl"},
481 {
"struct foo { [[op^erator int()]]; };",
"CXXConversionDecl"},
482 {
"struct foo { [[^~foo()]]; };",
"CXXDestructorDecl"},
483 {
"struct foo { [[~^foo()]]; };",
"CXXDestructorDecl"},
484 {
"template <class T> struct foo { ~foo<[[^T]]>(){} };",
485 "TemplateTypeParmTypeLoc"},
486 {
"struct foo {}; void bar(foo *f) { [[f->~^foo]](); }",
"MemberExpr"},
487 {
"struct foo { [[fo^o(){}]] };",
"CXXConstructorDecl"},
490 struct S1 { void f(); };
491 struct S2 { S1 * operator->(); };
500 template <typename> class Vector {};
501 template <template <typename> class Container> class A {};
504 "TemplateArgumentLoc"},
508 void f(int * __attribute__(([[no^nnull]])) );
513 // Digraph syntax for attributes to avoid accidental annotations.
514 class <:[gsl::Owner([[in^t]])]:> X{};
521 [[@property(retain, nonnull) <:[My^Object2]:> *x]]; // error-ok
528 enum Bar : [[Fo^o]] {};
540 auto l = [^[[foo = bar]]] { };
545 void func() [[{^]])cpp",
548 void func() { [[__^func__]]; }
554 namespace ns { enum class A {}; };
555 using enum ns::[[^A]];
559 namespace ns { enum class A {}; using B = A; };
560 using enum ns::[[^B]];
564 namespace ns { enum class A {}; };
565 using enum [[^ns::]]A;
567 "NestedNameSpecifierLoc"},
569 namespace ns { enum class A {}; };
570 [[using ^enum ns::A]];
574 namespace ns { enum class A {}; };
575 [[^using enum ns::A]];
581 template <class> concept C = true;
582 auto x = [[^C<int>]];
586 template <class> concept C = true;
591 template <class> concept C = true;
592 void foo([[^C]] auto x) {}
596 template <class> concept C = true;
597 template <[[^C]] x> int i = 0;
601 namespace ns { template <class> concept C = true; }
602 auto x = [[ns::^C<int>]];
606 template <typename T, typename K>
608 template <typename T> void g(D<[[^T]]> auto abc) {}
610 "TemplateTypeParmTypeLoc"},
612 const unsigned WALDO = 64;
613 struct alignas([[WA^LDO]]) foo {};
618 for (
const Case &C : Cases) {
623 TU.
Code = std::string(Test.code());
625 TU.ExtraArgs.push_back(
"-xobjective-c++");
626 TU.ExtraArgs.push_back(
"-std=c++20");
628 auto AST = TU.build();
629 auto T = makeSelectionTree(
C.Code,
AST);
630 EXPECT_EQ(
"TranslationUnitDecl", nodeKind(&
T.root())) <<
C.Code;
632 if (Test.ranges().empty()) {
634 EXPECT_FALSE(
T.commonAncestor()) <<
C.Code <<
"\n" <<
T;
635 EXPECT_THAT(Tracer.takeMetric(
"selection_recovery",
"C++"),
640 EXPECT_EQ(
C.CommonAncestorKind, nodeKind(
T.commonAncestor()))
644 EXPECT_EQ(nodeRange(
T.commonAncestor(),
AST), Test.range())
650 EXPECT_TRUE(verifyCommonAncestor(
T.root(),
T.commonAncestor(),
C.Code))
652 EXPECT_THAT(Tracer.takeMetric(
"selection_recovery",
"C++"),
653 ElementsAreArray({0}));
659TEST(SelectionTest, InjectedClassName) {
660 const char *Code =
"struct ^X { int x; };";
662 auto T = makeSelectionTree(Code,
AST);
663 ASSERT_EQ(
"CXXRecordDecl", nodeKind(
T.commonAncestor())) <<
T;
664 auto *
D = dyn_cast<CXXRecordDecl>(
T.commonAncestor()->ASTNode.get<Decl>());
665 EXPECT_FALSE(
D->isInjectedClassName());
669 const char *Code = R
"cpp(
670 // error-ok: testing behavior on recovery expression
677 auto T = makeSelectionTree(Code,
AST);
678 EXPECT_THAT(Tracer.takeMetric(
"selection_recovery",
"C++"),
679 ElementsAreArray({1}));
680 EXPECT_THAT(Tracer.takeMetric(
"selection_recovery_type",
"C++"),
681 ElementsAreArray({1}));
687TEST(SelectionTest, Selected) {
691 const char *Cases[] = {
692 R
"cpp( int abc, xyz = [[^ab^c]]; )cpp",
693 R"cpp( int abc, xyz = [[a^bc^]]; )cpp",
694 R"cpp( int abc, xyz = $C[[^abc^]]; )cpp",
697 [[if ([[1^11]]) $C[[{
706 struct unique_ptr {};
707 void foo(^$C[[unique_ptr<$C[[unique_ptr<$C[[int]]>]]>]]^ a) {}
709 R"cpp(int a = [[5 >^> 1]];)cpp",
712 ECHO(EC^HO($C[[int]]) EC^HO(a));
714 R"cpp( $C[[^$C[[int]] a^]]; )cpp",
715 R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
717 for (
const char *C : Cases) {
720 auto T = makeSelectionTree(C,
AST);
722 std::vector<Range> Complete, Partial;
725 Complete.push_back(nodeRange(N,
AST));
727 Partial.push_back(nodeRange(N,
AST));
728 EXPECT_THAT(Complete, UnorderedElementsAreArray(Test.ranges(
"C"))) <<
C;
729 EXPECT_THAT(Partial, UnorderedElementsAreArray(Test.ranges())) <<
C;
733TEST(SelectionTest, PathologicalPreprocessor) {
734 const char *Case = R
"cpp(
735#define MACRO while(1)
743 TU.AdditionalFiles[
"Expand.inc"] =
"MACRO\n";
744 auto AST = TU.build();
745 EXPECT_THAT(
AST.getDiagnostics(), ::testing::IsEmpty());
746 auto T = makeSelectionTree(Case,
AST);
748 EXPECT_EQ(
"BreakStmt",
T.commonAncestor()->kind());
749 EXPECT_EQ(
"WhileStmt",
T.commonAncestor()->Parent->kind());
752TEST(SelectionTest, IncludedFile) {
753 const char *Case = R
"cpp(
755#include "Exp^and.inc"
761 TU.AdditionalFiles[
"Expand.inc"] =
"while(1)\n";
762 auto AST = TU.build();
763 auto T = makeSelectionTree(Case,
AST);
765 EXPECT_EQ(
nullptr,
T.commonAncestor());
768TEST(SelectionTest, MacroArgExpansion) {
771 const char *Case = R
"cpp(
773 #define SQUARE(X) mul(X, X);
774 int nine = SQUARE(^3);
778 auto T = makeSelectionTree(Case,
AST);
779 EXPECT_EQ(
"IntegerLiteral",
T.commonAncestor()->kind());
780 EXPECT_TRUE(
T.commonAncestor()->Selected);
785 void die(const char*);
786 #define assert(x) (x ? (void)0 : die(#x))
787 void foo() { assert(^42); }
791 T = makeSelectionTree(Case, AST);
792 EXPECT_EQ("IntegerLiteral",
T.commonAncestor()->kind());
799 template <typename T> class S {};
807 T = makeSelectionTree(Case, AST);
809 EXPECT_EQ(
"VarDecl",
T.commonAncestor()->kind());
812TEST(SelectionTest, Implicit) {
813 const char *Test = R
"cpp(
814 struct S { S(const char*); };
820 TU.ExtraArgs.push_back(
"-std=c++17");
821 auto AST = TU.build();
822 auto T = makeSelectionTree(Test,
AST);
825 EXPECT_EQ(
"StringLiteral", nodeKind(Str)) <<
"Implicit selected?";
826 EXPECT_EQ(
"ImplicitCastExpr", nodeKind(Str->Parent));
827 EXPECT_EQ(
"CXXConstructExpr", nodeKind(Str->Parent->Parent));
829 EXPECT_EQ(
"ImplicitCastExpr", nodeKind(ICE));
830 EXPECT_EQ(
"CallExpr", nodeKind(ICE->Parent));
831 EXPECT_EQ(Str, &ICE->ignoreImplicit())
832 <<
"Didn't unwrap " << nodeKind(&ICE->ignoreImplicit());
834 EXPECT_EQ(ICE, &Str->outerImplicit());
837TEST(SelectionTest, CreateAll) {
838 llvm::Annotations Test(
"int$unique^ a=1$ambiguous^+1; $empty^");
842 AST.getASTContext(),
AST.getTokens(), Test.point(
"ambiguous"),
846 EXPECT_EQ(
"BinaryOperator", nodeKind(T.commonAncestor()));
847 }
else if (Seen == 1) {
848 EXPECT_EQ(
"IntegerLiteral", nodeKind(
T.commonAncestor()));
857 Test.point(
"ambiguous"), Test.point(
"ambiguous"),
862 EXPECT_EQ(1u, Seen) <<
"Return true --> stop iterating";
866 Test.point(
"unique"), Test.point(
"unique"),
871 EXPECT_EQ(1u, Seen) <<
"no ambiguity --> only one tree";
875 Test.point(
"empty"), Test.point(
"empty"),
877 EXPECT_FALSE(T.commonAncestor());
881 EXPECT_EQ(1u, Seen) <<
"empty tree still created";
885 Test.point(
"unique"), Test.point(
"ambiguous"),
890 EXPECT_EQ(1u, Seen) <<
"one tree for nontrivial selection";
893TEST(SelectionTest, DeclContextIsLexical) {
894 llvm::Annotations Test(
"namespace a { void $1^foo(); } void a::$2^foo();");
898 Test.point(
"1"), Test.point(
"1"));
899 EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
903 Test.point(
"2"), Test.point(
"2"));
904 EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
908TEST(SelectionTest, DeclContextLambda) {
909 llvm::Annotations Test(R
"cpp(
917 Test.point(
"1"), Test.point(
"1"));
918 EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isFunctionOrMethod());
921TEST(SelectionTest, UsingConcepts) {
922 llvm::Annotations Test(R
"cpp(
930template <Fo^o... T, Fo^o auto U>
931auto Func(Fo^o auto V) -> Fo^o decltype(auto) {
937 TU.ExtraArgs.emplace_back(
"-std=c++2c");
938 auto AST = TU.build();
939 for (
auto Point : Test.points()) {
942 auto *
C = ST.commonAncestor()->ASTNode.get<ConceptReference>();
943 EXPECT_TRUE(C &&
C->getFoundDecl() &&
944 C->getFoundDecl()->getKind() == Decl::UsingShadow);
Same as llvm::Annotations, but adjusts functions to LSP-specific types for positions and ranges.
Stores and provides access to parsed AST.
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End, llvm::function_ref< bool(SelectionTree)> Func)
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
A RAII Tracer that can be used by tests.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
TEST(BackgroundQueueTest, Priority)
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::SmallVector< const Node * > Children
static TestTU withCode(llvm::StringRef Code)