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(Enum, DoesNotMatchClasses) {
164 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
167 TEST(Enum, MatchesEnums) {
168 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
171 TEST(EnumConstant, Matches) {
172 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
173 EXPECT_TRUE(matches("enum X{ A };", Matcher));
174 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
175 EXPECT_TRUE(notMatches("enum X {};", Matcher));
178 TEST(Matcher, UnresolvedLookupExpr) {
179 // FIXME: The test is known to be broken on Windows with delayed template
181 EXPECT_TRUE(matchesConditionally("template<typename T>"
182 "T foo() { T a; return a; }"
183 "template<typename T>"
187 unresolvedLookupExpr(),
188 /*ExpectMatch=*/true,
189 "-fno-delayed-template-parsing"));
192 TEST(Matcher, Call) {
193 // FIXME: Do we want to overload Call() to directly take
194 // Matcher<Decl>, too?
195 StatementMatcher MethodX =
196 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
198 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
199 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
201 StatementMatcher MethodOnY =
202 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
205 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
208 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
211 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
214 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
217 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
220 StatementMatcher MethodOnYPointer =
221 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
224 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
227 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
230 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
233 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
236 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
239 TEST(Matcher, Lambda) {
240 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
244 TEST(Matcher, ForRange) {
245 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
246 "void f() { for (auto &a : as); }",
248 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
252 TEST(Matcher, SubstNonTypeTemplateParm) {
253 EXPECT_FALSE(matches("template<int N>\n"
254 "struct A { static const int n = 0; };\n"
255 "struct B : public A<42> {};",
256 substNonTypeTemplateParmExpr()));
257 EXPECT_TRUE(matches("template<int N>\n"
258 "struct A { static const int n = N; };\n"
259 "struct B : public A<42> {};",
260 substNonTypeTemplateParmExpr()));
263 TEST(Matcher, NonTypeTemplateParmDecl) {
264 EXPECT_TRUE(matches("template <int N> void f();",
265 nonTypeTemplateParmDecl(hasName("N"))));
267 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
270 TEST(Matcher, templateTypeParmDecl) {
271 EXPECT_TRUE(matches("template <typename T> void f();",
272 templateTypeParmDecl(hasName("T"))));
274 notMatches("template <int N> void f();", templateTypeParmDecl()));
277 TEST(Matcher, UserDefinedLiteral) {
278 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
282 userDefinedLiteral()));
285 TEST(Matcher, FlowControl) {
286 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
287 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
289 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
290 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
293 labelDecl(hasName("FOO"))))));
294 EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
296 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
299 TEST(Matcher, OverloadedOperatorCall) {
300 StatementMatcher OpCall = cxxOperatorCallExpr();
302 EXPECT_TRUE(matches("class Y { }; "
303 "bool operator!(Y x) { return false; }; "
304 "Y y; bool c = !y;", OpCall));
305 // No match -- special operators like "new", "delete"
306 // FIXME: operator new takes size_t, for which we need stddef.h, for which
307 // we need to figure out include paths in the test.
308 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
310 // "void *operator new(size_t size) { return 0; } "
311 // "Y *y = new Y;", OpCall));
312 EXPECT_TRUE(notMatches("class Y { }; "
313 "void operator delete(void *p) { } "
314 "void a() {Y *y = new Y; delete y;}", OpCall));
316 EXPECT_TRUE(matches("class Y { }; "
317 "bool operator&&(Y x, Y y) { return true; }; "
318 "Y a; Y b; bool c = a && b;",
320 // No match -- normal operator, not an overloaded one.
321 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
322 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
325 TEST(Matcher, ThisPointerType) {
326 StatementMatcher MethodOnY =
327 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
330 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
333 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
336 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
339 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
342 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
347 " public: virtual void x();"
349 "class X : public Y {"
350 " public: virtual void x();"
352 "void z() { X *x; x->Y::x(); }", MethodOnY));
355 TEST(Matcher, VariableUsage) {
356 StatementMatcher Reference =
358 varDecl(hasInitializer(
359 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
366 "void z(const Y &y) {"
371 EXPECT_TRUE(notMatches(
376 "void z(const Y &y) {"
381 TEST(Matcher, CalledVariable) {
382 StatementMatcher CallOnVariableY =
383 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
386 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
388 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
390 "class Y { public: void x(); };"
391 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
393 "class Y { public: void x(); };"
394 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
395 EXPECT_TRUE(notMatches(
396 "class Y { public: void x(); };"
397 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
401 TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
402 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
403 unaryExprOrTypeTraitExpr()));
404 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
405 alignOfExpr(anything())));
406 // FIXME: Uncomment once alignof is enabled.
407 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
408 // unaryExprOrTypeTraitExpr()));
409 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
413 TEST(MemberExpression, DoesNotMatchClasses) {
414 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
417 TEST(MemberExpression, MatchesMemberFunctionCall) {
418 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
421 TEST(MemberExpression, MatchesVariable) {
423 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
425 matches("class Y { void x() { y; } int y; };", memberExpr()));
427 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
430 TEST(MemberExpression, MatchesStaticVariable) {
431 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
433 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
435 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
439 TEST(Function, MatchesFunctionDeclarations) {
440 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
442 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
443 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
445 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
446 llvm::Triple::Win32) {
447 // FIXME: Make this work for MSVC.
448 // Dependent contexts, but a non-dependent call.
449 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
452 matches("void f(); template <int N> struct S { void g() { f(); } };",
456 // Depedent calls don't match.
458 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
461 notMatches("void f(int);"
462 "template <typename T> struct S { void g(T t) { f(t); } };",
465 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
466 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
467 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
468 functionDecl(isVariadic())));
469 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
470 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
471 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
472 EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0))));
473 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
476 TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
478 matches("template <typename T> void f(T t) {}",
479 functionTemplateDecl(hasName("f"))));
482 TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
484 notMatches("void f(double d); void f(int t) {}",
485 functionTemplateDecl(hasName("f"))));
488 TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
490 notMatches("void g(); template <typename T> void f(T t) {}"
491 "template <> void f(int t) { g(); }",
492 functionTemplateDecl(hasName("f"),
493 hasDescendant(declRefExpr(to(
494 functionDecl(hasName("g"))))))));
497 TEST(Matcher, MatchesClassTemplateSpecialization) {
498 EXPECT_TRUE(matches("template<typename T> struct A {};"
499 "template<> struct A<int> {};",
500 classTemplateSpecializationDecl()));
501 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
502 classTemplateSpecializationDecl()));
503 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
504 classTemplateSpecializationDecl()));
507 TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
508 EXPECT_TRUE(matches("int x;", declaratorDecl()));
509 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
512 TEST(ParmVarDecl, MatchesParmVars) {
513 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
514 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
517 TEST(Matcher, ConstructorCall) {
518 StatementMatcher Constructor = cxxConstructExpr();
521 matches("class X { public: X(); }; void x() { X x; }", Constructor));
523 matches("class X { public: X(); }; void x() { X x = X(); }",
526 matches("class X { public: X(int); }; void x() { X x = 0; }",
528 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
531 TEST(Match, ConstructorInitializers) {
532 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
533 cxxCtorInitializer(forField(hasName("i")))));
536 TEST(Matcher, ThisExpr) {
538 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
540 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
543 TEST(Matcher, BindTemporaryExpression) {
544 StatementMatcher TempExpression = cxxBindTemporaryExpr();
546 std::string ClassString = "class string { public: string(); ~string(); }; ";
549 matches(ClassString +
550 "string GetStringByValue();"
551 "void FunctionTakesString(string s);"
552 "void run() { FunctionTakesString(GetStringByValue()); }",
556 notMatches(ClassString +
557 "string* GetStringPointer(); "
558 "void FunctionTakesStringPtr(string* s);"
560 " string* s = GetStringPointer();"
561 " FunctionTakesStringPtr(GetStringPointer());"
562 " FunctionTakesStringPtr(s);"
567 notMatches("class no_dtor {};"
568 "no_dtor GetObjByValue();"
569 "void ConsumeObj(no_dtor param);"
570 "void run() { ConsumeObj(GetObjByValue()); }",
574 TEST(MaterializeTemporaryExpr, MatchesTemporary) {
575 std::string ClassString =
576 "class string { public: string(); int length(); }; ";
579 matches(ClassString +
580 "string GetStringByValue();"
581 "void FunctionTakesString(string s);"
582 "void run() { FunctionTakesString(GetStringByValue()); }",
583 materializeTemporaryExpr()));
586 notMatches(ClassString +
587 "string* GetStringPointer(); "
588 "void FunctionTakesStringPtr(string* s);"
590 " string* s = GetStringPointer();"
591 " FunctionTakesStringPtr(GetStringPointer());"
592 " FunctionTakesStringPtr(s);"
594 materializeTemporaryExpr()));
597 matches(ClassString +
598 "string GetStringByValue();"
599 "void run() { int k = GetStringByValue().length(); }",
600 materializeTemporaryExpr()));
603 notMatches(ClassString +
604 "string GetStringByValue();"
605 "void run() { GetStringByValue(); }",
606 materializeTemporaryExpr()));
609 TEST(Matcher, NewExpression) {
610 StatementMatcher New = cxxNewExpr();
612 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
614 matches("class X { public: X(); }; void x() { new X(); }", New));
616 matches("class X { public: X(int); }; void x() { new X(0); }", New));
617 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
620 TEST(Matcher, DeleteExpression) {
621 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
625 TEST(Matcher, DefaultArgument) {
626 StatementMatcher Arg = cxxDefaultArgExpr();
628 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
630 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
631 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
634 TEST(Matcher, StringLiterals) {
635 StatementMatcher Literal = stringLiteral();
636 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
638 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
639 // with escaped characters
640 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
641 // no matching -- though the data type is the same, there is no string literal
642 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
645 TEST(Matcher, CharacterLiterals) {
646 StatementMatcher CharLiteral = characterLiteral();
647 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
649 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
650 // wide character, Hex encoded, NOT MATCHED!
651 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
652 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
655 TEST(Matcher, IntegerLiterals) {
656 StatementMatcher HasIntLiteral = integerLiteral();
657 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
658 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
659 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
660 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
662 // Non-matching cases (character literals, float and double)
663 EXPECT_TRUE(notMatches("int i = L'a';",
664 HasIntLiteral)); // this is actually a character
665 // literal cast to int
666 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
667 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
668 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
671 TEST(Matcher, FloatLiterals) {
672 StatementMatcher HasFloatLiteral = floatLiteral();
673 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
674 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
675 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
676 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
677 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
678 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
679 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
681 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
683 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
684 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
685 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
687 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
690 TEST(Matcher, NullPtrLiteral) {
691 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
694 TEST(Matcher, GNUNullExpr) {
695 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
698 TEST(Matcher, AtomicExpr) {
699 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
703 TEST(Matcher, Initializers) {
704 const char *ToMatch = "void foo() { struct point { double x; double y; };"
705 " struct point ptarray[10] = "
706 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }";
707 EXPECT_TRUE(matchesConditionally(
712 requiresZeroInitialization())),
715 hasType(asString("struct point")),
716 has(floatLiteral(equals(1.0))),
717 has(implicitValueInitExpr(
718 hasType(asString("double")))))),
721 hasType(asString("struct point")),
722 has(floatLiteral(equals(2.0))),
723 has(floatLiteral(equals(1.0)))))
724 ), true, "-std=gnu++98"));
726 EXPECT_TRUE(matchesC99(ToMatch,
732 designatorCountIs(2),
739 designatorCountIs(2),
746 designatorCountIs(2),
754 TEST(Matcher, ParenListExpr) {
756 matches("template<typename T> class foo { void bar() { foo X(*this); } };"
757 "template class foo<int>;",
758 varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
761 TEST(Matcher, StmtExpr) {
762 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
763 varDecl(hasInitializer(stmtExpr()))));
766 TEST(Matcher, ImportPredefinedExpr) {
767 // __func__ expands as StringLiteral("foo")
768 EXPECT_TRUE(matches("void foo() { __func__; }",
770 hasType(asString("const char [4]")),
771 has(stringLiteral()))));
774 TEST(Matcher, AsmStatement) {
775 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
778 TEST(Matcher, Conditions) {
779 StatementMatcher Condition =
780 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
782 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
783 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
784 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
785 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
786 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
789 TEST(Matcher, ConditionalOperator) {
790 StatementMatcher Conditional = conditionalOperator(
791 hasCondition(cxxBoolLiteral(equals(true))),
792 hasTrueExpression(cxxBoolLiteral(equals(false))));
794 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
795 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
796 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
798 StatementMatcher ConditionalFalse = conditionalOperator(
799 hasFalseExpression(cxxBoolLiteral(equals(false))));
801 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
803 notMatches("void x() { true ? false : true; }", ConditionalFalse));
805 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
807 notMatches("void x() { true ? false : true; }", ConditionalFalse));
810 TEST(Matcher, BinaryConditionalOperator) {
811 StatementMatcher AlwaysOne = binaryConditionalOperator(
812 hasCondition(implicitCastExpr(
815 hasSourceExpression((integerLiteral(equals(1)))))))),
816 hasFalseExpression(integerLiteral(equals(0))));
818 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
820 StatementMatcher FourNotFive = binaryConditionalOperator(
821 hasTrueExpression(opaqueValueExpr(
822 hasSourceExpression((integerLiteral(equals(4)))))),
823 hasFalseExpression(integerLiteral(equals(5))));
825 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
828 TEST(ArraySubscriptMatchers, ArraySubscripts) {
829 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
830 arraySubscriptExpr()));
831 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
832 arraySubscriptExpr()));
835 TEST(For, FindsForLoops) {
836 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
837 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
838 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
839 "void f() { for (auto &a : as); }",
843 TEST(For, ReportsNoFalsePositives) {
844 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
845 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
848 TEST(CompoundStatement, HandlesSimpleCases) {
849 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
850 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
851 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
854 TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
855 // It's not a compound statement just because there's "{}" in the source
856 // text. This is an AST search, not grep.
857 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
859 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
863 TEST(CastExpression, MatchesExplicitCasts) {
864 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
865 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
866 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
867 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
869 TEST(CastExpression, MatchesImplicitCasts) {
870 // This test creates an implicit cast from int to char.
871 EXPECT_TRUE(matches("char c = 0;", castExpr()));
872 // This test creates an implicit cast from lvalue to rvalue.
873 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
876 TEST(CastExpression, DoesNotMatchNonCasts) {
877 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
878 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
879 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
880 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
883 TEST(ReinterpretCast, MatchesSimpleCase) {
884 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
885 cxxReinterpretCastExpr()));
888 TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
889 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
890 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
891 cxxReinterpretCastExpr()));
892 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
893 cxxReinterpretCastExpr()));
894 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
896 "D* p = dynamic_cast<D*>(&b);",
897 cxxReinterpretCastExpr()));
900 TEST(FunctionalCast, MatchesSimpleCase) {
901 std::string foo_class = "class Foo { public: Foo(const char*); };";
902 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
903 cxxFunctionalCastExpr()));
906 TEST(FunctionalCast, DoesNotMatchOtherCasts) {
907 std::string FooClass = "class Foo { public: Foo(const char*); };";
909 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
910 cxxFunctionalCastExpr()));
912 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
913 cxxFunctionalCastExpr()));
916 TEST(DynamicCast, MatchesSimpleCase) {
917 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
919 "D* p = dynamic_cast<D*>(&b);",
920 cxxDynamicCastExpr()));
923 TEST(StaticCast, MatchesSimpleCase) {
924 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
925 cxxStaticCastExpr()));
928 TEST(StaticCast, DoesNotMatchOtherCasts) {
929 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
930 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
931 cxxStaticCastExpr()));
932 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
933 cxxStaticCastExpr()));
934 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
936 "D* p = dynamic_cast<D*>(&b);",
937 cxxStaticCastExpr()));
940 TEST(CStyleCast, MatchesSimpleCase) {
941 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
944 TEST(CStyleCast, DoesNotMatchOtherCasts) {
945 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
946 "char q, *r = const_cast<char*>(&q);"
947 "void* s = reinterpret_cast<char*>(&s);"
948 "struct B { virtual ~B() {} }; struct D : B {};"
950 "D* t = dynamic_cast<D*>(&b);",
954 TEST(ImplicitCast, MatchesSimpleCase) {
955 // This test creates an implicit const cast.
956 EXPECT_TRUE(matches("int x = 0; const int y = x;",
957 varDecl(hasInitializer(implicitCastExpr()))));
958 // This test creates an implicit cast from int to char.
959 EXPECT_TRUE(matches("char c = 0;",
960 varDecl(hasInitializer(implicitCastExpr()))));
961 // This test creates an implicit array-to-pointer cast.
962 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
963 varDecl(hasInitializer(implicitCastExpr()))));
966 TEST(ImplicitCast, DoesNotMatchIncorrectly) {
967 // This test verifies that implicitCastExpr() matches exactly when implicit casts
968 // are present, and that it ignores explicit and paren casts.
970 // These two test cases have no casts.
971 EXPECT_TRUE(notMatches("int x = 0;",
972 varDecl(hasInitializer(implicitCastExpr()))));
973 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
974 varDecl(hasInitializer(implicitCastExpr()))));
976 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
977 varDecl(hasInitializer(implicitCastExpr()))));
978 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
979 varDecl(hasInitializer(implicitCastExpr()))));
981 EXPECT_TRUE(notMatches("int x = (0);",
982 varDecl(hasInitializer(implicitCastExpr()))));
985 TEST(Statement, DoesNotMatchDeclarations) {
986 EXPECT_TRUE(notMatches("class X {};", stmt()));
989 TEST(Statement, MatchesCompoundStatments) {
990 EXPECT_TRUE(matches("void x() {}", stmt()));
993 TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
994 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
997 TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
998 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1001 TEST(ExprWithCleanups, MatchesExprWithCleanups) {
1002 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
1003 "const Foo f = Foo();",
1004 varDecl(hasInitializer(exprWithCleanups()))));
1005 EXPECT_FALSE(matches("struct Foo { }; Foo a;"
1007 varDecl(hasInitializer(exprWithCleanups()))));
1010 TEST(InitListExpression, MatchesInitListExpression) {
1011 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1012 initListExpr(hasType(asString("int [2]")))));
1013 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
1014 initListExpr(hasType(recordDecl(hasName("B"))))));
1015 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1018 declRefExpr(to(functionDecl(hasName("f"))))));
1020 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1023 TEST(CXXStdInitializerListExpression, MatchesCXXStdInitializerListExpression) {
1024 const std::string code = "namespace std {"
1025 "template <typename> class initializer_list {"
1026 " public: initializer_list() noexcept {}"
1030 " A(std::initializer_list<int>) {}"
1032 EXPECT_TRUE(matches(code + "A a{0};",
1033 cxxConstructExpr(has(cxxStdInitializerListExpr()),
1034 hasDeclaration(cxxConstructorDecl(
1035 ofClass(hasName("A")))))));
1036 EXPECT_TRUE(matches(code + "A a = {0};",
1037 cxxConstructExpr(has(cxxStdInitializerListExpr()),
1038 hasDeclaration(cxxConstructorDecl(
1039 ofClass(hasName("A")))))));
1041 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1042 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1043 cxxStdInitializerListExpr()));
1046 TEST(UsingDeclaration, MatchesUsingDeclarations) {
1047 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
1051 TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
1052 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1053 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1056 TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
1057 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1058 usingDirectiveDecl()));
1060 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1064 TEST(While, MatchesWhileLoops) {
1065 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1066 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
1067 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
1070 TEST(Do, MatchesDoLoops) {
1071 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
1072 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
1075 TEST(Do, DoesNotMatchWhileLoops) {
1076 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
1079 TEST(SwitchCase, MatchesCase) {
1080 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1081 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1082 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1083 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1086 TEST(SwitchCase, MatchesSwitch) {
1087 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1088 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1089 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1090 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1093 TEST(ExceptionHandling, SimpleCases) {
1094 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1095 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1097 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1098 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
1100 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
1102 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1103 cxxCatchStmt(isCatchAll())));
1104 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1105 cxxCatchStmt(isCatchAll())));
1106 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1107 varDecl(isExceptionVariable())));
1108 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1109 varDecl(isExceptionVariable())));
1112 TEST(ParenExpression, SimpleCases) {
1113 EXPECT_TRUE(matches("int i = (3);", parenExpr()));
1114 EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr()));
1115 EXPECT_TRUE(notMatches("int i = 3;", parenExpr()));
1116 EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();",
1120 TEST(TypeMatching, MatchesTypes) {
1121 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1124 TEST(TypeMatching, MatchesConstantArrayTypes) {
1125 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1126 EXPECT_TRUE(notMatches(
1127 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1128 constantArrayType(hasElementType(builtinType()))));
1130 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1131 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1132 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1135 TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
1136 EXPECT_TRUE(matches(
1137 "template <typename T, int Size> class array { T data[Size]; };",
1138 dependentSizedArrayType()));
1139 EXPECT_TRUE(notMatches(
1140 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1141 dependentSizedArrayType()));
1144 TEST(TypeMatching, MatchesIncompleteArrayType) {
1145 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1146 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1148 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1149 incompleteArrayType()));
1152 TEST(TypeMatching, MatchesVariableArrayType) {
1153 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1154 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1156 EXPECT_TRUE(matches(
1157 "void f(int b) { int a[b]; }",
1158 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
1159 varDecl(hasName("b")))))))));
1163 TEST(TypeMatching, MatchesAtomicTypes) {
1164 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1165 llvm::Triple::Win32) {
1166 // FIXME: Make this work for MSVC.
1167 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1169 EXPECT_TRUE(matches("_Atomic(int) i;",
1170 atomicType(hasValueType(isInteger()))));
1171 EXPECT_TRUE(notMatches("_Atomic(float) f;",
1172 atomicType(hasValueType(isInteger()))));
1176 TEST(TypeMatching, MatchesAutoTypes) {
1177 EXPECT_TRUE(matches("auto i = 2;", autoType()));
1178 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1181 // FIXME: Matching against the type-as-written can't work here, because the
1182 // type as written was not deduced.
1183 //EXPECT_TRUE(matches("auto a = 1;",
1184 // autoType(hasDeducedType(isInteger()))));
1185 //EXPECT_TRUE(notMatches("auto b = 2.0;",
1186 // autoType(hasDeducedType(isInteger()))));
1189 TEST(TypeMatching, MatchesFunctionTypes) {
1190 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1191 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1194 TEST(TypeMatching, IgnoringParens) {
1196 notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1197 EXPECT_TRUE(matches("void (*fp)(void);",
1198 pointerType(pointee(ignoringParens(functionType())))));
1201 TEST(TypeMatching, MatchesFunctionProtoTypes) {
1202 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1203 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1204 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1205 EXPECT_TRUE(notMatchesC("void f();", functionProtoType()));
1207 matchesC("void f(void);", functionProtoType(parameterCountIs(0))));
1210 TEST(TypeMatching, MatchesParenType) {
1212 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1213 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1215 EXPECT_TRUE(matches(
1216 "int (*ptr_to_func)(int);",
1217 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1218 EXPECT_TRUE(notMatches(
1219 "int (*ptr_to_array)[4];",
1220 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1223 TEST(TypeMatching, PointerTypes) {
1224 // FIXME: Reactive when these tests can be more specific (not matching
1225 // implicit code on certain platforms), likely when we have hasDescendant for
1227 //EXPECT_TRUE(matchAndVerifyResultTrue(
1229 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1230 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1231 //EXPECT_TRUE(matchAndVerifyResultTrue(
1233 // pointerTypeLoc().bind("loc"),
1234 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1235 EXPECT_TRUE(matches(
1237 loc(pointerType(pointee(qualType())))));
1238 EXPECT_TRUE(matches(
1240 loc(pointerType(pointee(pointerType())))));
1241 EXPECT_TRUE(matches(
1242 "int* b; int* * const a = &b;",
1243 loc(qualType(isConstQualified(), pointerType()))));
1245 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1246 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1247 hasType(blockPointerType()))));
1248 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1249 hasType(memberPointerType()))));
1250 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1251 hasType(pointerType()))));
1252 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1253 hasType(referenceType()))));
1254 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1255 hasType(lValueReferenceType()))));
1256 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1257 hasType(rValueReferenceType()))));
1259 Fragment = "int *ptr;";
1260 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1261 hasType(blockPointerType()))));
1262 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1263 hasType(memberPointerType()))));
1264 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
1265 hasType(pointerType()))));
1266 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
1267 hasType(referenceType()))));
1269 Fragment = "int a; int &ref = a;";
1270 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1271 hasType(blockPointerType()))));
1272 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1273 hasType(memberPointerType()))));
1274 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1275 hasType(pointerType()))));
1276 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1277 hasType(referenceType()))));
1278 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1279 hasType(lValueReferenceType()))));
1280 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1281 hasType(rValueReferenceType()))));
1283 Fragment = "int &&ref = 2;";
1284 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1285 hasType(blockPointerType()))));
1286 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1287 hasType(memberPointerType()))));
1288 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1289 hasType(pointerType()))));
1290 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1291 hasType(referenceType()))));
1292 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
1293 hasType(lValueReferenceType()))));
1294 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
1295 hasType(rValueReferenceType()))));
1298 TEST(TypeMatching, AutoRefTypes) {
1299 std::string Fragment = "auto a = 1;"
1304 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
1305 hasType(referenceType()))));
1306 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
1307 hasType(referenceType()))));
1308 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1309 hasType(referenceType()))));
1310 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
1311 hasType(lValueReferenceType()))));
1312 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
1313 hasType(rValueReferenceType()))));
1314 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1315 hasType(referenceType()))));
1316 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
1317 hasType(lValueReferenceType()))));
1318 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
1319 hasType(rValueReferenceType()))));
1320 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1321 hasType(referenceType()))));
1322 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
1323 hasType(lValueReferenceType()))));
1324 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
1325 hasType(rValueReferenceType()))));
1328 TEST(TypeMatching, MatchesEnumTypes) {
1329 EXPECT_TRUE(matches("enum Color { Green }; Color color;",
1331 EXPECT_TRUE(matches("enum class Color { Green }; Color color;",
1335 TEST(TypeMatching, MatchesPointersToConstTypes) {
1336 EXPECT_TRUE(matches("int b; int * const a = &b;",
1337 loc(pointerType())));
1338 EXPECT_TRUE(matches("int b; int * const a = &b;",
1339 loc(pointerType())));
1340 EXPECT_TRUE(matches(
1341 "int b; const int * a = &b;",
1342 loc(pointerType(pointee(builtinType())))));
1343 EXPECT_TRUE(matches(
1344 "int b; const int * a = &b;",
1345 pointerType(pointee(builtinType()))));
1348 TEST(TypeMatching, MatchesTypedefTypes) {
1349 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
1350 hasType(typedefType()))));
1353 TEST(TypeMatching, MatchesTemplateSpecializationType) {
1354 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1355 templateSpecializationType()));
1358 TEST(TypeMatching, MatchesRecordType) {
1359 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
1360 EXPECT_TRUE(matches("struct S{}; S s;",
1361 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1362 EXPECT_TRUE(notMatches("int i;",
1363 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1366 TEST(TypeMatching, MatchesElaboratedType) {
1367 EXPECT_TRUE(matches(
1373 "N::M::D d;", elaboratedType()));
1374 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1375 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
1378 TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
1379 const std::string code = "template <typename T>"
1383 "int i = F<int>();";
1384 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1385 expr(hasType(substTemplateTypeParmType()))))));
1386 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1387 expr(hasType(substTemplateTypeParmType()))))));
1390 TEST(NNS, MatchesNestedNameSpecifiers) {
1391 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
1392 nestedNameSpecifier()));
1393 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1394 nestedNameSpecifier()));
1395 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
1396 nestedNameSpecifier()));
1397 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1398 nestedNameSpecifier()));
1400 EXPECT_TRUE(matches(
1401 "struct A { static void f() {} }; void g() { A::f(); }",
1402 nestedNameSpecifier()));
1403 EXPECT_TRUE(notMatches(
1404 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
1405 nestedNameSpecifier()));
1408 TEST(NullStatement, SimpleCases) {
1409 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1410 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1414 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1415 namespaceAliasDecl(hasName("alias"))));
1418 TEST(NNS, MatchesTypes) {
1419 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1420 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1421 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1422 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
1424 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
1427 TEST(NNS, MatchesNamespaceDecls) {
1428 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1429 specifiesNamespace(hasName("ns")));
1430 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
1431 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
1432 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
1435 TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
1436 EXPECT_TRUE(matches(
1437 "struct A { struct B { struct C {}; }; }; A::B::C c;",
1438 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
1439 EXPECT_TRUE(matches(
1440 "struct A { struct B { struct C {}; }; }; A::B::C c;",
1441 nestedNameSpecifierLoc(hasPrefix(
1442 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
1446 template <typename T>
1447 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
1449 bool run(const BoundNodes *Nodes) override { return false; }
1451 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
1452 const T *Node = Nodes->getNodeAs<T>("");
1453 return verify(*Nodes, *Context, Node);
1456 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
1457 // Use the original typed pointer to verify we can pass pointers to subtypes
1459 const T *TypedNode = cast<T>(Node);
1460 return selectFirst<T>(
1461 "", match(stmt(hasParent(
1462 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
1463 *Node, Context)) != nullptr;
1465 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
1466 // Use the original typed pointer to verify we can pass pointers to subtypes
1468 const T *TypedNode = cast<T>(Node);
1469 return selectFirst<T>(
1470 "", match(decl(hasParent(
1471 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
1472 *Node, Context)) != nullptr;
1474 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
1475 // Use the original typed pointer to verify we can pass pointers to subtypes
1477 const T *TypedNode = cast<T>(Node);
1478 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
1479 return selectFirst<T>(
1480 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
1481 hasType(type(equalsNode(TypedNode)).bind(""))))))),
1482 *Dec, Context)) != nullptr;
1486 TEST(IsEqualTo, MatchesNodesByIdentity) {
1487 EXPECT_TRUE(matchAndVerifyResultTrue(
1488 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
1489 llvm::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
1490 EXPECT_TRUE(matchAndVerifyResultTrue(
1491 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
1492 llvm::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
1493 EXPECT_TRUE(matchAndVerifyResultTrue(
1494 "class X { class Y {} y; };",
1495 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
1496 llvm::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
1499 TEST(TypedefDeclMatcher, Match) {
1500 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
1501 typedefDecl(hasName("typedefDeclTest"))));
1502 EXPECT_TRUE(notMatches("using typedefDeclTest2 = int;",
1503 typedefDecl(hasName("typedefDeclTest2"))));
1506 TEST(TypeAliasDeclMatcher, Match) {
1507 EXPECT_TRUE(matches("using typeAliasTest2 = int;",
1508 typeAliasDecl(hasName("typeAliasTest2"))));
1509 EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
1510 typeAliasDecl(hasName("typeAliasTest"))));
1513 TEST(TypedefNameDeclMatcher, Match) {
1514 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
1515 typedefNameDecl(hasName("typedefNameDeclTest1"))));
1516 EXPECT_TRUE(matches("using typedefNameDeclTest2 = int;",
1517 typedefNameDecl(hasName("typedefNameDeclTest2"))));
1520 TEST(TypeAliasTemplateDeclMatcher, Match) {
1521 std::string Code = R"(
1522 template <typename T>
1525 template <typename T>
1526 using typeAliasTemplateDecl = X<T>;
1528 using typeAliasDecl = X<int>;
1531 matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
1533 notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
1536 TEST(ObjCMessageExprMatcher, SimpleExprs) {
1537 // don't find ObjCMessageExpr where none are present
1538 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
1540 std::string Objc1String =
1542 " - (Str *)uppercaseString;"
1546 "- (void)meth:(Str *)text;"
1549 "@implementation foo "
1550 "- (void) meth:(Str *)text { "
1552 " Str *up = [text uppercaseString];"
1555 EXPECT_TRUE(matchesObjC(
1557 objcMessageExpr(anything())));
1558 EXPECT_TRUE(matchesObjC(
1560 objcMessageExpr(hasSelector("contents"))));
1561 EXPECT_TRUE(matchesObjC(
1563 objcMessageExpr(matchesSelector("cont*"))));
1564 EXPECT_FALSE(matchesObjC(
1566 objcMessageExpr(matchesSelector("?cont*"))));
1567 EXPECT_TRUE(notMatchesObjC(
1569 objcMessageExpr(hasSelector("contents"), hasNullSelector())));
1570 EXPECT_TRUE(matchesObjC(
1572 objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
1573 EXPECT_TRUE(matchesObjC(
1575 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
1576 EXPECT_TRUE(matchesObjC(
1578 objcMessageExpr(matchesSelector("uppercase*"),
1583 TEST(ObjCDeclMacher, CoreDecls) {
1584 std::string ObjCString =
1586 "- (void)protoDidThing; "
1589 "@property int enabled; "
1591 "@interface Thing (ABC) "
1592 "- (void)abc_doThing; "
1594 "@implementation Thing "
1596 "- (void)anything {} "
1600 EXPECT_TRUE(matchesObjC(
1602 objcProtocolDecl(hasName("Proto"))));
1603 EXPECT_TRUE(matchesObjC(
1605 objcCategoryDecl(hasName("ABC"))));
1606 EXPECT_TRUE(matchesObjC(
1608 objcMethodDecl(hasName("protoDidThing"))));
1609 EXPECT_TRUE(matchesObjC(
1611 objcMethodDecl(hasName("abc_doThing"))));
1612 EXPECT_TRUE(matchesObjC(
1614 objcMethodDecl(hasName("anything"))));
1615 EXPECT_TRUE(matchesObjC(
1617 objcIvarDecl(hasName("_ivar"))));
1618 EXPECT_TRUE(matchesObjC(
1620 objcPropertyDecl(hasName("enabled"))));
1623 } // namespace ast_matchers
1624 } // namespace clang