1 //== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ASTMatchersTest.h"
11 #include "clang/AST/PrettyPrinter.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Tooling/Tooling.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/Support/Host.h"
17 #include "gtest/gtest.h"
20 namespace ast_matchers {
22 TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
24 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
25 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
26 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
29 // Do not accept non-toplevel matchers.
30 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
31 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
34 TEST(Decl, MatchesDeclarations) {
35 EXPECT_TRUE(notMatches("", decl(usingDecl())));
36 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
40 TEST(NameableDeclaration, MatchesVariousDecls) {
41 DeclarationMatcher NamedX = namedDecl(hasName("X"));
42 EXPECT_TRUE(matches("typedef int X;", NamedX));
43 EXPECT_TRUE(matches("int X;", NamedX));
44 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
45 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
46 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
47 EXPECT_TRUE(matches("namespace X { }", NamedX));
48 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
50 EXPECT_TRUE(notMatches("#define X 1", NamedX));
53 TEST(NameableDeclaration, REMatchesVariousDecls) {
54 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
55 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
56 EXPECT_TRUE(matches("int Xb;", NamedX));
57 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
58 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
59 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
60 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
61 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
63 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
65 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
66 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
67 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
69 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
70 EXPECT_TRUE(matches("int abc;", Abc));
71 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
72 EXPECT_TRUE(notMatches("int cab;", Abc));
73 EXPECT_TRUE(matches("int cabc;", Abc));
75 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
76 EXPECT_TRUE(matches("int k;", StartsWithK));
77 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
78 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
79 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
80 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
83 TEST(DeclarationMatcher, MatchClass) {
84 DeclarationMatcher ClassMatcher(recordDecl());
86 // This passes on Windows only because we explicitly pass -target
87 // i386-unknown-unknown. If we were to compile with the default target
88 // triple, we'd want to EXPECT_TRUE if it's Win32 or MSVC.
89 EXPECT_FALSE(matches("", ClassMatcher));
91 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
92 EXPECT_TRUE(matches("class X;", ClassX));
93 EXPECT_TRUE(matches("class X {};", ClassX));
94 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
95 EXPECT_TRUE(notMatches("", ClassX));
98 TEST(DeclarationMatcher, translationUnitDecl) {
99 const std::string Code = "int MyVar1;\n"
100 "namespace NameSpace {\n"
102 "} // namespace NameSpace\n";
104 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
105 EXPECT_FALSE(matches(
106 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
109 varDecl(hasName("MyVar2"),
110 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
113 TEST(DeclarationMatcher, LinkageSpecification) {
114 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
115 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
118 TEST(ClassTemplate, DoesNotMatchClass) {
119 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
120 EXPECT_TRUE(notMatches("class X;", ClassX));
121 EXPECT_TRUE(notMatches("class X {};", ClassX));
124 TEST(ClassTemplate, MatchesClassTemplate) {
125 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
126 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
127 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
130 TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
131 EXPECT_TRUE(notMatches("template<typename T> class X { };"
132 "template<> class X<int> { int a; };",
133 classTemplateDecl(hasName("X"),
134 hasDescendant(fieldDecl(hasName("a"))))));
137 TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
138 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
139 "template<typename T> class X<T, int> { int a; };",
140 classTemplateDecl(hasName("X"),
141 hasDescendant(fieldDecl(hasName("a"))))));
144 TEST(DeclarationMatcher, MatchCudaDecl) {
145 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
146 "void g() { f<<<1, 2>>>(); }",
147 cudaKernelCallExpr()));
148 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
149 hasAttr(clang::attr::CUDADevice)));
150 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
151 cudaKernelCallExpr()));
152 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
153 hasAttr(clang::attr::CUDAGlobal)));
156 TEST(ValueDecl, Matches) {
157 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
158 valueDecl(hasType(asString("enum EnumType")))));
159 EXPECT_TRUE(matches("void FunctionDecl();",
160 valueDecl(hasType(asString("void (void)")))));
163 TEST(FriendDecl, Matches) {
164 EXPECT_TRUE(matches("class Y { friend class X; };",
165 friendDecl(hasType(asString("class X")))));
166 EXPECT_TRUE(matches("class Y { friend class X; };",
167 friendDecl(hasType(recordDecl(hasName("X"))))));
169 EXPECT_TRUE(matches("class Y { friend void f(); };",
170 functionDecl(hasName("f"), hasParent(friendDecl()))));
173 TEST(Enum, DoesNotMatchClasses) {
174 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
177 TEST(Enum, MatchesEnums) {
178 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
181 TEST(EnumConstant, Matches) {
182 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
183 EXPECT_TRUE(matches("enum X{ A };", Matcher));
184 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
185 EXPECT_TRUE(notMatches("enum X {};", Matcher));
188 TEST(Matcher, UnresolvedLookupExpr) {
189 // FIXME: The test is known to be broken on Windows with delayed template
191 EXPECT_TRUE(matchesConditionally("template<typename T>"
192 "T foo() { T a; return a; }"
193 "template<typename T>"
197 unresolvedLookupExpr(),
198 /*ExpectMatch=*/true,
199 "-fno-delayed-template-parsing"));
202 TEST(Matcher, Call) {
203 // FIXME: Do we want to overload Call() to directly take
204 // Matcher<Decl>, too?
205 StatementMatcher MethodX =
206 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
208 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
209 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
211 StatementMatcher MethodOnY =
212 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
215 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
218 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
221 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
224 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
227 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
230 StatementMatcher MethodOnYPointer =
231 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
234 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
237 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
240 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
243 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
246 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
249 TEST(Matcher, Lambda) {
250 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
254 TEST(Matcher, ForRange) {
255 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
256 "void f() { for (auto &a : as); }",
258 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
262 TEST(Matcher, SubstNonTypeTemplateParm) {
263 EXPECT_FALSE(matches("template<int N>\n"
264 "struct A { static const int n = 0; };\n"
265 "struct B : public A<42> {};",
266 substNonTypeTemplateParmExpr()));
267 EXPECT_TRUE(matches("template<int N>\n"
268 "struct A { static const int n = N; };\n"
269 "struct B : public A<42> {};",
270 substNonTypeTemplateParmExpr()));
273 TEST(Matcher, NonTypeTemplateParmDecl) {
274 EXPECT_TRUE(matches("template <int N> void f();",
275 nonTypeTemplateParmDecl(hasName("N"))));
277 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
280 TEST(Matcher, templateTypeParmDecl) {
281 EXPECT_TRUE(matches("template <typename T> void f();",
282 templateTypeParmDecl(hasName("T"))));
284 notMatches("template <int N> void f();", templateTypeParmDecl()));
287 TEST(Matcher, UserDefinedLiteral) {
288 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
292 userDefinedLiteral()));
295 TEST(Matcher, FlowControl) {
296 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
297 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
299 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
300 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
303 labelDecl(hasName("FOO"))))));
304 EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
306 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
309 TEST(Matcher, OverloadedOperatorCall) {
310 StatementMatcher OpCall = cxxOperatorCallExpr();
312 EXPECT_TRUE(matches("class Y { }; "
313 "bool operator!(Y x) { return false; }; "
314 "Y y; bool c = !y;", OpCall));
315 // No match -- special operators like "new", "delete"
316 // FIXME: operator new takes size_t, for which we need stddef.h, for which
317 // we need to figure out include paths in the test.
318 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
320 // "void *operator new(size_t size) { return 0; } "
321 // "Y *y = new Y;", OpCall));
322 EXPECT_TRUE(notMatches("class Y { }; "
323 "void operator delete(void *p) { } "
324 "void a() {Y *y = new Y; delete y;}", OpCall));
326 EXPECT_TRUE(matches("class Y { }; "
327 "bool operator&&(Y x, Y y) { return true; }; "
328 "Y a; Y b; bool c = a && b;",
330 // No match -- normal operator, not an overloaded one.
331 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
332 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
335 TEST(Matcher, ThisPointerType) {
336 StatementMatcher MethodOnY =
337 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
340 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
343 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
346 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
349 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
352 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
357 " public: virtual void x();"
359 "class X : public Y {"
360 " public: virtual void x();"
362 "void z() { X *x; x->Y::x(); }", MethodOnY));
365 TEST(Matcher, VariableUsage) {
366 StatementMatcher Reference =
368 varDecl(hasInitializer(
369 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
376 "void z(const Y &y) {"
381 EXPECT_TRUE(notMatches(
386 "void z(const Y &y) {"
391 TEST(Matcher, CalledVariable) {
392 StatementMatcher CallOnVariableY =
393 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
396 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
398 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
400 "class Y { public: void x(); };"
401 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
403 "class Y { public: void x(); };"
404 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
405 EXPECT_TRUE(notMatches(
406 "class Y { public: void x(); };"
407 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
411 TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
412 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
413 unaryExprOrTypeTraitExpr()));
414 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
415 alignOfExpr(anything())));
416 // FIXME: Uncomment once alignof is enabled.
417 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
418 // unaryExprOrTypeTraitExpr()));
419 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
423 TEST(MemberExpression, DoesNotMatchClasses) {
424 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
427 TEST(MemberExpression, MatchesMemberFunctionCall) {
428 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
431 TEST(MemberExpression, MatchesVariable) {
433 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
435 matches("class Y { void x() { y; } int y; };", memberExpr()));
437 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
440 TEST(MemberExpression, MatchesStaticVariable) {
441 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
443 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
445 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
449 TEST(Function, MatchesFunctionDeclarations) {
450 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
452 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
453 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
455 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
456 llvm::Triple::Win32) {
457 // FIXME: Make this work for MSVC.
458 // Dependent contexts, but a non-dependent call.
459 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
462 matches("void f(); template <int N> struct S { void g() { f(); } };",
466 // Depedent calls don't match.
468 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
471 notMatches("void f(int);"
472 "template <typename T> struct S { void g(T t) { f(t); } };",
475 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
476 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
477 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
478 functionDecl(isVariadic())));
479 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
480 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
481 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
482 EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0))));
483 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
486 TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
488 matches("template <typename T> void f(T t) {}",
489 functionTemplateDecl(hasName("f"))));
492 TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
494 notMatches("void f(double d); void f(int t) {}",
495 functionTemplateDecl(hasName("f"))));
498 TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
500 notMatches("void g(); template <typename T> void f(T t) {}"
501 "template <> void f(int t) { g(); }",
502 functionTemplateDecl(hasName("f"),
503 hasDescendant(declRefExpr(to(
504 functionDecl(hasName("g"))))))));
507 TEST(Matcher, MatchesClassTemplateSpecialization) {
508 EXPECT_TRUE(matches("template<typename T> struct A {};"
509 "template<> struct A<int> {};",
510 classTemplateSpecializationDecl()));
511 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
512 classTemplateSpecializationDecl()));
513 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
514 classTemplateSpecializationDecl()));
517 TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
518 EXPECT_TRUE(matches("int x;", declaratorDecl()));
519 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
522 TEST(ParmVarDecl, MatchesParmVars) {
523 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
524 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
527 TEST(Matcher, ConstructorCall) {
528 StatementMatcher Constructor = cxxConstructExpr();
531 matches("class X { public: X(); }; void x() { X x; }", Constructor));
533 matches("class X { public: X(); }; void x() { X x = X(); }",
536 matches("class X { public: X(int); }; void x() { X x = 0; }",
538 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
541 TEST(Match, ConstructorInitializers) {
542 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
543 cxxCtorInitializer(forField(hasName("i")))));
546 TEST(Matcher, ThisExpr) {
548 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
550 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
553 TEST(Matcher, BindTemporaryExpression) {
554 StatementMatcher TempExpression = cxxBindTemporaryExpr();
556 std::string ClassString = "class string { public: string(); ~string(); }; ";
559 matches(ClassString +
560 "string GetStringByValue();"
561 "void FunctionTakesString(string s);"
562 "void run() { FunctionTakesString(GetStringByValue()); }",
566 notMatches(ClassString +
567 "string* GetStringPointer(); "
568 "void FunctionTakesStringPtr(string* s);"
570 " string* s = GetStringPointer();"
571 " FunctionTakesStringPtr(GetStringPointer());"
572 " FunctionTakesStringPtr(s);"
577 notMatches("class no_dtor {};"
578 "no_dtor GetObjByValue();"
579 "void ConsumeObj(no_dtor param);"
580 "void run() { ConsumeObj(GetObjByValue()); }",
584 TEST(MaterializeTemporaryExpr, MatchesTemporary) {
585 std::string ClassString =
586 "class string { public: string(); int length(); }; ";
589 matches(ClassString +
590 "string GetStringByValue();"
591 "void FunctionTakesString(string s);"
592 "void run() { FunctionTakesString(GetStringByValue()); }",
593 materializeTemporaryExpr()));
596 notMatches(ClassString +
597 "string* GetStringPointer(); "
598 "void FunctionTakesStringPtr(string* s);"
600 " string* s = GetStringPointer();"
601 " FunctionTakesStringPtr(GetStringPointer());"
602 " FunctionTakesStringPtr(s);"
604 materializeTemporaryExpr()));
607 matches(ClassString +
608 "string GetStringByValue();"
609 "void run() { int k = GetStringByValue().length(); }",
610 materializeTemporaryExpr()));
613 notMatches(ClassString +
614 "string GetStringByValue();"
615 "void run() { GetStringByValue(); }",
616 materializeTemporaryExpr()));
619 TEST(Matcher, NewExpression) {
620 StatementMatcher New = cxxNewExpr();
622 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
624 matches("class X { public: X(); }; void x() { new X(); }", New));
626 matches("class X { public: X(int); }; void x() { new X(0); }", New));
627 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
630 TEST(Matcher, DeleteExpression) {
631 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
635 TEST(Matcher, DefaultArgument) {
636 StatementMatcher Arg = cxxDefaultArgExpr();
638 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
640 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
641 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
644 TEST(Matcher, StringLiterals) {
645 StatementMatcher Literal = stringLiteral();
646 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
648 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
649 // with escaped characters
650 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
651 // no matching -- though the data type is the same, there is no string literal
652 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
655 TEST(Matcher, CharacterLiterals) {
656 StatementMatcher CharLiteral = characterLiteral();
657 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
659 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
660 // wide character, Hex encoded, NOT MATCHED!
661 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
662 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
665 TEST(Matcher, IntegerLiterals) {
666 StatementMatcher HasIntLiteral = integerLiteral();
667 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
668 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
669 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
670 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
672 // Non-matching cases (character literals, float and double)
673 EXPECT_TRUE(notMatches("int i = L'a';",
674 HasIntLiteral)); // this is actually a character
675 // literal cast to int
676 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
677 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
678 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
680 // Negative integers.
682 matches("int i = -10;",
683 unaryOperator(hasOperatorName("-"),
684 hasUnaryOperand(integerLiteral(equals(10))))));
687 TEST(Matcher, FloatLiterals) {
688 StatementMatcher HasFloatLiteral = floatLiteral();
689 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
690 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
691 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
692 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
693 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
694 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
695 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
697 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
699 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
700 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
701 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
703 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
706 TEST(Matcher, NullPtrLiteral) {
707 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
710 TEST(Matcher, GNUNullExpr) {
711 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
714 TEST(Matcher, AtomicExpr) {
715 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
719 TEST(Matcher, Initializers) {
720 const char *ToMatch = "void foo() { struct point { double x; double y; };"
721 " struct point ptarray[10] = "
722 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }";
723 EXPECT_TRUE(matchesConditionally(
728 requiresZeroInitialization())),
731 hasType(asString("struct point")),
732 has(floatLiteral(equals(1.0))),
733 has(implicitValueInitExpr(
734 hasType(asString("double")))))),
737 hasType(asString("struct point")),
738 has(floatLiteral(equals(2.0))),
739 has(floatLiteral(equals(1.0)))))
740 ), true, "-std=gnu++98"));
742 EXPECT_TRUE(matchesC99(ToMatch,
748 designatorCountIs(2),
755 designatorCountIs(2),
762 designatorCountIs(2),
770 TEST(Matcher, ParenListExpr) {
772 matches("template<typename T> class foo { void bar() { foo X(*this); } };"
773 "template class foo<int>;",
774 varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
777 TEST(Matcher, StmtExpr) {
778 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
779 varDecl(hasInitializer(stmtExpr()))));
782 TEST(Matcher, ImportPredefinedExpr) {
783 // __func__ expands as StringLiteral("foo")
784 EXPECT_TRUE(matches("void foo() { __func__; }",
786 hasType(asString("const char [4]")),
787 has(stringLiteral()))));
790 TEST(Matcher, AsmStatement) {
791 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
794 TEST(Matcher, Conditions) {
795 StatementMatcher Condition =
796 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
798 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
799 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
800 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
801 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
802 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
805 TEST(Matcher, ConditionalOperator) {
806 StatementMatcher Conditional = conditionalOperator(
807 hasCondition(cxxBoolLiteral(equals(true))),
808 hasTrueExpression(cxxBoolLiteral(equals(false))));
810 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
811 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
812 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
814 StatementMatcher ConditionalFalse = conditionalOperator(
815 hasFalseExpression(cxxBoolLiteral(equals(false))));
817 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
819 notMatches("void x() { true ? false : true; }", ConditionalFalse));
821 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
823 notMatches("void x() { true ? false : true; }", ConditionalFalse));
826 TEST(Matcher, BinaryConditionalOperator) {
827 StatementMatcher AlwaysOne = binaryConditionalOperator(
828 hasCondition(implicitCastExpr(
831 hasSourceExpression((integerLiteral(equals(1)))))))),
832 hasFalseExpression(integerLiteral(equals(0))));
834 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
836 StatementMatcher FourNotFive = binaryConditionalOperator(
837 hasTrueExpression(opaqueValueExpr(
838 hasSourceExpression((integerLiteral(equals(4)))))),
839 hasFalseExpression(integerLiteral(equals(5))));
841 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
844 TEST(ArraySubscriptMatchers, ArraySubscripts) {
845 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
846 arraySubscriptExpr()));
847 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
848 arraySubscriptExpr()));
851 TEST(For, FindsForLoops) {
852 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
853 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
854 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
855 "void f() { for (auto &a : as); }",
859 TEST(For, ReportsNoFalsePositives) {
860 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
861 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
864 TEST(CompoundStatement, HandlesSimpleCases) {
865 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
866 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
867 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
870 TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
871 // It's not a compound statement just because there's "{}" in the source
872 // text. This is an AST search, not grep.
873 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
875 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
879 TEST(CastExpression, MatchesExplicitCasts) {
880 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
881 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
882 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
883 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
885 TEST(CastExpression, MatchesImplicitCasts) {
886 // This test creates an implicit cast from int to char.
887 EXPECT_TRUE(matches("char c = 0;", castExpr()));
888 // This test creates an implicit cast from lvalue to rvalue.
889 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
892 TEST(CastExpression, DoesNotMatchNonCasts) {
893 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
894 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
895 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
896 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
899 TEST(ReinterpretCast, MatchesSimpleCase) {
900 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
901 cxxReinterpretCastExpr()));
904 TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
905 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
906 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
907 cxxReinterpretCastExpr()));
908 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
909 cxxReinterpretCastExpr()));
910 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
912 "D* p = dynamic_cast<D*>(&b);",
913 cxxReinterpretCastExpr()));
916 TEST(FunctionalCast, MatchesSimpleCase) {
917 std::string foo_class = "class Foo { public: Foo(const char*); };";
918 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
919 cxxFunctionalCastExpr()));
922 TEST(FunctionalCast, DoesNotMatchOtherCasts) {
923 std::string FooClass = "class Foo { public: Foo(const char*); };";
925 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
926 cxxFunctionalCastExpr()));
928 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
929 cxxFunctionalCastExpr()));
932 TEST(DynamicCast, MatchesSimpleCase) {
933 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
935 "D* p = dynamic_cast<D*>(&b);",
936 cxxDynamicCastExpr()));
939 TEST(StaticCast, MatchesSimpleCase) {
940 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
941 cxxStaticCastExpr()));
944 TEST(StaticCast, DoesNotMatchOtherCasts) {
945 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
946 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
947 cxxStaticCastExpr()));
948 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
949 cxxStaticCastExpr()));
950 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
952 "D* p = dynamic_cast<D*>(&b);",
953 cxxStaticCastExpr()));
956 TEST(CStyleCast, MatchesSimpleCase) {
957 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
960 TEST(CStyleCast, DoesNotMatchOtherCasts) {
961 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
962 "char q, *r = const_cast<char*>(&q);"
963 "void* s = reinterpret_cast<char*>(&s);"
964 "struct B { virtual ~B() {} }; struct D : B {};"
966 "D* t = dynamic_cast<D*>(&b);",
970 TEST(ImplicitCast, MatchesSimpleCase) {
971 // This test creates an implicit const cast.
972 EXPECT_TRUE(matches("int x = 0; const int y = x;",
973 varDecl(hasInitializer(implicitCastExpr()))));
974 // This test creates an implicit cast from int to char.
975 EXPECT_TRUE(matches("char c = 0;",
976 varDecl(hasInitializer(implicitCastExpr()))));
977 // This test creates an implicit array-to-pointer cast.
978 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
979 varDecl(hasInitializer(implicitCastExpr()))));
982 TEST(ImplicitCast, DoesNotMatchIncorrectly) {
983 // This test verifies that implicitCastExpr() matches exactly when implicit casts
984 // are present, and that it ignores explicit and paren casts.
986 // These two test cases have no casts.
987 EXPECT_TRUE(notMatches("int x = 0;",
988 varDecl(hasInitializer(implicitCastExpr()))));
989 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
990 varDecl(hasInitializer(implicitCastExpr()))));
992 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
993 varDecl(hasInitializer(implicitCastExpr()))));
994 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
995 varDecl(hasInitializer(implicitCastExpr()))));
997 EXPECT_TRUE(notMatches("int x = (0);",
998 varDecl(hasInitializer(implicitCastExpr()))));
1001 TEST(Statement, DoesNotMatchDeclarations) {
1002 EXPECT_TRUE(notMatches("class X {};", stmt()));
1005 TEST(Statement, MatchesCompoundStatments) {
1006 EXPECT_TRUE(matches("void x() {}", stmt()));
1009 TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
1010 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1013 TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
1014 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1017 TEST(ExprWithCleanups, MatchesExprWithCleanups) {
1018 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
1019 "const Foo f = Foo();",
1020 varDecl(hasInitializer(exprWithCleanups()))));
1021 EXPECT_FALSE(matches("struct Foo { }; Foo a;"
1023 varDecl(hasInitializer(exprWithCleanups()))));
1026 TEST(InitListExpression, MatchesInitListExpression) {
1027 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1028 initListExpr(hasType(asString("int [2]")))));
1029 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
1030 initListExpr(hasType(recordDecl(hasName("B"))))));
1031 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1034 declRefExpr(to(functionDecl(hasName("f"))))));
1036 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1039 TEST(CXXStdInitializerListExpression, MatchesCXXStdInitializerListExpression) {
1040 const std::string code = "namespace std {"
1041 "template <typename> class initializer_list {"
1042 " public: initializer_list() noexcept {}"
1046 " A(std::initializer_list<int>) {}"
1048 EXPECT_TRUE(matches(code + "A a{0};",
1049 cxxConstructExpr(has(cxxStdInitializerListExpr()),
1050 hasDeclaration(cxxConstructorDecl(
1051 ofClass(hasName("A")))))));
1052 EXPECT_TRUE(matches(code + "A a = {0};",
1053 cxxConstructExpr(has(cxxStdInitializerListExpr()),
1054 hasDeclaration(cxxConstructorDecl(
1055 ofClass(hasName("A")))))));
1057 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1058 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1059 cxxStdInitializerListExpr()));
1062 TEST(UsingDeclaration, MatchesUsingDeclarations) {
1063 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
1067 TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
1068 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1069 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1072 TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
1073 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1074 usingDirectiveDecl()));
1076 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1080 TEST(While, MatchesWhileLoops) {
1081 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1082 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
1083 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
1086 TEST(Do, MatchesDoLoops) {
1087 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
1088 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
1091 TEST(Do, DoesNotMatchWhileLoops) {
1092 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
1095 TEST(SwitchCase, MatchesCase) {
1096 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1097 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1098 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1099 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1102 TEST(SwitchCase, MatchesSwitch) {
1103 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1104 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1105 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1106 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1109 TEST(ExceptionHandling, SimpleCases) {
1110 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1111 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1113 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1114 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
1116 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
1118 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1119 cxxCatchStmt(isCatchAll())));
1120 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1121 cxxCatchStmt(isCatchAll())));
1122 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1123 varDecl(isExceptionVariable())));
1124 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1125 varDecl(isExceptionVariable())));
1128 TEST(ParenExpression, SimpleCases) {
1129 EXPECT_TRUE(matches("int i = (3);", parenExpr()));
1130 EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr()));
1131 EXPECT_TRUE(notMatches("int i = 3;", parenExpr()));
1132 EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();",
1136 TEST(TypeMatching, MatchesTypes) {
1137 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1140 TEST(TypeMatching, MatchesConstantArrayTypes) {
1141 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1142 EXPECT_TRUE(notMatches(
1143 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1144 constantArrayType(hasElementType(builtinType()))));
1146 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1147 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1148 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1151 TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
1152 EXPECT_TRUE(matches(
1153 "template <typename T, int Size> class array { T data[Size]; };",
1154 dependentSizedArrayType()));
1155 EXPECT_TRUE(notMatches(
1156 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1157 dependentSizedArrayType()));
1160 TEST(TypeMatching, MatchesIncompleteArrayType) {
1161 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1162 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1164 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1165 incompleteArrayType()));
1168 TEST(TypeMatching, MatchesVariableArrayType) {
1169 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1170 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1172 EXPECT_TRUE(matches(
1173 "void f(int b) { int a[b]; }",
1174 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
1175 varDecl(hasName("b")))))))));
1179 TEST(TypeMatching, MatchesAtomicTypes) {
1180 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1181 llvm::Triple::Win32) {
1182 // FIXME: Make this work for MSVC.
1183 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1185 EXPECT_TRUE(matches("_Atomic(int) i;",
1186 atomicType(hasValueType(isInteger()))));
1187 EXPECT_TRUE(notMatches("_Atomic(float) f;",
1188 atomicType(hasValueType(isInteger()))));
1192 TEST(TypeMatching, MatchesAutoTypes) {
1193 EXPECT_TRUE(matches("auto i = 2;", autoType()));
1194 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1197 EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1198 EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1199 varDecl(hasType(recordDecl(hasName("X"))))));
1201 // FIXME: Matching against the type-as-written can't work here, because the
1202 // type as written was not deduced.
1203 //EXPECT_TRUE(matches("auto a = 1;",
1204 // autoType(hasDeducedType(isInteger()))));
1205 //EXPECT_TRUE(notMatches("auto b = 2.0;",
1206 // autoType(hasDeducedType(isInteger()))));
1209 TEST(TypeMatching, MatchesDeclTypes) {
1210 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1211 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1212 decltypeType(hasUnderlyingType(isInteger()))));
1215 TEST(TypeMatching, MatchesFunctionTypes) {
1216 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1217 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1220 TEST(TypeMatching, IgnoringParens) {
1222 notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1223 EXPECT_TRUE(matches("void (*fp)(void);",
1224 pointerType(pointee(ignoringParens(functionType())))));
1227 TEST(TypeMatching, MatchesFunctionProtoTypes) {
1228 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1229 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1230 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1231 EXPECT_TRUE(notMatchesC("void f();", functionProtoType()));
1233 matchesC("void f(void);", functionProtoType(parameterCountIs(0))));
1236 TEST(TypeMatching, MatchesParenType) {
1238 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1239 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1241 EXPECT_TRUE(matches(
1242 "int (*ptr_to_func)(int);",
1243 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1244 EXPECT_TRUE(notMatches(
1245 "int (*ptr_to_array)[4];",
1246 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1249 TEST(TypeMatching, PointerTypes) {
1250 // FIXME: Reactive when these tests can be more specific (not matching
1251 // implicit code on certain platforms), likely when we have hasDescendant for
1253 //EXPECT_TRUE(matchAndVerifyResultTrue(
1255 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1256 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1257 //EXPECT_TRUE(matchAndVerifyResultTrue(
1259 // pointerTypeLoc().bind("loc"),
1260 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1261 EXPECT_TRUE(matches(
1263 loc(pointerType(pointee(qualType())))));
1264 EXPECT_TRUE(matches(
1266 loc(pointerType(pointee(pointerType())))));
1267 EXPECT_TRUE(matches(
1268 "int* b; int* * const a = &b;",
1269 loc(qualType(isConstQualified(), pointerType()))));
1271 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1272 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1273 hasType(blockPointerType()))));
1274 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1275 hasType(memberPointerType()))));
1276 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1277 hasType(pointerType()))));
1278 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1279 hasType(referenceType()))));
1280 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1281 hasType(lValueReferenceType()))));
1282 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1283 hasType(rValueReferenceType()))));
1285 Fragment = "int *ptr;";
1286 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1287 hasType(blockPointerType()))));
1288 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1289 hasType(memberPointerType()))));
1290 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1291 hasType(pointerType()))));
1292 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1293 hasType(referenceType()))));
1295 Fragment = "int a; int &ref = a;";
1296 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1297 hasType(blockPointerType()))));
1298 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1299 hasType(memberPointerType()))));
1300 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1301 hasType(pointerType()))));
1302 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1303 hasType(referenceType()))));
1304 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1305 hasType(lValueReferenceType()))));
1306 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1307 hasType(rValueReferenceType()))));
1309 Fragment = "int &&ref = 2;";
1310 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1311 hasType(blockPointerType()))));
1312 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1313 hasType(memberPointerType()))));
1314 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1315 hasType(pointerType()))));
1316 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1317 hasType(referenceType()))));
1318 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1319 hasType(lValueReferenceType()))));
1320 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1321 hasType(rValueReferenceType()))));
1324 TEST(TypeMatching, AutoRefTypes) {
1325 std::string Fragment = "auto a = 1;"
1330 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
1331 hasType(referenceType()))));
1332 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
1333 hasType(referenceType()))));
1334 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1335 hasType(referenceType()))));
1336 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1337 hasType(lValueReferenceType()))));
1338 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
1339 hasType(rValueReferenceType()))));
1340 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1341 hasType(referenceType()))));
1342 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1343 hasType(lValueReferenceType()))));
1344 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
1345 hasType(rValueReferenceType()))));
1346 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1347 hasType(referenceType()))));
1348 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
1349 hasType(lValueReferenceType()))));
1350 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1351 hasType(rValueReferenceType()))));
1354 TEST(TypeMatching, MatchesEnumTypes) {
1355 EXPECT_TRUE(matches("enum Color { Green }; Color color;",
1357 EXPECT_TRUE(matches("enum class Color { Green }; Color color;",
1361 TEST(TypeMatching, MatchesPointersToConstTypes) {
1362 EXPECT_TRUE(matches("int b; int * const a = &b;",
1363 loc(pointerType())));
1364 EXPECT_TRUE(matches("int b; int * const a = &b;",
1365 loc(pointerType())));
1366 EXPECT_TRUE(matches(
1367 "int b; const int * a = &b;",
1368 loc(pointerType(pointee(builtinType())))));
1369 EXPECT_TRUE(matches(
1370 "int b; const int * a = &b;",
1371 pointerType(pointee(builtinType()))));
1374 TEST(TypeMatching, MatchesTypedefTypes) {
1375 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
1376 hasType(typedefType()))));
1379 TEST(TypeMatching, MatchesTemplateSpecializationType) {
1380 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1381 templateSpecializationType()));
1384 TEST(TypeMatching, MatchesRecordType) {
1385 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
1386 EXPECT_TRUE(matches("struct S{}; S s;",
1387 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1388 EXPECT_TRUE(notMatches("int i;",
1389 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1392 TEST(TypeMatching, MatchesElaboratedType) {
1393 EXPECT_TRUE(matches(
1399 "N::M::D d;", elaboratedType()));
1400 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1401 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
1404 TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
1405 const std::string code = "template <typename T>"
1409 "int i = F<int>();";
1410 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1411 expr(hasType(substTemplateTypeParmType()))))));
1412 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1413 expr(hasType(substTemplateTypeParmType()))))));
1416 TEST(NNS, MatchesNestedNameSpecifiers) {
1417 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
1418 nestedNameSpecifier()));
1419 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1420 nestedNameSpecifier()));
1421 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
1422 nestedNameSpecifier()));
1423 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1424 nestedNameSpecifier()));
1426 EXPECT_TRUE(matches(
1427 "struct A { static void f() {} }; void g() { A::f(); }",
1428 nestedNameSpecifier()));
1429 EXPECT_TRUE(notMatches(
1430 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
1431 nestedNameSpecifier()));
1434 TEST(NullStatement, SimpleCases) {
1435 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1436 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1440 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1441 namespaceAliasDecl(hasName("alias"))));
1444 TEST(NNS, MatchesTypes) {
1445 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1446 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1447 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1448 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
1450 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
1453 TEST(NNS, MatchesNamespaceDecls) {
1454 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1455 specifiesNamespace(hasName("ns")));
1456 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
1457 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
1458 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
1461 TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
1462 EXPECT_TRUE(matches(
1463 "struct A { struct B { struct C {}; }; }; A::B::C c;",
1464 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
1465 EXPECT_TRUE(matches(
1466 "struct A { struct B { struct C {}; }; }; A::B::C c;",
1467 nestedNameSpecifierLoc(hasPrefix(
1468 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
1469 EXPECT_TRUE(matches(
1470 "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
1471 nestedNameSpecifierLoc(hasPrefix(
1472 specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
1476 template <typename T>
1477 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
1479 bool run(const BoundNodes *Nodes) override { return false; }
1481 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
1482 const T *Node = Nodes->getNodeAs<T>("");
1483 return verify(*Nodes, *Context, Node);
1486 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
1487 // Use the original typed pointer to verify we can pass pointers to subtypes
1489 const T *TypedNode = cast<T>(Node);
1490 return selectFirst<T>(
1491 "", match(stmt(hasParent(
1492 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
1493 *Node, Context)) != nullptr;
1495 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
1496 // Use the original typed pointer to verify we can pass pointers to subtypes
1498 const T *TypedNode = cast<T>(Node);
1499 return selectFirst<T>(
1500 "", match(decl(hasParent(
1501 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
1502 *Node, Context)) != nullptr;
1504 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
1505 // Use the original typed pointer to verify we can pass pointers to subtypes
1507 const T *TypedNode = cast<T>(Node);
1508 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
1509 return selectFirst<T>(
1510 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
1511 hasType(type(equalsNode(TypedNode)).bind(""))))))),
1512 *Dec, Context)) != nullptr;
1516 TEST(IsEqualTo, MatchesNodesByIdentity) {
1517 EXPECT_TRUE(matchAndVerifyResultTrue(
1518 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
1519 llvm::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
1520 EXPECT_TRUE(matchAndVerifyResultTrue(
1521 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
1522 llvm::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
1523 EXPECT_TRUE(matchAndVerifyResultTrue(
1524 "class X { class Y {} y; };",
1525 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
1526 llvm::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
1529 TEST(TypedefDeclMatcher, Match) {
1530 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
1531 typedefDecl(hasName("typedefDeclTest"))));
1532 EXPECT_TRUE(notMatches("using typedefDeclTest2 = int;",
1533 typedefDecl(hasName("typedefDeclTest2"))));
1536 TEST(TypeAliasDeclMatcher, Match) {
1537 EXPECT_TRUE(matches("using typeAliasTest2 = int;",
1538 typeAliasDecl(hasName("typeAliasTest2"))));
1539 EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
1540 typeAliasDecl(hasName("typeAliasTest"))));
1543 TEST(TypedefNameDeclMatcher, Match) {
1544 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
1545 typedefNameDecl(hasName("typedefNameDeclTest1"))));
1546 EXPECT_TRUE(matches("using typedefNameDeclTest2 = int;",
1547 typedefNameDecl(hasName("typedefNameDeclTest2"))));
1550 TEST(TypeAliasTemplateDeclMatcher, Match) {
1551 std::string Code = R"(
1552 template <typename T>
1555 template <typename T>
1556 using typeAliasTemplateDecl = X<T>;
1558 using typeAliasDecl = X<int>;
1561 matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
1563 notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
1566 TEST(ObjCMessageExprMatcher, SimpleExprs) {
1567 // don't find ObjCMessageExpr where none are present
1568 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
1570 std::string Objc1String =
1572 " - (Str *)uppercaseString;"
1576 "- (void)meth:(Str *)text;"
1579 "@implementation foo "
1580 "- (void) meth:(Str *)text { "
1582 " Str *up = [text uppercaseString];"
1585 EXPECT_TRUE(matchesObjC(
1587 objcMessageExpr(anything())));
1588 EXPECT_TRUE(matchesObjC(Objc1String,
1589 objcMessageExpr(hasAnySelector({
1590 "contents", "meth:"}))
1593 EXPECT_TRUE(matchesObjC(
1595 objcMessageExpr(hasSelector("contents"))));
1596 EXPECT_TRUE(matchesObjC(
1598 objcMessageExpr(hasAnySelector("contents", "contentsA"))));
1599 EXPECT_FALSE(matchesObjC(
1601 objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
1602 EXPECT_TRUE(matchesObjC(
1604 objcMessageExpr(matchesSelector("cont*"))));
1605 EXPECT_FALSE(matchesObjC(
1607 objcMessageExpr(matchesSelector("?cont*"))));
1608 EXPECT_TRUE(notMatchesObjC(
1610 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
1611 EXPECT_TRUE(matchesObjC(
1613 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
1614 EXPECT_TRUE(matchesObjC(
1616 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
1617 EXPECT_TRUE(matchesObjC(
1619 objcMessageExpr(matchesSelector("uppercase*"),
1624 TEST(ObjCDeclMatcher, CoreDecls) {
1625 std::string ObjCString =
1627 "- (void)protoDidThing; "
1630 "@property int enabled; "
1632 "@interface Thing (ABC) "
1633 "- (void)abc_doThing; "
1635 "@implementation Thing "
1637 "- (void)anything {} "
1639 "@implementation Thing (ABC) "
1640 "- (void)abc_doThing {} "
1644 EXPECT_TRUE(matchesObjC(
1646 objcProtocolDecl(hasName("Proto"))));
1647 EXPECT_TRUE(matchesObjC(
1649 objcImplementationDecl(hasName("Thing"))));
1650 EXPECT_TRUE(matchesObjC(
1652 objcCategoryDecl(hasName("ABC"))));
1653 EXPECT_TRUE(matchesObjC(
1655 objcCategoryImplDecl(hasName("ABC"))));
1656 EXPECT_TRUE(matchesObjC(
1658 objcMethodDecl(hasName("protoDidThing"))));
1659 EXPECT_TRUE(matchesObjC(
1661 objcMethodDecl(hasName("abc_doThing"))));
1662 EXPECT_TRUE(matchesObjC(
1664 objcMethodDecl(hasName("anything"))));
1665 EXPECT_TRUE(matchesObjC(
1667 objcIvarDecl(hasName("_ivar"))));
1668 EXPECT_TRUE(matchesObjC(
1670 objcPropertyDecl(hasName("enabled"))));
1673 TEST(ObjCStmtMatcher, ExceptionStmts) {
1674 std::string ObjCString =
1682 EXPECT_TRUE(matchesObjC(
1685 EXPECT_TRUE(matchesObjC(
1688 EXPECT_TRUE(matchesObjC(
1691 EXPECT_TRUE(matchesObjC(
1693 objcFinallyStmt()));
1696 TEST(ObjCAutoreleaseMatcher, AutoreleasePool) {
1697 std::string ObjCString =
1699 "@autoreleasepool {"
1703 EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
1704 std::string ObjCStringNoPool = "void f() { int x = 1; }";
1705 EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
1708 } // namespace ast_matchers
1709 } // namespace clang