1//== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ASTMatchersTest.h"
10#include "clang/AST/PrettyPrinter.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Tooling/Tooling.h"
14#include "llvm/TargetParser/Host.h"
15#include "llvm/TargetParser/Triple.h"
16#include "gtest/gtest.h"
17
18namespace clang {
19namespace ast_matchers {
20
21TEST_P(ASTMatchersTest, Decl_CXX) {
22 if (!GetParam().isCXX()) {
23 // FIXME: Add a test for `decl()` that does not depend on C++.
24 return;
25 }
26 EXPECT_TRUE(notMatches("", decl(usingDecl())));
27 EXPECT_TRUE(
28 matches("namespace x { class X {}; } using x::X;", decl(usingDecl())));
29}
30
31TEST_P(ASTMatchersTest, NameableDeclaration_MatchesVariousDecls) {
32 DeclarationMatcher NamedX = namedDecl(hasName(Name: "X"));
33 EXPECT_TRUE(matches("typedef int X;", NamedX));
34 EXPECT_TRUE(matches("int X;", NamedX));
35 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
36 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
37
38 EXPECT_TRUE(notMatches("#define X 1", NamedX));
39}
40
41TEST_P(ASTMatchersTest, NamedDecl_CXX) {
42 if (!GetParam().isCXX()) {
43 return;
44 }
45 DeclarationMatcher NamedX = namedDecl(hasName(Name: "X"));
46 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
47 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
48 EXPECT_TRUE(matches("namespace X { }", NamedX));
49}
50
51TEST_P(ASTMatchersTest, MatchesNameRE) {
52 DeclarationMatcher NamedX = namedDecl(matchesName(RegExp: "::X"));
53 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
54 EXPECT_TRUE(matches("int Xb;", NamedX));
55 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
56 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
57
58 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
59
60 DeclarationMatcher StartsWithNo = namedDecl(matchesName(RegExp: "::no"));
61 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
62
63 DeclarationMatcher Abc = namedDecl(matchesName(RegExp: "a.*b.*c"));
64 EXPECT_TRUE(matches("int abc;", Abc));
65 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
66 EXPECT_TRUE(notMatches("int cab;", Abc));
67 EXPECT_TRUE(matches("int cabc;", Abc));
68
69 DeclarationMatcher StartsWithK = namedDecl(matchesName(RegExp: ":k[^:]*$"));
70 EXPECT_TRUE(matches("int k;", StartsWithK));
71 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
72}
73
74TEST_P(ASTMatchersTest, MatchesNameRE_CXX) {
75 if (!GetParam().isCXX()) {
76 return;
77 }
78 DeclarationMatcher NamedX = namedDecl(matchesName(RegExp: "::X"));
79 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
80 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
81 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
82
83 DeclarationMatcher StartsWithNo = namedDecl(matchesName(RegExp: "::no"));
84 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
85
86 DeclarationMatcher StartsWithK = namedDecl(matchesName(RegExp: ":k[^:]*$"));
87 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
88 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
89 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
90 EXPECT_TRUE(notMatches("int K;", StartsWithK));
91
92 DeclarationMatcher StartsWithKIgnoreCase =
93 namedDecl(matchesName(RegExp: ":k[^:]*$", RegexFlags: llvm::Regex::IgnoreCase));
94 EXPECT_TRUE(matches("int k;", StartsWithKIgnoreCase));
95 EXPECT_TRUE(matches("int K;", StartsWithKIgnoreCase));
96}
97
98TEST_P(ASTMatchersTest, DeclarationMatcher_MatchClass) {
99 if (!GetParam().isCXX()) {
100 return;
101 }
102
103 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName(Name: "X")));
104 EXPECT_TRUE(matches("class X;", ClassX));
105 EXPECT_TRUE(matches("class X {};", ClassX));
106 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
107 EXPECT_TRUE(notMatches("", ClassX));
108}
109
110TEST_P(ASTMatchersTest, TranslationUnitDecl) {
111 if (!GetParam().isCXX()) {
112 // FIXME: Add a test for `translationUnitDecl()` that does not depend on
113 // C++.
114 return;
115 }
116 StringRef Code = "int MyVar1;\n"
117 "namespace NameSpace {\n"
118 "int MyVar2;\n"
119 "} // namespace NameSpace\n";
120 EXPECT_TRUE(matches(
121 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
122 EXPECT_FALSE(matches(
123 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
124 EXPECT_TRUE(matches(
125 Code,
126 varDecl(hasName("MyVar2"),
127 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
128}
129
130TEST_P(ASTMatchersTest, LinkageSpecDecl) {
131 if (!GetParam().isCXX()) {
132 return;
133 }
134 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
135 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
136}
137
138TEST_P(ASTMatchersTest, ClassTemplateDecl_DoesNotMatchClass) {
139 if (!GetParam().isCXX()) {
140 return;
141 }
142 DeclarationMatcher ClassX = classTemplateDecl(hasName(Name: "X"));
143 EXPECT_TRUE(notMatches("class X;", ClassX));
144 EXPECT_TRUE(notMatches("class X {};", ClassX));
145}
146
147TEST_P(ASTMatchersTest, ClassTemplateDecl_MatchesClassTemplate) {
148 if (!GetParam().isCXX()) {
149 return;
150 }
151 DeclarationMatcher ClassX = classTemplateDecl(hasName(Name: "X"));
152 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
153 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
154}
155
156TEST_P(ASTMatchersTest,
157 ClassTemplateDecl_DoesNotMatchClassTemplateExplicitSpecialization) {
158 if (!GetParam().isCXX()) {
159 return;
160 }
161 EXPECT_TRUE(notMatches(
162 "template<typename T> class X { };"
163 "template<> class X<int> { int a; };",
164 classTemplateDecl(hasName("X"), hasDescendant(fieldDecl(hasName("a"))))));
165}
166
167TEST_P(ASTMatchersTest,
168 ClassTemplateDecl_DoesNotMatchClassTemplatePartialSpecialization) {
169 if (!GetParam().isCXX()) {
170 return;
171 }
172 EXPECT_TRUE(notMatches(
173 "template<typename T, typename U> class X { };"
174 "template<typename T> class X<T, int> { int a; };",
175 classTemplateDecl(hasName("X"), hasDescendant(fieldDecl(hasName("a"))))));
176}
177
178TEST(ASTMatchersTestCUDA, CUDAKernelCallExpr) {
179 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
180 "void g() { f<<<1, 2>>>(); }",
181 cudaKernelCallExpr()));
182 EXPECT_TRUE(notMatchesWithCuda("void f() {}", cudaKernelCallExpr()));
183}
184
185TEST(ASTMatchersTestCUDA, HasAttrCUDA) {
186 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
187 hasAttr(clang::attr::CUDADevice)));
188 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
189 hasAttr(clang::attr::CUDAGlobal)));
190}
191
192TEST_P(ASTMatchersTest, ValueDecl) {
193 if (!GetParam().isCXX()) {
194 // FIXME: Fix this test in non-C++ language modes.
195 return;
196 }
197 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
198 valueDecl(hasType(asString("enum EnumType")))));
199 EXPECT_TRUE(matches("void FunctionDecl();",
200 valueDecl(hasType(asString("void (void)")))));
201}
202
203TEST_P(ASTMatchersTest, FriendDecl) {
204 if (!GetParam().isCXX()) {
205 return;
206 }
207 EXPECT_TRUE(matches("class Y { friend class X; };",
208 friendDecl(hasType(asString("class X")))));
209 EXPECT_TRUE(matches("class Y { friend class X; };",
210 friendDecl(hasType(recordDecl(hasName("X"))))));
211
212 EXPECT_TRUE(matches("class Y { friend void f(); };",
213 functionDecl(hasName("f"), hasParent(friendDecl()))));
214}
215
216TEST_P(ASTMatchersTest, EnumDecl_DoesNotMatchClasses) {
217 if (!GetParam().isCXX()) {
218 return;
219 }
220 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
221}
222
223TEST_P(ASTMatchersTest, EnumDecl_MatchesEnums) {
224 if (!GetParam().isCXX()) {
225 // FIXME: Fix this test in non-C++ language modes.
226 return;
227 }
228 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
229}
230
231TEST_P(ASTMatchersTest, EnumConstantDecl) {
232 if (!GetParam().isCXX()) {
233 // FIXME: Fix this test in non-C++ language modes.
234 return;
235 }
236 DeclarationMatcher Matcher = enumConstantDecl(hasName(Name: "A"));
237 EXPECT_TRUE(matches("enum X{ A };", Matcher));
238 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
239 EXPECT_TRUE(notMatches("enum X {};", Matcher));
240}
241
242TEST_P(ASTMatchersTest, TagDecl) {
243 if (!GetParam().isCXX()) {
244 // FIXME: Fix this test in non-C++ language modes.
245 return;
246 }
247 EXPECT_TRUE(matches("struct X {};", tagDecl(hasName("X"))));
248 EXPECT_TRUE(matches("union U {};", tagDecl(hasName("U"))));
249 EXPECT_TRUE(matches("enum E {};", tagDecl(hasName("E"))));
250}
251
252TEST_P(ASTMatchersTest, TagDecl_CXX) {
253 if (!GetParam().isCXX()) {
254 return;
255 }
256 EXPECT_TRUE(matches("class C {};", tagDecl(hasName("C"))));
257}
258
259TEST_P(ASTMatchersTest, UnresolvedLookupExpr) {
260 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
261 // FIXME: Fix this test to work with delayed template parsing.
262 return;
263 }
264
265 EXPECT_TRUE(matches("template<typename T>"
266 "T foo() { T a; return a; }"
267 "template<typename T>"
268 "void bar() {"
269 " foo<T>();"
270 "}",
271 unresolvedLookupExpr()));
272}
273
274TEST_P(ASTMatchersTest, UsesADL) {
275 if (!GetParam().isCXX()) {
276 return;
277 }
278
279 StatementMatcher ADLMatch = callExpr(usesADL());
280 StatementMatcher ADLMatchOper = cxxOperatorCallExpr(usesADL());
281 StringRef NS_Str = R"cpp(
282 namespace NS {
283 struct X {};
284 void f(X);
285 void operator+(X, X);
286 }
287 struct MyX {};
288 void f(...);
289 void operator+(MyX, MyX);
290)cpp";
291
292 auto MkStr = [&](StringRef Body) {
293 return (NS_Str + "void test_fn() { " + Body + " }").str();
294 };
295
296 EXPECT_TRUE(matches(MkStr("NS::X x; f(x);"), ADLMatch));
297 EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::f(x);"), ADLMatch));
298 EXPECT_TRUE(notMatches(MkStr("MyX x; f(x);"), ADLMatch));
299 EXPECT_TRUE(notMatches(MkStr("NS::X x; using NS::f; f(x);"), ADLMatch));
300
301 // Operator call expressions
302 EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatch));
303 EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatchOper));
304 EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatch));
305 EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatchOper));
306 EXPECT_TRUE(matches(MkStr("NS::X x; operator+(x, x);"), ADLMatch));
307 EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::operator+(x, x);"), ADLMatch));
308}
309
310TEST_P(ASTMatchersTest, CallExpr_CXX) {
311 if (!GetParam().isCXX()) {
312 // FIXME: Add a test for `callExpr()` that does not depend on C++.
313 return;
314 }
315 // FIXME: Do we want to overload Call() to directly take
316 // Matcher<Decl>, too?
317 StatementMatcher MethodX =
318 callExpr(hasDeclaration(InnerMatcher: cxxMethodDecl(hasName(Name: "x"))));
319
320 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
321 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
322
323 StatementMatcher MethodOnY =
324 cxxMemberCallExpr(on(InnerMatcher: hasType(InnerMatcher: recordDecl(hasName(Name: "Y")))));
325
326 EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
327 MethodOnY));
328 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
329 MethodOnY));
330 EXPECT_TRUE(notMatches(
331 "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
332 EXPECT_TRUE(notMatches(
333 "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
334 EXPECT_TRUE(notMatches(
335 "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
336
337 StatementMatcher MethodOnYPointer =
338 cxxMemberCallExpr(on(InnerMatcher: hasType(InnerMatcher: pointsTo(InnerMatcher: recordDecl(hasName(Name: "Y"))))));
339
340 EXPECT_TRUE(
341 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
342 MethodOnYPointer));
343 EXPECT_TRUE(
344 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
345 MethodOnYPointer));
346 EXPECT_TRUE(
347 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
348 MethodOnYPointer));
349 EXPECT_TRUE(
350 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
351 MethodOnYPointer));
352 EXPECT_TRUE(
353 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
354 MethodOnYPointer));
355}
356
357TEST_P(ASTMatchersTest, LambdaExpr) {
358 if (!GetParam().isCXX11OrLater()) {
359 return;
360 }
361 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", lambdaExpr()));
362}
363
364TEST_P(ASTMatchersTest, CXXForRangeStmt) {
365 EXPECT_TRUE(
366 notMatches("void f() { for (int i; i<5; ++i); }", cxxForRangeStmt()));
367}
368
369TEST_P(ASTMatchersTest, CXXForRangeStmt_CXX11) {
370 if (!GetParam().isCXX11OrLater()) {
371 return;
372 }
373 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
374 "void f() { for (auto &a : as); }",
375 cxxForRangeStmt()));
376}
377
378TEST_P(ASTMatchersTest, SubstNonTypeTemplateParmExpr) {
379 if (!GetParam().isCXX()) {
380 return;
381 }
382 EXPECT_FALSE(matches("template<int N>\n"
383 "struct A { static const int n = 0; };\n"
384 "struct B : public A<42> {};",
385 traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
386 EXPECT_TRUE(matches("template<int N>\n"
387 "struct A { static const int n = N; };\n"
388 "struct B : public A<42> {};",
389 traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
390}
391
392TEST_P(ASTMatchersTest, NonTypeTemplateParmDecl) {
393 if (!GetParam().isCXX()) {
394 return;
395 }
396 EXPECT_TRUE(matches("template <int N> void f();",
397 nonTypeTemplateParmDecl(hasName("N"))));
398 EXPECT_TRUE(
399 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
400}
401
402TEST_P(ASTMatchersTest, TemplateTypeParmDecl) {
403 if (!GetParam().isCXX()) {
404 return;
405 }
406 EXPECT_TRUE(matches("template <typename T> void f();",
407 templateTypeParmDecl(hasName("T"))));
408 EXPECT_TRUE(notMatches("template <int N> void f();", templateTypeParmDecl()));
409}
410
411TEST_P(ASTMatchersTest, TemplateTemplateParmDecl) {
412 if (!GetParam().isCXX())
413 return;
414 EXPECT_TRUE(matches("template <template <typename> class Z> void f();",
415 templateTemplateParmDecl(hasName("Z"))));
416 EXPECT_TRUE(notMatches("template <typename, int> void f();",
417 templateTemplateParmDecl()));
418}
419
420TEST_P(ASTMatchersTest, UserDefinedLiteral) {
421 if (!GetParam().isCXX11OrLater()) {
422 return;
423 }
424 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
425 " return i + 1;"
426 "}"
427 "char c = 'a'_inc;",
428 userDefinedLiteral()));
429}
430
431TEST_P(ASTMatchersTest, FlowControl) {
432 EXPECT_TRUE(matches("void f() { while(1) { break; } }", breakStmt()));
433 EXPECT_TRUE(matches("void f() { while(1) { continue; } }", continueStmt()));
434 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
435 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
436 labelStmt(hasDeclaration(labelDecl(hasName("FOO"))))));
437 EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
438 addrLabelExpr()));
439 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
440}
441
442TEST_P(ASTMatchersTest, CXXOperatorCallExpr) {
443 if (!GetParam().isCXX()) {
444 return;
445 }
446
447 StatementMatcher OpCall = cxxOperatorCallExpr();
448 // Unary operator
449 EXPECT_TRUE(matches("class Y { }; "
450 "bool operator!(Y x) { return false; }; "
451 "Y y; bool c = !y;",
452 OpCall));
453 // No match -- special operators like "new", "delete"
454 // FIXME: operator new takes size_t, for which we need stddef.h, for which
455 // we need to figure out include paths in the test.
456 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
457 // "class Y { }; "
458 // "void *operator new(size_t size) { return 0; } "
459 // "Y *y = new Y;", OpCall));
460 EXPECT_TRUE(notMatches("class Y { }; "
461 "void operator delete(void *p) { } "
462 "void a() {Y *y = new Y; delete y;}",
463 OpCall));
464 // Binary operator
465 EXPECT_TRUE(matches("class Y { }; "
466 "bool operator&&(Y x, Y y) { return true; }; "
467 "Y a; Y b; bool c = a && b;",
468 OpCall));
469 // No match -- normal operator, not an overloaded one.
470 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
471 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
472}
473
474TEST_P(ASTMatchersTest, FoldExpr) {
475 if (!GetParam().isCXX() || !GetParam().isCXX17OrLater()) {
476 return;
477 }
478
479 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
480 "return (0 + ... + args); }",
481 cxxFoldExpr()));
482 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
483 "return (args + ...); }",
484 cxxFoldExpr()));
485}
486
487TEST_P(ASTMatchersTest, ThisPointerType) {
488 if (!GetParam().isCXX()) {
489 return;
490 }
491
492 StatementMatcher MethodOnY = traverse(
493 TK: TK_AsIs, InnerMatcher: cxxMemberCallExpr(thisPointerType(InnerMatcher: recordDecl(hasName(Name: "Y")))));
494
495 EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
496 MethodOnY));
497 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
498 MethodOnY));
499 EXPECT_TRUE(matches(
500 "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
501 EXPECT_TRUE(matches(
502 "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
503 EXPECT_TRUE(matches(
504 "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
505
506 EXPECT_TRUE(matches("class Y {"
507 " public: virtual void x();"
508 "};"
509 "class X : public Y {"
510 " public: virtual void x();"
511 "};"
512 "void z() { X *x; x->Y::x(); }",
513 MethodOnY));
514}
515
516TEST_P(ASTMatchersTest, DeclRefExpr) {
517 if (!GetParam().isCXX()) {
518 // FIXME: Add a test for `declRefExpr()` that does not depend on C++.
519 return;
520 }
521 StatementMatcher Reference = declRefExpr(to(InnerMatcher: varDecl(hasInitializer(
522 InnerMatcher: cxxMemberCallExpr(thisPointerType(InnerMatcher: recordDecl(hasName(Name: "Y"))))))));
523
524 EXPECT_TRUE(matches("class Y {"
525 " public:"
526 " bool x() const;"
527 "};"
528 "void z(const Y &y) {"
529 " bool b = y.x();"
530 " if (b) {}"
531 "}",
532 Reference));
533
534 EXPECT_TRUE(notMatches("class Y {"
535 " public:"
536 " bool x() const;"
537 "};"
538 "void z(const Y &y) {"
539 " bool b = y.x();"
540 "}",
541 Reference));
542}
543
544TEST_P(ASTMatchersTest, CXXMemberCallExpr) {
545 if (!GetParam().isCXX()) {
546 return;
547 }
548 StatementMatcher CallOnVariableY =
549 cxxMemberCallExpr(on(InnerMatcher: declRefExpr(to(InnerMatcher: varDecl(hasName(Name: "y"))))));
550
551 EXPECT_TRUE(matches("class Y { public: void x() { Y y; y.x(); } };",
552 CallOnVariableY));
553 EXPECT_TRUE(matches("class Y { public: void x() const { Y y; y.x(); } };",
554 CallOnVariableY));
555 EXPECT_TRUE(matches("class Y { public: void x(); };"
556 "class X : public Y { void z() { X y; y.x(); } };",
557 CallOnVariableY));
558 EXPECT_TRUE(matches("class Y { public: void x(); };"
559 "class X : public Y { void z() { X *y; y->x(); } };",
560 CallOnVariableY));
561 EXPECT_TRUE(notMatches(
562 "class Y { public: void x(); };"
563 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
564 CallOnVariableY));
565}
566
567TEST_P(ASTMatchersTest, UnaryExprOrTypeTraitExpr) {
568 EXPECT_TRUE(
569 matches("void x() { int a = sizeof(a); }", unaryExprOrTypeTraitExpr()));
570}
571
572TEST_P(ASTMatchersTest, AlignOfExpr) {
573 EXPECT_TRUE(
574 notMatches("void x() { int a = sizeof(a); }", alignOfExpr(anything())));
575 // FIXME: Uncomment once alignof is enabled.
576 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
577 // unaryExprOrTypeTraitExpr()));
578 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
579 // sizeOfExpr()));
580}
581
582TEST_P(ASTMatchersTest, MemberExpr_DoesNotMatchClasses) {
583 if (!GetParam().isCXX()) {
584 return;
585 }
586 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
587 EXPECT_TRUE(notMatches("class Y { void x() {} };", unresolvedMemberExpr()));
588 EXPECT_TRUE(
589 notMatches("class Y { void x() {} };", cxxDependentScopeMemberExpr()));
590}
591
592TEST_P(ASTMatchersTest, MemberExpr_MatchesMemberFunctionCall) {
593 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
594 // FIXME: Fix this test to work with delayed template parsing.
595 return;
596 }
597 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
598 EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
599 unresolvedMemberExpr()));
600 EXPECT_TRUE(matches("template <class T> void x() { T t; t.f(); }",
601 cxxDependentScopeMemberExpr()));
602}
603
604TEST_P(ASTMatchersTest, MemberExpr_MatchesVariable) {
605 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
606 // FIXME: Fix this test to work with delayed template parsing.
607 return;
608 }
609 EXPECT_TRUE(
610 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
611 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", memberExpr()));
612 EXPECT_TRUE(
613 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
614 EXPECT_TRUE(matches("template <class T>"
615 "class X : T { void f() { this->T::v; } };",
616 cxxDependentScopeMemberExpr()));
617 EXPECT_TRUE(matches("template <class T> class X : T { void f() { T::v; } };",
618 cxxDependentScopeMemberExpr()));
619 EXPECT_TRUE(matches("template <class T> void x() { T t; t.v; }",
620 cxxDependentScopeMemberExpr()));
621}
622
623TEST_P(ASTMatchersTest, MemberExpr_MatchesStaticVariable) {
624 if (!GetParam().isCXX()) {
625 return;
626 }
627 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
628 memberExpr()));
629 EXPECT_TRUE(
630 notMatches("class Y { void x() { y; } static int y; };", memberExpr()));
631 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
632 memberExpr()));
633}
634
635TEST_P(ASTMatchersTest, FunctionDecl) {
636 StatementMatcher CallFunctionF = callExpr(callee(InnerMatcher: functionDecl(hasName(Name: "f"))));
637
638 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
639 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
640
641 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
642 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
643 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
644}
645
646TEST_P(ASTMatchersTest, FunctionDecl_C) {
647 if (!GetParam().isC()) {
648 return;
649 }
650 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
651 EXPECT_TRUE(matches("void f();", functionDecl(parameterCountIs(0))));
652}
653
654TEST_P(ASTMatchersTest, FunctionDecl_CXX) {
655 if (!GetParam().isCXX()) {
656 return;
657 }
658
659 StatementMatcher CallFunctionF = callExpr(callee(InnerMatcher: functionDecl(hasName(Name: "f"))));
660
661 if (!GetParam().hasDelayedTemplateParsing()) {
662 // FIXME: Fix this test to work with delayed template parsing.
663 // Dependent contexts, but a non-dependent call.
664 EXPECT_TRUE(
665 matches("void f(); template <int N> void g() { f(); }", CallFunctionF));
666 EXPECT_TRUE(
667 matches("void f(); template <int N> struct S { void g() { f(); } };",
668 CallFunctionF));
669 }
670
671 // Dependent calls don't match.
672 EXPECT_TRUE(
673 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
674 CallFunctionF));
675 EXPECT_TRUE(
676 notMatches("void f(int);"
677 "template <typename T> struct S { void g(T t) { f(t); } };",
678 CallFunctionF));
679
680 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
681 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
682}
683
684TEST_P(ASTMatchersTest, FunctionDecl_CXX11) {
685 if (!GetParam().isCXX11OrLater()) {
686 return;
687 }
688
689 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
690 functionDecl(isVariadic())));
691}
692
693TEST_P(ASTMatchersTest,
694 FunctionTemplateDecl_MatchesFunctionTemplateDeclarations) {
695 if (!GetParam().isCXX()) {
696 return;
697 }
698 EXPECT_TRUE(matches("template <typename T> void f(T t) {}",
699 functionTemplateDecl(hasName("f"))));
700}
701
702TEST_P(ASTMatchersTest, FunctionTemplate_DoesNotMatchFunctionDeclarations) {
703 EXPECT_TRUE(
704 notMatches("void f(double d);", functionTemplateDecl(hasName("f"))));
705 EXPECT_TRUE(
706 notMatches("void f(int t) {}", functionTemplateDecl(hasName("f"))));
707}
708
709TEST_P(ASTMatchersTest,
710 FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations) {
711 if (!GetParam().isCXX()) {
712 return;
713 }
714 EXPECT_TRUE(notMatches(
715 "void g(); template <typename T> void f(T t) {}"
716 "template <> void f(int t) { g(); }",
717 functionTemplateDecl(hasName("f"), hasDescendant(declRefExpr(to(
718 functionDecl(hasName("g"))))))));
719}
720
721TEST_P(ASTMatchersTest, ClassTemplateSpecializationDecl) {
722 if (!GetParam().isCXX()) {
723 return;
724 }
725 EXPECT_TRUE(matches("template<typename T> struct A {};"
726 "template<> struct A<int> {};",
727 classTemplateSpecializationDecl()));
728 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
729 classTemplateSpecializationDecl()));
730 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
731 classTemplateSpecializationDecl()));
732}
733
734TEST_P(ASTMatchersTest, DeclaratorDecl) {
735 EXPECT_TRUE(matches("int x;", declaratorDecl()));
736 EXPECT_TRUE(notMatches("struct A {};", declaratorDecl()));
737}
738
739TEST_P(ASTMatchersTest, DeclaratorDecl_CXX) {
740 if (!GetParam().isCXX()) {
741 return;
742 }
743 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
744}
745
746TEST_P(ASTMatchersTest, ParmVarDecl) {
747 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
748 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
749}
750
751TEST_P(ASTMatchersTest, StaticAssertDecl) {
752 if (!GetParam().isCXX11OrLater())
753 return;
754
755 EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
756 EXPECT_TRUE(
757 notMatches("constexpr bool staticassert(bool B, const char *M) "
758 "{ return true; };\n void f() { staticassert(true, \"\"); }",
759 staticAssertDecl()));
760}
761
762TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
763 if (!GetParam().isCXX()) {
764 return;
765 }
766
767 StatementMatcher Constructor = traverse(TK: TK_AsIs, InnerMatcher: cxxConstructExpr());
768
769 EXPECT_TRUE(
770 matches("class X { public: X(); }; void x() { X x; }", Constructor));
771 EXPECT_TRUE(matches("class X { public: X(); }; void x() { X x = X(); }",
772 Constructor));
773 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
774 Constructor));
775 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
776}
777
778TEST_P(ASTMatchersTest, Match_ConstructorInitializers) {
779 if (!GetParam().isCXX()) {
780 return;
781 }
782 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
783 cxxCtorInitializer(forField(hasName("i")))));
784}
785
786TEST_P(ASTMatchersTest, Matcher_ThisExpr) {
787 if (!GetParam().isCXX()) {
788 return;
789 }
790 EXPECT_TRUE(
791 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
792 EXPECT_TRUE(
793 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
794}
795
796TEST_P(ASTMatchersTest, Matcher_BindTemporaryExpression) {
797 if (!GetParam().isCXX()) {
798 return;
799 }
800
801 StatementMatcher TempExpression = traverse(TK: TK_AsIs, InnerMatcher: cxxBindTemporaryExpr());
802
803 StringRef ClassString = "class string { public: string(); ~string(); }; ";
804
805 EXPECT_TRUE(matches(
806 ClassString + "string GetStringByValue();"
807 "void FunctionTakesString(string s);"
808 "void run() { FunctionTakesString(GetStringByValue()); }",
809 TempExpression));
810
811 EXPECT_TRUE(notMatches(ClassString +
812 "string* GetStringPointer(); "
813 "void FunctionTakesStringPtr(string* s);"
814 "void run() {"
815 " string* s = GetStringPointer();"
816 " FunctionTakesStringPtr(GetStringPointer());"
817 " FunctionTakesStringPtr(s);"
818 "}",
819 TempExpression));
820
821 EXPECT_TRUE(notMatches("class no_dtor {};"
822 "no_dtor GetObjByValue();"
823 "void ConsumeObj(no_dtor param);"
824 "void run() { ConsumeObj(GetObjByValue()); }",
825 TempExpression));
826}
827
828TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14) {
829 if (GetParam().Language != Lang_CXX11 && GetParam().Language != Lang_CXX14) {
830 return;
831 }
832
833 StatementMatcher TempExpression =
834 traverse(TK: TK_AsIs, InnerMatcher: materializeTemporaryExpr());
835
836 EXPECT_TRUE(matches("class string { public: string(); }; "
837 "string GetStringByValue();"
838 "void FunctionTakesString(string s);"
839 "void run() { FunctionTakesString(GetStringByValue()); }",
840 TempExpression));
841}
842
843TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporary) {
844 if (!GetParam().isCXX()) {
845 return;
846 }
847
848 StringRef ClassString = "class string { public: string(); int length(); }; ";
849 StatementMatcher TempExpression =
850 traverse(TK: TK_AsIs, InnerMatcher: materializeTemporaryExpr());
851
852 EXPECT_TRUE(notMatches(ClassString +
853 "string* GetStringPointer(); "
854 "void FunctionTakesStringPtr(string* s);"
855 "void run() {"
856 " string* s = GetStringPointer();"
857 " FunctionTakesStringPtr(GetStringPointer());"
858 " FunctionTakesStringPtr(s);"
859 "}",
860 TempExpression));
861
862 EXPECT_TRUE(matches(ClassString +
863 "string GetStringByValue();"
864 "void run() { int k = GetStringByValue().length(); }",
865 TempExpression));
866
867 EXPECT_TRUE(notMatches(ClassString + "string GetStringByValue();"
868 "void run() { GetStringByValue(); }",
869 TempExpression));
870}
871
872TEST_P(ASTMatchersTest, Matcher_NewExpression) {
873 if (!GetParam().isCXX()) {
874 return;
875 }
876
877 StatementMatcher New = cxxNewExpr();
878
879 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
880 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X(); }", New));
881 EXPECT_TRUE(
882 matches("class X { public: X(int); }; void x() { new X(0); }", New));
883 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
884}
885
886TEST_P(ASTMatchersTest, Matcher_DeleteExpression) {
887 if (!GetParam().isCXX()) {
888 return;
889 }
890 EXPECT_TRUE(
891 matches("struct A {}; void f(A* a) { delete a; }", cxxDeleteExpr()));
892}
893
894TEST_P(ASTMatchersTest, Matcher_NoexceptExpression) {
895 if (!GetParam().isCXX11OrLater()) {
896 return;
897 }
898 StatementMatcher NoExcept = cxxNoexceptExpr();
899 EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept));
900 EXPECT_TRUE(
901 matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept));
902 EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept));
903 EXPECT_TRUE(notMatches("void foo() noexcept(0+1);", NoExcept));
904 EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept));
905}
906
907TEST_P(ASTMatchersTest, Matcher_DefaultArgument) {
908 if (!GetParam().isCXX()) {
909 return;
910 }
911 StatementMatcher Arg = cxxDefaultArgExpr();
912 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
913 EXPECT_TRUE(
914 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
915 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
916}
917
918TEST_P(ASTMatchersTest, StringLiteral) {
919 StatementMatcher Literal = stringLiteral();
920 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
921 // with escaped characters
922 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
923 // no matching -- though the data type is the same, there is no string literal
924 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
925}
926
927TEST_P(ASTMatchersTest, StringLiteral_CXX) {
928 if (!GetParam().isCXX()) {
929 return;
930 }
931 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", stringLiteral()));
932}
933
934TEST_P(ASTMatchersTest, CharacterLiteral) {
935 EXPECT_TRUE(matches("const char c = 'c';", characterLiteral()));
936 EXPECT_TRUE(notMatches("const char c = 0x1;", characterLiteral()));
937}
938
939TEST_P(ASTMatchersTest, CharacterLiteral_CXX) {
940 if (!GetParam().isCXX()) {
941 return;
942 }
943 // wide character
944 EXPECT_TRUE(matches("const char c = L'c';", characterLiteral()));
945 // wide character, Hex encoded, NOT MATCHED!
946 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", characterLiteral()));
947}
948
949TEST_P(ASTMatchersTest, IntegerLiteral) {
950 StatementMatcher HasIntLiteral = integerLiteral();
951 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
952 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
953 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
954 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
955
956 // Non-matching cases (character literals, float and double)
957 EXPECT_TRUE(notMatches("int i = L'a';",
958 HasIntLiteral)); // this is actually a character
959 // literal cast to int
960 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
961 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
962 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
963
964 // Negative integers.
965 EXPECT_TRUE(
966 matches("int i = -10;",
967 unaryOperator(hasOperatorName("-"),
968 hasUnaryOperand(integerLiteral(equals(10))))));
969}
970
971TEST_P(ASTMatchersTest, FloatLiteral) {
972 StatementMatcher HasFloatLiteral = floatLiteral();
973 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
974 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
975 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
976 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
977 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
978 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
979 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
980 EXPECT_TRUE(
981 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
982
983 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
984 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
985 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
986 EXPECT_TRUE(
987 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
988}
989
990TEST_P(ASTMatchersTest, CXXNullPtrLiteralExpr) {
991 if (!GetParam().isCXX11OrLater()) {
992 return;
993 }
994 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
995}
996
997TEST_P(ASTMatchersTest, ChooseExpr) {
998 EXPECT_TRUE(matches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
999 chooseExpr()));
1000}
1001
1002TEST_P(ASTMatchersTest, ConvertVectorExpr) {
1003 EXPECT_TRUE(matches(
1004 "typedef double vector4double __attribute__((__vector_size__(32)));"
1005 "typedef float vector4float __attribute__((__vector_size__(16)));"
1006 "vector4float vf;"
1007 "void f() { (void)__builtin_convertvector(vf, vector4double); }",
1008 convertVectorExpr()));
1009 EXPECT_TRUE(notMatches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
1010 convertVectorExpr()));
1011}
1012
1013TEST_P(ASTMatchersTest, GNUNullExpr) {
1014 if (!GetParam().isCXX()) {
1015 return;
1016 }
1017 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
1018}
1019
1020TEST_P(ASTMatchersTest, GenericSelectionExpr) {
1021 EXPECT_TRUE(matches("void f() { (void)_Generic(1, int: 1, float: 2.0); }",
1022 genericSelectionExpr()));
1023}
1024
1025TEST_P(ASTMatchersTest, AtomicExpr) {
1026 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
1027 atomicExpr()));
1028}
1029
1030TEST_P(ASTMatchersTest, Initializers_C99) {
1031 if (!GetParam().isC99OrLater()) {
1032 return;
1033 }
1034 EXPECT_TRUE(matches(
1035 "void foo() { struct point { double x; double y; };"
1036 " struct point ptarray[10] = "
1037 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1038 initListExpr(hasSyntacticForm(initListExpr(
1039 has(designatedInitExpr(designatorCountIs(2),
1040 hasDescendant(floatLiteral(equals(1.0))),
1041 hasDescendant(integerLiteral(equals(2))))),
1042 has(designatedInitExpr(designatorCountIs(2),
1043 hasDescendant(floatLiteral(equals(2.0))),
1044 hasDescendant(integerLiteral(equals(2))))),
1045 has(designatedInitExpr(
1046 designatorCountIs(2), hasDescendant(floatLiteral(equals(1.0))),
1047 hasDescendant(integerLiteral(equals(0))))))))));
1048}
1049
1050TEST_P(ASTMatchersTest, Initializers_CXX) {
1051 if (GetParam().Language != Lang_CXX03) {
1052 // FIXME: Make this test pass with other C++ standard versions.
1053 return;
1054 }
1055 EXPECT_TRUE(matches(
1056 "void foo() { struct point { double x; double y; };"
1057 " struct point ptarray[10] = "
1058 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1059 initListExpr(
1060 has(cxxConstructExpr(requiresZeroInitialization())),
1061 has(initListExpr(
1062 hasType(asString("struct point")), has(floatLiteral(equals(1.0))),
1063 has(implicitValueInitExpr(hasType(asString("double")))))),
1064 has(initListExpr(hasType(asString("struct point")),
1065 has(floatLiteral(equals(2.0))),
1066 has(floatLiteral(equals(1.0))))))));
1067}
1068
1069TEST_P(ASTMatchersTest, ParenListExpr) {
1070 if (!GetParam().isCXX()) {
1071 return;
1072 }
1073 EXPECT_TRUE(
1074 matches("template<typename T> class foo { void bar() { foo X(*this); } };"
1075 "template class foo<int>;",
1076 varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
1077}
1078
1079TEST_P(ASTMatchersTest, StmtExpr) {
1080 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
1081 varDecl(hasInitializer(stmtExpr()))));
1082}
1083
1084TEST_P(ASTMatchersTest, PredefinedExpr) {
1085 // __func__ expands as StringLiteral("foo")
1086 EXPECT_TRUE(matches("void foo() { __func__; }",
1087 predefinedExpr(hasType(asString("const char[4]")),
1088 has(stringLiteral()))));
1089}
1090
1091TEST_P(ASTMatchersTest, AsmStatement) {
1092 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1093}
1094
1095TEST_P(ASTMatchersTest, HasCondition) {
1096 if (!GetParam().isCXX()) {
1097 // FIXME: Add a test for `hasCondition()` that does not depend on C++.
1098 return;
1099 }
1100
1101 StatementMatcher Condition =
1102 ifStmt(hasCondition(InnerMatcher: cxxBoolLiteral(equals(Value: true))));
1103
1104 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1105 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1106 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1107 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1108 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1109}
1110
1111TEST_P(ASTMatchersTest, ConditionalOperator) {
1112 if (!GetParam().isCXX()) {
1113 // FIXME: Add a test for `conditionalOperator()` that does not depend on
1114 // C++.
1115 return;
1116 }
1117
1118 StatementMatcher Conditional =
1119 conditionalOperator(hasCondition(InnerMatcher: cxxBoolLiteral(equals(Value: true))),
1120 hasTrueExpression(InnerMatcher: cxxBoolLiteral(equals(Value: false))));
1121
1122 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
1123 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
1124 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
1125
1126 StatementMatcher ConditionalFalse =
1127 conditionalOperator(hasFalseExpression(InnerMatcher: cxxBoolLiteral(equals(Value: false))));
1128
1129 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1130 EXPECT_TRUE(
1131 notMatches("void x() { true ? false : true; }", ConditionalFalse));
1132
1133 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1134 EXPECT_TRUE(
1135 notMatches("void x() { true ? false : true; }", ConditionalFalse));
1136}
1137
1138TEST_P(ASTMatchersTest, BinaryConditionalOperator) {
1139 if (!GetParam().isCXX()) {
1140 // FIXME: This test should work in non-C++ language modes.
1141 return;
1142 }
1143
1144 StatementMatcher AlwaysOne = traverse(
1145 TK: TK_AsIs, InnerMatcher: binaryConditionalOperator(
1146 hasCondition(InnerMatcher: implicitCastExpr(has(opaqueValueExpr(
1147 hasSourceExpression(InnerMatcher: (integerLiteral(equals(Value: 1)))))))),
1148 hasFalseExpression(InnerMatcher: integerLiteral(equals(Value: 0)))));
1149
1150 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
1151
1152 StatementMatcher FourNotFive = binaryConditionalOperator(
1153 hasTrueExpression(
1154 InnerMatcher: opaqueValueExpr(hasSourceExpression(InnerMatcher: (integerLiteral(equals(Value: 4)))))),
1155 hasFalseExpression(InnerMatcher: integerLiteral(equals(Value: 5))));
1156
1157 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
1158}
1159
1160TEST_P(ASTMatchersTest, ArraySubscriptExpr) {
1161 EXPECT_TRUE(
1162 matches("int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr()));
1163 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", arraySubscriptExpr()));
1164}
1165
1166TEST_P(ASTMatchersTest, ForStmt) {
1167 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1168 EXPECT_TRUE(matches("void f() { if(1) for(;;); }", forStmt()));
1169}
1170
1171TEST_P(ASTMatchersTest, ForStmt_CXX11) {
1172 if (!GetParam().isCXX11OrLater()) {
1173 return;
1174 }
1175 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
1176 "void f() { for (auto &a : as); }",
1177 forStmt()));
1178}
1179
1180TEST_P(ASTMatchersTest, ForStmt_NoFalsePositives) {
1181 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1182 EXPECT_TRUE(notMatches("void f() { if(1); }", forStmt()));
1183}
1184
1185TEST_P(ASTMatchersTest, CompoundStatement) {
1186 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
1187 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
1188 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
1189}
1190
1191TEST_P(ASTMatchersTest, CompoundStatement_DoesNotMatchEmptyStruct) {
1192 if (!GetParam().isCXX()) {
1193 // FIXME: Add a similar test that does not depend on C++.
1194 return;
1195 }
1196 // It's not a compound statement just because there's "{}" in the source
1197 // text. This is an AST search, not grep.
1198 EXPECT_TRUE(notMatches("namespace n { struct S {}; }", compoundStmt()));
1199 EXPECT_TRUE(
1200 matches("namespace n { struct S { void f() {{}} }; }", compoundStmt()));
1201}
1202
1203TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts) {
1204 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
1205}
1206
1207TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts_CXX) {
1208 if (!GetParam().isCXX()) {
1209 return;
1210 }
1211 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);", castExpr()));
1212 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
1213 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
1214}
1215
1216TEST_P(ASTMatchersTest, CastExpression_MatchesImplicitCasts) {
1217 // This test creates an implicit cast from int to char.
1218 EXPECT_TRUE(matches("char c = 0;", traverse(TK_AsIs, castExpr())));
1219 // This test creates an implicit cast from lvalue to rvalue.
1220 EXPECT_TRUE(matches("void f() { char c = 0, d = c; }",
1221 traverse(TK_AsIs, castExpr())));
1222}
1223
1224TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts) {
1225 if (GetParam().Language == Lang_C89 || GetParam().Language == Lang_C99) {
1226 // This does have a cast in C
1227 EXPECT_TRUE(matches("char c = '0';", implicitCastExpr()));
1228 } else {
1229 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
1230 }
1231 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
1232 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
1233}
1234
1235TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts_CXX) {
1236 if (!GetParam().isCXX()) {
1237 return;
1238 }
1239 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
1240}
1241
1242TEST_P(ASTMatchersTest, CXXReinterpretCastExpr) {
1243 if (!GetParam().isCXX()) {
1244 return;
1245 }
1246 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1247 cxxReinterpretCastExpr()));
1248}
1249
1250TEST_P(ASTMatchersTest, CXXReinterpretCastExpr_DoesNotMatchOtherCasts) {
1251 if (!GetParam().isCXX()) {
1252 return;
1253 }
1254 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
1255 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1256 cxxReinterpretCastExpr()));
1257 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1258 cxxReinterpretCastExpr()));
1259 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1260 "B b;"
1261 "D* p = dynamic_cast<D*>(&b);",
1262 cxxReinterpretCastExpr()));
1263}
1264
1265TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_MatchesSimpleCase) {
1266 if (!GetParam().isCXX()) {
1267 return;
1268 }
1269 StringRef foo_class = "class Foo { public: Foo(const char*); };";
1270 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
1271 cxxFunctionalCastExpr()));
1272}
1273
1274TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_DoesNotMatchOtherCasts) {
1275 if (!GetParam().isCXX()) {
1276 return;
1277 }
1278 StringRef FooClass = "class Foo { public: Foo(const char*); };";
1279 EXPECT_TRUE(
1280 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
1281 cxxFunctionalCastExpr()));
1282 EXPECT_TRUE(notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
1283 cxxFunctionalCastExpr()));
1284}
1285
1286TEST_P(ASTMatchersTest, CXXDynamicCastExpr) {
1287 if (!GetParam().isCXX()) {
1288 return;
1289 }
1290 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1291 "B b;"
1292 "D* p = dynamic_cast<D*>(&b);",
1293 cxxDynamicCastExpr()));
1294}
1295
1296TEST_P(ASTMatchersTest, CXXStaticCastExpr_MatchesSimpleCase) {
1297 if (!GetParam().isCXX()) {
1298 return;
1299 }
1300 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", cxxStaticCastExpr()));
1301}
1302
1303TEST_P(ASTMatchersTest, CXXStaticCastExpr_DoesNotMatchOtherCasts) {
1304 if (!GetParam().isCXX()) {
1305 return;
1306 }
1307 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
1308 EXPECT_TRUE(
1309 notMatches("char q, *p = const_cast<char*>(&q);", cxxStaticCastExpr()));
1310 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1311 cxxStaticCastExpr()));
1312 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1313 "B b;"
1314 "D* p = dynamic_cast<D*>(&b);",
1315 cxxStaticCastExpr()));
1316}
1317
1318TEST_P(ASTMatchersTest, CStyleCastExpr_MatchesSimpleCase) {
1319 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
1320}
1321
1322TEST_P(ASTMatchersTest, CStyleCastExpr_DoesNotMatchOtherCasts) {
1323 if (!GetParam().isCXX()) {
1324 return;
1325 }
1326 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
1327 "char q, *r = const_cast<char*>(&q);"
1328 "void* s = reinterpret_cast<char*>(&s);"
1329 "struct B { virtual ~B() {} }; struct D : B {};"
1330 "B b;"
1331 "D* t = dynamic_cast<D*>(&b);",
1332 cStyleCastExpr()));
1333}
1334
1335TEST_P(ASTMatchersTest, ImplicitCastExpr_MatchesSimpleCase) {
1336 // This test creates an implicit const cast.
1337 EXPECT_TRUE(
1338 matches("void f() { int x = 0; const int y = x; }",
1339 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1340 // This test creates an implicit cast from int to char.
1341 EXPECT_TRUE(
1342 matches("char c = 0;",
1343 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1344 // This test creates an implicit array-to-pointer cast.
1345 EXPECT_TRUE(
1346 matches("int arr[6]; int *p = arr;",
1347 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1348}
1349
1350TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly) {
1351 // This test verifies that implicitCastExpr() matches exactly when implicit
1352 // casts are present, and that it ignores explicit and paren casts.
1353
1354 // These two test cases have no casts.
1355 EXPECT_TRUE(
1356 notMatches("int x = 0;", varDecl(hasInitializer(implicitCastExpr()))));
1357 EXPECT_TRUE(
1358 notMatches("int x = (0);", varDecl(hasInitializer(implicitCastExpr()))));
1359 EXPECT_TRUE(notMatches("void f() { int x = 0; double d = (double) x; }",
1360 varDecl(hasInitializer(implicitCastExpr()))));
1361}
1362
1363TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly_CXX) {
1364 if (!GetParam().isCXX()) {
1365 return;
1366 }
1367 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
1368 varDecl(hasInitializer(implicitCastExpr()))));
1369 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
1370 varDecl(hasInitializer(implicitCastExpr()))));
1371}
1372
1373TEST_P(ASTMatchersTest, Stmt_DoesNotMatchDeclarations) {
1374 EXPECT_TRUE(notMatches("struct X {};", stmt()));
1375}
1376
1377TEST_P(ASTMatchersTest, Stmt_MatchesCompoundStatments) {
1378 EXPECT_TRUE(matches("void x() {}", stmt()));
1379}
1380
1381TEST_P(ASTMatchersTest, DeclStmt_DoesNotMatchCompoundStatements) {
1382 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1383}
1384
1385TEST_P(ASTMatchersTest, DeclStmt_MatchesVariableDeclarationStatements) {
1386 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1387}
1388
1389TEST_P(ASTMatchersTest, ExprWithCleanups_MatchesExprWithCleanups) {
1390 if (!GetParam().isCXX()) {
1391 return;
1392 }
1393 EXPECT_TRUE(
1394 matches("struct Foo { ~Foo(); };"
1395 "const Foo f = Foo();",
1396 traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1397 EXPECT_FALSE(
1398 matches("struct Foo { }; Foo a;"
1399 "const Foo f = a;",
1400 traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1401}
1402
1403TEST_P(ASTMatchersTest, InitListExpr) {
1404 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1405 initListExpr(hasType(asString("int[2]")))));
1406 EXPECT_TRUE(matches("struct B { int x, y; }; struct B b = { 5, 6 };",
1407 initListExpr(hasType(recordDecl(hasName("B"))))));
1408 EXPECT_TRUE(
1409 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1410}
1411
1412TEST_P(ASTMatchersTest, InitListExpr_CXX) {
1413 if (!GetParam().isCXX()) {
1414 return;
1415 }
1416 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1417 "void f();"
1418 "S s[1] = { &f };",
1419 declRefExpr(to(functionDecl(hasName("f"))))));
1420}
1421
1422TEST_P(ASTMatchersTest,
1423 CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression) {
1424 if (!GetParam().isCXX11OrLater()) {
1425 return;
1426 }
1427 StringRef code = "namespace std {"
1428 "template <typename> class initializer_list {"
1429 " public: initializer_list() noexcept {}"
1430 "};"
1431 "}"
1432 "struct A {"
1433 " A(std::initializer_list<int>) {}"
1434 "};";
1435 EXPECT_TRUE(matches(
1436 code + "A a{0};",
1437 traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1438 hasDeclaration(cxxConstructorDecl(
1439 ofClass(hasName("A"))))))));
1440 EXPECT_TRUE(matches(
1441 code + "A a = {0};",
1442 traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1443 hasDeclaration(cxxConstructorDecl(
1444 ofClass(hasName("A"))))))));
1445
1446 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1447 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1448 cxxStdInitializerListExpr()));
1449}
1450
1451TEST_P(ASTMatchersTest, UsingDecl_MatchesUsingDeclarations) {
1452 if (!GetParam().isCXX()) {
1453 return;
1454 }
1455 EXPECT_TRUE(matches("namespace X { int x; } using X::x;", usingDecl()));
1456}
1457
1458TEST_P(ASTMatchersTest, UsingDecl_MatchesShadowUsingDelcarations) {
1459 if (!GetParam().isCXX()) {
1460 return;
1461 }
1462 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1463 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1464}
1465
1466TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesUsingEnumDeclarations) {
1467 if (!GetParam().isCXX20OrLater()) {
1468 return;
1469 }
1470 EXPECT_TRUE(
1471 matches("namespace X { enum x {}; } using enum X::x;", usingEnumDecl()));
1472}
1473
1474TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesShadowUsingDeclarations) {
1475 if (!GetParam().isCXX20OrLater()) {
1476 return;
1477 }
1478 EXPECT_TRUE(matches("namespace f { enum a {b}; } using enum f::a;",
1479 usingEnumDecl(hasAnyUsingShadowDecl(hasName("b")))));
1480}
1481
1482TEST_P(ASTMatchersTest, UsingDirectiveDecl_MatchesUsingNamespace) {
1483 if (!GetParam().isCXX()) {
1484 return;
1485 }
1486 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1487 usingDirectiveDecl()));
1488 EXPECT_FALSE(
1489 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1490}
1491
1492TEST_P(ASTMatchersTest, WhileStmt) {
1493 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1494 EXPECT_TRUE(matches("void x() { while(1); }", whileStmt()));
1495 EXPECT_TRUE(notMatches("void x() { do {} while(1); }", whileStmt()));
1496}
1497
1498TEST_P(ASTMatchersTest, DoStmt_MatchesDoLoops) {
1499 EXPECT_TRUE(matches("void x() { do {} while(1); }", doStmt()));
1500 EXPECT_TRUE(matches("void x() { do ; while(0); }", doStmt()));
1501}
1502
1503TEST_P(ASTMatchersTest, DoStmt_DoesNotMatchWhileLoops) {
1504 EXPECT_TRUE(notMatches("void x() { while(1) {} }", doStmt()));
1505}
1506
1507TEST_P(ASTMatchersTest, SwitchCase_MatchesCase) {
1508 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1509 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1510 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1511 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1512}
1513
1514TEST_P(ASTMatchersTest, SwitchCase_MatchesSwitch) {
1515 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1516 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1517 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1518 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1519}
1520
1521TEST_P(ASTMatchersTest, CxxExceptionHandling_SimpleCases) {
1522 if (!GetParam().isCXX()) {
1523 return;
1524 }
1525 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1526 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1527 EXPECT_TRUE(
1528 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1529 EXPECT_TRUE(
1530 matches("void foo() try { throw; } catch(int X) { }", cxxThrowExpr()));
1531 EXPECT_TRUE(
1532 matches("void foo() try { throw 5;} catch(int X) { }", cxxThrowExpr()));
1533 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1534 cxxCatchStmt(isCatchAll())));
1535 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1536 cxxCatchStmt(isCatchAll())));
1537 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1538 varDecl(isExceptionVariable())));
1539 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1540 varDecl(isExceptionVariable())));
1541}
1542
1543TEST_P(ASTMatchersTest, ParenExpr_SimpleCases) {
1544 EXPECT_TRUE(matches("int i = (3);", traverse(TK_AsIs, parenExpr())));
1545 EXPECT_TRUE(matches("int i = (3 + 7);", traverse(TK_AsIs, parenExpr())));
1546 EXPECT_TRUE(notMatches("int i = 3;", traverse(TK_AsIs, parenExpr())));
1547 EXPECT_TRUE(notMatches("int f() { return 1; }; void g() { int a = f(); }",
1548 traverse(TK_AsIs, parenExpr())));
1549}
1550
1551TEST_P(ASTMatchersTest, IgnoringParens) {
1552 EXPECT_FALSE(matches("const char* str = (\"my-string\");",
1553 traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1554 stringLiteral())))));
1555 EXPECT_TRUE(
1556 matches("const char* str = (\"my-string\");",
1557 traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1558 ignoringParens(stringLiteral()))))));
1559}
1560
1561TEST_P(ASTMatchersTest, QualType) {
1562 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1563}
1564
1565TEST_P(ASTMatchersTest, ConstantArrayType) {
1566 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1567 EXPECT_TRUE(notMatches("void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1568 constantArrayType(hasElementType(builtinType()))));
1569
1570 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1571 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1572 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1573}
1574
1575TEST_P(ASTMatchersTest, DependentSizedArrayType) {
1576 if (!GetParam().isCXX()) {
1577 return;
1578 }
1579 EXPECT_TRUE(
1580 matches("template <typename T, int Size> class array { T data[Size]; };",
1581 dependentSizedArrayType()));
1582 EXPECT_TRUE(
1583 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1584 dependentSizedArrayType()));
1585}
1586
1587TEST_P(ASTMatchersTest, DependentSizedExtVectorType) {
1588 if (!GetParam().isCXX()) {
1589 return;
1590 }
1591 EXPECT_TRUE(matches("template<typename T, int Size>"
1592 "class vector {"
1593 " typedef T __attribute__((ext_vector_type(Size))) type;"
1594 "};",
1595 dependentSizedExtVectorType()));
1596 EXPECT_TRUE(
1597 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1598 dependentSizedExtVectorType()));
1599}
1600
1601TEST_P(ASTMatchersTest, IncompleteArrayType) {
1602 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1603 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1604
1605 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1606 incompleteArrayType()));
1607}
1608
1609TEST_P(ASTMatchersTest, VariableArrayType) {
1610 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1611 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1612
1613 EXPECT_TRUE(matches("void f(int b) { int a[b]; }",
1614 variableArrayType(hasSizeExpr(ignoringImpCasts(
1615 declRefExpr(to(varDecl(hasName("b")))))))));
1616}
1617
1618TEST_P(ASTMatchersTest, AtomicType) {
1619 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1620 llvm::Triple::Win32) {
1621 // FIXME: Make this work for MSVC.
1622 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1623
1624 EXPECT_TRUE(
1625 matches("_Atomic(int) i;", atomicType(hasValueType(isInteger()))));
1626 EXPECT_TRUE(
1627 notMatches("_Atomic(float) f;", atomicType(hasValueType(isInteger()))));
1628 }
1629}
1630
1631TEST_P(ASTMatchersTest, AutoType) {
1632 if (!GetParam().isCXX11OrLater()) {
1633 return;
1634 }
1635 EXPECT_TRUE(matches("auto i = 2;", autoType()));
1636 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1637 autoType()));
1638
1639 EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1640 EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1641 varDecl(hasType(recordDecl(hasName("X"))))));
1642
1643 // FIXME: Matching against the type-as-written can't work here, because the
1644 // type as written was not deduced.
1645 // EXPECT_TRUE(matches("auto a = 1;",
1646 // autoType(hasDeducedType(isInteger()))));
1647 // EXPECT_TRUE(notMatches("auto b = 2.0;",
1648 // autoType(hasDeducedType(isInteger()))));
1649}
1650
1651TEST_P(ASTMatchersTest, DecltypeType) {
1652 if (!GetParam().isCXX11OrLater()) {
1653 return;
1654 }
1655 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1656 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1657 decltypeType(hasUnderlyingType(isInteger()))));
1658}
1659
1660TEST_P(ASTMatchersTest, FunctionType) {
1661 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1662 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1663}
1664
1665TEST_P(ASTMatchersTest, IgnoringParens_Type) {
1666 EXPECT_TRUE(
1667 notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1668 EXPECT_TRUE(matches("void (*fp)(void);",
1669 pointerType(pointee(ignoringParens(functionType())))));
1670}
1671
1672TEST_P(ASTMatchersTest, FunctionProtoType) {
1673 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1674 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1675 EXPECT_TRUE(matches("void f(void);", functionProtoType(parameterCountIs(0))));
1676}
1677
1678TEST_P(ASTMatchersTest, FunctionProtoType_C) {
1679 if (!GetParam().isC()) {
1680 return;
1681 }
1682 EXPECT_TRUE(notMatches("void f();", functionProtoType()));
1683}
1684
1685TEST_P(ASTMatchersTest, FunctionProtoType_CXX) {
1686 if (!GetParam().isCXX()) {
1687 return;
1688 }
1689 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1690}
1691
1692TEST_P(ASTMatchersTest, ParenType) {
1693 EXPECT_TRUE(
1694 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1695 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1696
1697 EXPECT_TRUE(matches(
1698 "int (*ptr_to_func)(int);",
1699 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1700 EXPECT_TRUE(notMatches(
1701 "int (*ptr_to_array)[4];",
1702 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1703}
1704
1705TEST_P(ASTMatchersTest, PointerType) {
1706 // FIXME: Reactive when these tests can be more specific (not matching
1707 // implicit code on certain platforms), likely when we have hasDescendant for
1708 // Types/TypeLocs.
1709 // EXPECT_TRUE(matchAndVerifyResultTrue(
1710 // "int* a;",
1711 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1712 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1713 // EXPECT_TRUE(matchAndVerifyResultTrue(
1714 // "int* a;",
1715 // pointerTypeLoc().bind("loc"),
1716 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1717 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(qualType())))));
1718 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(pointerType())))));
1719 EXPECT_TRUE(matches("int* b; int* * const a = &b;",
1720 loc(qualType(isConstQualified(), pointerType()))));
1721
1722 StringRef Fragment = "int *ptr;";
1723 EXPECT_TRUE(notMatches(Fragment,
1724 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1725 EXPECT_TRUE(notMatches(
1726 Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1727 EXPECT_TRUE(
1728 matches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1729 EXPECT_TRUE(
1730 notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1731}
1732
1733TEST_P(ASTMatchersTest, PointerType_CXX) {
1734 if (!GetParam().isCXX()) {
1735 return;
1736 }
1737 StringRef Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1738 EXPECT_TRUE(notMatches(Fragment,
1739 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1740 EXPECT_TRUE(
1741 matches(Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1742 EXPECT_TRUE(
1743 notMatches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1744 EXPECT_TRUE(
1745 notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1746 EXPECT_TRUE(notMatches(
1747 Fragment, varDecl(hasName("ptr"), hasType(lValueReferenceType()))));
1748 EXPECT_TRUE(notMatches(
1749 Fragment, varDecl(hasName("ptr"), hasType(rValueReferenceType()))));
1750
1751 Fragment = "int a; int &ref = a;";
1752 EXPECT_TRUE(notMatches(Fragment,
1753 varDecl(hasName("ref"), hasType(blockPointerType()))));
1754 EXPECT_TRUE(notMatches(
1755 Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1756 EXPECT_TRUE(
1757 notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1758 EXPECT_TRUE(
1759 matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1760 EXPECT_TRUE(matches(Fragment,
1761 varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1762 EXPECT_TRUE(notMatches(
1763 Fragment, varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1764}
1765
1766TEST_P(ASTMatchersTest, PointerType_CXX11) {
1767 if (!GetParam().isCXX11OrLater()) {
1768 return;
1769 }
1770 StringRef Fragment = "int &&ref = 2;";
1771 EXPECT_TRUE(notMatches(Fragment,
1772 varDecl(hasName("ref"), hasType(blockPointerType()))));
1773 EXPECT_TRUE(notMatches(
1774 Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1775 EXPECT_TRUE(
1776 notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1777 EXPECT_TRUE(
1778 matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1779 EXPECT_TRUE(notMatches(
1780 Fragment, varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1781 EXPECT_TRUE(matches(Fragment,
1782 varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1783}
1784
1785TEST_P(ASTMatchersTest, AutoRefTypes) {
1786 if (!GetParam().isCXX11OrLater()) {
1787 return;
1788 }
1789
1790 StringRef Fragment = "auto a = 1;"
1791 "auto b = a;"
1792 "auto &c = a;"
1793 "auto &&d = c;"
1794 "auto &&e = 2;";
1795 EXPECT_TRUE(
1796 notMatches(Fragment, varDecl(hasName("a"), hasType(referenceType()))));
1797 EXPECT_TRUE(
1798 notMatches(Fragment, varDecl(hasName("b"), hasType(referenceType()))));
1799 EXPECT_TRUE(
1800 matches(Fragment, varDecl(hasName("c"), hasType(referenceType()))));
1801 EXPECT_TRUE(
1802 matches(Fragment, varDecl(hasName("c"), hasType(lValueReferenceType()))));
1803 EXPECT_TRUE(notMatches(
1804 Fragment, varDecl(hasName("c"), hasType(rValueReferenceType()))));
1805 EXPECT_TRUE(
1806 matches(Fragment, varDecl(hasName("d"), hasType(referenceType()))));
1807 EXPECT_TRUE(
1808 matches(Fragment, varDecl(hasName("d"), hasType(lValueReferenceType()))));
1809 EXPECT_TRUE(notMatches(
1810 Fragment, varDecl(hasName("d"), hasType(rValueReferenceType()))));
1811 EXPECT_TRUE(
1812 matches(Fragment, varDecl(hasName("e"), hasType(referenceType()))));
1813 EXPECT_TRUE(notMatches(
1814 Fragment, varDecl(hasName("e"), hasType(lValueReferenceType()))));
1815 EXPECT_TRUE(
1816 matches(Fragment, varDecl(hasName("e"), hasType(rValueReferenceType()))));
1817}
1818
1819TEST_P(ASTMatchersTest, EnumType) {
1820 EXPECT_TRUE(
1821 matches("enum Color { Green }; enum Color color;", loc(enumType())));
1822}
1823
1824TEST_P(ASTMatchersTest, EnumType_CXX) {
1825 if (!GetParam().isCXX()) {
1826 return;
1827 }
1828 EXPECT_TRUE(matches("enum Color { Green }; Color color;", loc(enumType())));
1829}
1830
1831TEST_P(ASTMatchersTest, EnumType_CXX11) {
1832 if (!GetParam().isCXX11OrLater()) {
1833 return;
1834 }
1835 EXPECT_TRUE(
1836 matches("enum class Color { Green }; Color color;", loc(enumType())));
1837}
1838
1839TEST_P(ASTMatchersTest, PointerType_MatchesPointersToConstTypes) {
1840 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1841 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1842 EXPECT_TRUE(matches("int b; const int * a = &b;",
1843 loc(pointerType(pointee(builtinType())))));
1844 EXPECT_TRUE(matches("int b; const int * a = &b;",
1845 pointerType(pointee(builtinType()))));
1846}
1847
1848TEST_P(ASTMatchersTest, TypedefType) {
1849 EXPECT_TRUE(matches("typedef int X; X a;",
1850 varDecl(hasName("a"), hasType(elaboratedType(
1851 namesType(typedefType()))))));
1852}
1853
1854TEST_P(ASTMatchersTest, MacroQualifiedType) {
1855 EXPECT_TRUE(matches(
1856 R"(
1857 #define CDECL __attribute__((cdecl))
1858 typedef void (CDECL *X)();
1859 )",
1860 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1861 EXPECT_TRUE(notMatches(
1862 R"(
1863 typedef void (__attribute__((cdecl)) *Y)();
1864 )",
1865 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1866}
1867
1868TEST_P(ASTMatchersTest, TemplateSpecializationType) {
1869 if (!GetParam().isCXX()) {
1870 return;
1871 }
1872 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1873 templateSpecializationType()));
1874}
1875
1876TEST_P(ASTMatchersTest, DeducedTemplateSpecializationType) {
1877 if (!GetParam().isCXX17OrLater()) {
1878 return;
1879 }
1880 EXPECT_TRUE(
1881 matches("template <typename T> class A{ public: A(T) {} }; A a(1);",
1882 deducedTemplateSpecializationType()));
1883}
1884
1885TEST_P(ASTMatchersTest, RecordType) {
1886 EXPECT_TRUE(matches("struct S {}; struct S s;",
1887 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1888 EXPECT_TRUE(notMatches("int i;",
1889 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1890}
1891
1892TEST_P(ASTMatchersTest, RecordType_CXX) {
1893 if (!GetParam().isCXX()) {
1894 return;
1895 }
1896 EXPECT_TRUE(matches("class C {}; C c;", recordType()));
1897 EXPECT_TRUE(matches("struct S {}; S s;",
1898 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1899}
1900
1901TEST_P(ASTMatchersTest, ElaboratedType) {
1902 if (!GetParam().isCXX()) {
1903 // FIXME: Add a test for `elaboratedType()` that does not depend on C++.
1904 return;
1905 }
1906 EXPECT_TRUE(matches("namespace N {"
1907 " namespace M {"
1908 " class D {};"
1909 " }"
1910 "}"
1911 "N::M::D d;",
1912 elaboratedType()));
1913 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1914 EXPECT_TRUE(matches("class C {}; C c;", elaboratedType()));
1915}
1916
1917TEST_P(ASTMatchersTest, SubstTemplateTypeParmType) {
1918 if (!GetParam().isCXX()) {
1919 return;
1920 }
1921 StringRef code = "template <typename T>"
1922 "int F() {"
1923 " return 1 + T();"
1924 "}"
1925 "int i = F<int>();";
1926 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1927 expr(hasType(substTemplateTypeParmType()))))));
1928 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1929 expr(hasType(substTemplateTypeParmType()))))));
1930}
1931
1932TEST_P(ASTMatchersTest, NestedNameSpecifier) {
1933 if (!GetParam().isCXX()) {
1934 return;
1935 }
1936 EXPECT_TRUE(
1937 matches("namespace ns { struct A {}; } ns::A a;", nestedNameSpecifier()));
1938 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1939 nestedNameSpecifier()));
1940 EXPECT_TRUE(
1941 matches("struct A { void f(); }; void A::f() {}", nestedNameSpecifier()));
1942 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1943 nestedNameSpecifier()));
1944
1945 EXPECT_TRUE(matches("struct A { static void f() {} }; void g() { A::f(); }",
1946 nestedNameSpecifier()));
1947 EXPECT_TRUE(
1948 notMatches("struct A { static void f() {} }; void g(A* a) { a->f(); }",
1949 nestedNameSpecifier()));
1950}
1951
1952TEST_P(ASTMatchersTest, Attr) {
1953 // Windows adds some implicit attributes.
1954 bool AutomaticAttributes = StringRef(GetParam().Target).contains(Other: "win32");
1955 if (GetParam().isCXX11OrLater()) {
1956 EXPECT_TRUE(matches("struct [[clang::warn_unused_result]] F{};", attr()));
1957
1958 // Unknown attributes are not parsed into an AST node.
1959 if (!AutomaticAttributes) {
1960 EXPECT_TRUE(notMatches("int x [[unknownattr]];", attr()));
1961 }
1962 }
1963 if (GetParam().isCXX17OrLater()) {
1964 EXPECT_TRUE(matches("struct [[nodiscard]] F{};", attr()));
1965 }
1966 EXPECT_TRUE(matches("int x(int * __attribute__((nonnull)) );", attr()));
1967 if (!AutomaticAttributes) {
1968 EXPECT_TRUE(notMatches("struct F{}; int x(int *);", attr()));
1969 // Some known attributes are not parsed into an AST node.
1970 EXPECT_TRUE(notMatches("typedef int x __attribute__((ext_vector_type(1)));",
1971 attr()));
1972 }
1973}
1974
1975TEST_P(ASTMatchersTest, NullStmt) {
1976 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1977 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1978}
1979
1980TEST_P(ASTMatchersTest, NamespaceAliasDecl) {
1981 if (!GetParam().isCXX()) {
1982 return;
1983 }
1984 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1985 namespaceAliasDecl(hasName("alias"))));
1986}
1987
1988TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesTypes) {
1989 if (!GetParam().isCXX()) {
1990 return;
1991 }
1992 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1993 specifiesType(InnerMatcher: hasDeclaration(InnerMatcher: recordDecl(hasName(Name: "A")))));
1994 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1995 EXPECT_TRUE(
1996 matches("struct A { struct B { struct C {}; }; }; A::B::C c;", Matcher));
1997 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
1998}
1999
2000TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesNamespaceDecls) {
2001 if (!GetParam().isCXX()) {
2002 return;
2003 }
2004 NestedNameSpecifierMatcher Matcher =
2005 nestedNameSpecifier(specifiesNamespace(InnerMatcher: hasName(Name: "ns")));
2006 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
2007 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
2008 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
2009}
2010
2011TEST_P(ASTMatchersTest,
2012 NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes) {
2013 if (!GetParam().isCXX()) {
2014 return;
2015 }
2016 EXPECT_TRUE(matches(
2017 "struct A { struct B { struct C {}; }; }; A::B::C c;",
2018 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
2019 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
2020 nestedNameSpecifierLoc(hasPrefix(specifiesTypeLoc(
2021 loc(qualType(asString("struct A"))))))));
2022 EXPECT_TRUE(matches(
2023 "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
2024 nestedNameSpecifierLoc(hasPrefix(
2025 specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
2026}
2027
2028template <typename T>
2029class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
2030public:
2031 bool run(const BoundNodes *Nodes) override { return false; }
2032
2033 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
2034 const T *Node = Nodes->getNodeAs<T>("");
2035 return verify(*Nodes, *Context, Node);
2036 }
2037
2038 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
2039 // Use the original typed pointer to verify we can pass pointers to subtypes
2040 // to equalsNode.
2041 const T *TypedNode = cast<T>(Node);
2042 return selectFirst<T>(
2043 "", match(stmt(hasParent(
2044 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
2045 *Node, Context)) != nullptr;
2046 }
2047 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
2048 // Use the original typed pointer to verify we can pass pointers to subtypes
2049 // to equalsNode.
2050 const T *TypedNode = cast<T>(Node);
2051 return selectFirst<T>(
2052 "", match(decl(hasParent(
2053 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
2054 *Node, Context)) != nullptr;
2055 }
2056 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
2057 // Use the original typed pointer to verify we can pass pointers to subtypes
2058 // to equalsNode.
2059 const T *TypedNode = cast<T>(Node);
2060 const auto *Dec = Nodes.getNodeAs<FieldDecl>(ID: "decl");
2061 return selectFirst<T>(
2062 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
2063 hasType(type(equalsNode(TypedNode)).bind(""))))))),
2064 *Dec, Context)) != nullptr;
2065 }
2066};
2067
2068TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity) {
2069 EXPECT_TRUE(matchAndVerifyResultTrue(
2070 "void f() { if (1) if(1) {} }", ifStmt().bind(""),
2071 std::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
2072}
2073
2074TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity_Cxx) {
2075 if (!GetParam().isCXX()) {
2076 return;
2077 }
2078 EXPECT_TRUE(matchAndVerifyResultTrue(
2079 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
2080 std::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
2081 EXPECT_TRUE(matchAndVerifyResultTrue(
2082 "class X { class Y {} y; };",
2083 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
2084 std::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
2085}
2086
2087TEST_P(ASTMatchersTest, TypedefDecl) {
2088 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
2089 typedefDecl(hasName("typedefDeclTest"))));
2090}
2091
2092TEST_P(ASTMatchersTest, TypedefDecl_Cxx) {
2093 if (!GetParam().isCXX11OrLater()) {
2094 return;
2095 }
2096 EXPECT_TRUE(notMatches("using typedefDeclTest = int;",
2097 typedefDecl(hasName("typedefDeclTest"))));
2098}
2099
2100TEST_P(ASTMatchersTest, TypeAliasDecl) {
2101 EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
2102 typeAliasDecl(hasName("typeAliasTest"))));
2103}
2104
2105TEST_P(ASTMatchersTest, TypeAliasDecl_CXX) {
2106 if (!GetParam().isCXX11OrLater()) {
2107 return;
2108 }
2109 EXPECT_TRUE(matches("using typeAliasTest = int;",
2110 typeAliasDecl(hasName("typeAliasTest"))));
2111}
2112
2113TEST_P(ASTMatchersTest, TypedefNameDecl) {
2114 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
2115 typedefNameDecl(hasName("typedefNameDeclTest1"))));
2116}
2117
2118TEST_P(ASTMatchersTest, TypedefNameDecl_CXX) {
2119 if (!GetParam().isCXX11OrLater()) {
2120 return;
2121 }
2122 EXPECT_TRUE(matches("using typedefNameDeclTest = int;",
2123 typedefNameDecl(hasName("typedefNameDeclTest"))));
2124}
2125
2126TEST_P(ASTMatchersTest, TypeAliasTemplateDecl) {
2127 if (!GetParam().isCXX11OrLater()) {
2128 return;
2129 }
2130 StringRef Code = R"(
2131 template <typename T>
2132 class X { T t; };
2133
2134 template <typename T>
2135 using typeAliasTemplateDecl = X<T>;
2136
2137 using typeAliasDecl = X<int>;
2138 )";
2139 EXPECT_TRUE(
2140 matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
2141 EXPECT_TRUE(
2142 notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
2143}
2144
2145TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntVarDecl) {
2146 EXPECT_TRUE(matches("const int x = 0;",
2147 qualifiedTypeLoc(loc(asString("const int")))));
2148}
2149
2150TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntFunctionDecl) {
2151 EXPECT_TRUE(matches("const int f() { return 5; }",
2152 qualifiedTypeLoc(loc(asString("const int")))));
2153}
2154
2155TEST_P(ASTMatchersTest, QualifiedTypeLocTest_DoesNotBindToUnqualifiedVarDecl) {
2156 EXPECT_TRUE(notMatches("int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2157}
2158
2159TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstIntDecl) {
2160 EXPECT_TRUE(
2161 notMatches("const int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2162}
2163
2164TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstFloatDecl) {
2165 EXPECT_TRUE(
2166 notMatches("const float x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2167}
2168
2169TEST_P(ASTMatchersTest, PointerTypeLocTest_BindsToAnyPointerTypeLoc) {
2170 auto matcher = varDecl(hasName(Name: "x"), hasTypeLoc(Inner: pointerTypeLoc()));
2171 EXPECT_TRUE(matches("int* x;", matcher));
2172 EXPECT_TRUE(matches("float* x;", matcher));
2173 EXPECT_TRUE(matches("char* x;", matcher));
2174 EXPECT_TRUE(matches("void* x;", matcher));
2175}
2176
2177TEST_P(ASTMatchersTest, PointerTypeLocTest_DoesNotBindToNonPointerTypeLoc) {
2178 auto matcher = varDecl(hasName(Name: "x"), hasTypeLoc(Inner: pointerTypeLoc()));
2179 EXPECT_TRUE(notMatches("int x;", matcher));
2180 EXPECT_TRUE(notMatches("float x;", matcher));
2181 EXPECT_TRUE(notMatches("char x;", matcher));
2182}
2183
2184TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyReferenceTypeLoc) {
2185 if (!GetParam().isCXX()) {
2186 return;
2187 }
2188 auto matcher = varDecl(hasName(Name: "r"), hasTypeLoc(Inner: referenceTypeLoc()));
2189 EXPECT_TRUE(matches("int rr = 3; int& r = rr;", matcher));
2190 EXPECT_TRUE(matches("int rr = 3; auto& r = rr;", matcher));
2191 EXPECT_TRUE(matches("int rr = 3; const int& r = rr;", matcher));
2192 EXPECT_TRUE(matches("float rr = 3.0; float& r = rr;", matcher));
2193 EXPECT_TRUE(matches("char rr = 'a'; char& r = rr;", matcher));
2194}
2195
2196TEST_P(ASTMatchersTest, ReferenceTypeLocTest_DoesNotBindToNonReferenceTypeLoc) {
2197 auto matcher = varDecl(hasName(Name: "r"), hasTypeLoc(Inner: referenceTypeLoc()));
2198 EXPECT_TRUE(notMatches("int r;", matcher));
2199 EXPECT_TRUE(notMatches("int r = 3;", matcher));
2200 EXPECT_TRUE(notMatches("const int r = 3;", matcher));
2201 EXPECT_TRUE(notMatches("int* r;", matcher));
2202 EXPECT_TRUE(notMatches("float r;", matcher));
2203 EXPECT_TRUE(notMatches("char r;", matcher));
2204}
2205
2206TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyRvalueReferenceTypeLoc) {
2207 if (!GetParam().isCXX()) {
2208 return;
2209 }
2210 auto matcher = varDecl(hasName(Name: "r"), hasTypeLoc(Inner: referenceTypeLoc()));
2211 EXPECT_TRUE(matches("int&& r = 3;", matcher));
2212 EXPECT_TRUE(matches("auto&& r = 3;", matcher));
2213 EXPECT_TRUE(matches("float&& r = 3.0;", matcher));
2214}
2215
2216TEST_P(
2217 ASTMatchersTest,
2218 TemplateSpecializationTypeLocTest_BindsToTemplateSpecializationExplicitInstantiation) {
2219 if (!GetParam().isCXX()) {
2220 return;
2221 }
2222 EXPECT_TRUE(
2223 matches("template <typename T> class C {}; template class C<int>;",
2224 classTemplateSpecializationDecl(
2225 hasName("C"), hasTypeLoc(templateSpecializationTypeLoc()))));
2226}
2227
2228TEST_P(ASTMatchersTest,
2229 TemplateSpecializationTypeLocTest_BindsToVarDeclTemplateSpecialization) {
2230 if (!GetParam().isCXX()) {
2231 return;
2232 }
2233 EXPECT_TRUE(matches(
2234 "template <typename T> class C {}; C<char> var;",
2235 varDecl(hasName("var"), hasTypeLoc(elaboratedTypeLoc(hasNamedTypeLoc(
2236 templateSpecializationTypeLoc()))))));
2237}
2238
2239TEST_P(
2240 ASTMatchersTest,
2241 TemplateSpecializationTypeLocTest_DoesNotBindToNonTemplateSpecialization) {
2242 if (!GetParam().isCXX()) {
2243 return;
2244 }
2245 EXPECT_TRUE(notMatches(
2246 "class C {}; C var;",
2247 varDecl(hasName("var"), hasTypeLoc(templateSpecializationTypeLoc()))));
2248}
2249
2250TEST_P(ASTMatchersTest,
2251 ElaboratedTypeLocTest_BindsToElaboratedObjectDeclaration) {
2252 if (!GetParam().isCXX()) {
2253 return;
2254 }
2255 EXPECT_TRUE(matches("class C {}; class C c;",
2256 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2257}
2258
2259TEST_P(ASTMatchersTest,
2260 ElaboratedTypeLocTest_BindsToNamespaceElaboratedObjectDeclaration) {
2261 if (!GetParam().isCXX()) {
2262 return;
2263 }
2264 EXPECT_TRUE(matches("namespace N { class D {}; } N::D d;",
2265 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2266}
2267
2268TEST_P(ASTMatchersTest,
2269 ElaboratedTypeLocTest_BindsToElaboratedStructDeclaration) {
2270 EXPECT_TRUE(matches("struct s {}; struct s ss;",
2271 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2272}
2273
2274TEST_P(ASTMatchersTest,
2275 ElaboratedTypeLocTest_BindsToBareElaboratedObjectDeclaration) {
2276 if (!GetParam().isCXX()) {
2277 return;
2278 }
2279 EXPECT_TRUE(matches("class C {}; C c;",
2280 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2281}
2282
2283TEST_P(
2284 ASTMatchersTest,
2285 ElaboratedTypeLocTest_DoesNotBindToNamespaceNonElaboratedObjectDeclaration) {
2286 if (!GetParam().isCXX()) {
2287 return;
2288 }
2289 EXPECT_TRUE(matches("namespace N { class D {}; } using N::D; D d;",
2290 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2291}
2292
2293TEST_P(ASTMatchersTest,
2294 ElaboratedTypeLocTest_BindsToBareElaboratedStructDeclaration) {
2295 if (!GetParam().isCXX()) {
2296 return;
2297 }
2298 EXPECT_TRUE(matches("struct s {}; s ss;",
2299 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2300}
2301
2302TEST_P(ASTMatchersTest, LambdaCaptureTest) {
2303 if (!GetParam().isCXX11OrLater()) {
2304 return;
2305 }
2306 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2307 lambdaExpr(hasAnyCapture(lambdaCapture()))));
2308}
2309
2310TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfVarDecl) {
2311 if (!GetParam().isCXX11OrLater()) {
2312 return;
2313 }
2314 auto matcher = lambdaExpr(
2315 hasAnyCapture(InnerMatcher: lambdaCapture(capturesVar(InnerMatcher: varDecl(hasName(Name: "cc"))))));
2316 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2317 matcher));
2318 EXPECT_TRUE(matches("int main() { int cc; auto f = [&cc](){ return cc; }; }",
2319 matcher));
2320 EXPECT_TRUE(
2321 matches("int main() { int cc; auto f = [=](){ return cc; }; }", matcher));
2322 EXPECT_TRUE(
2323 matches("int main() { int cc; auto f = [&](){ return cc; }; }", matcher));
2324 EXPECT_TRUE(matches(
2325 "void f(int a) { int cc[a]; auto f = [&](){ return cc;}; }", matcher));
2326}
2327
2328TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureWithInitializer) {
2329 if (!GetParam().isCXX14OrLater()) {
2330 return;
2331 }
2332 auto matcher = lambdaExpr(hasAnyCapture(InnerMatcher: lambdaCapture(capturesVar(
2333 InnerMatcher: varDecl(hasName(Name: "cc"), hasInitializer(InnerMatcher: integerLiteral(equals(Value: 1))))))));
2334 EXPECT_TRUE(
2335 matches("int main() { auto lambda = [cc = 1] {return cc;}; }", matcher));
2336 EXPECT_TRUE(
2337 matches("int main() { int cc = 2; auto lambda = [cc = 1] {return cc;}; }",
2338 matcher));
2339}
2340
2341TEST_P(ASTMatchersTest, LambdaCaptureTest_DoesNotBindToCaptureOfVarDecl) {
2342 if (!GetParam().isCXX11OrLater()) {
2343 return;
2344 }
2345 auto matcher = lambdaExpr(
2346 hasAnyCapture(InnerMatcher: lambdaCapture(capturesVar(InnerMatcher: varDecl(hasName(Name: "cc"))))));
2347 EXPECT_FALSE(matches("int main() { auto f = [](){ return 5; }; }", matcher));
2348 EXPECT_FALSE(matches("int main() { int xx; auto f = [xx](){ return xx; }; }",
2349 matcher));
2350}
2351
2352TEST_P(ASTMatchersTest,
2353 LambdaCaptureTest_DoesNotBindToCaptureWithInitializerAndDifferentName) {
2354 if (!GetParam().isCXX14OrLater()) {
2355 return;
2356 }
2357 EXPECT_FALSE(matches(
2358 "int main() { auto lambda = [xx = 1] {return xx;}; }",
2359 lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(varDecl(
2360 hasName("cc"), hasInitializer(integerLiteral(equals(1))))))))));
2361}
2362
2363TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfReferenceType) {
2364 if (!GetParam().isCXX20OrLater()) {
2365 return;
2366 }
2367 auto matcher = lambdaExpr(hasAnyCapture(
2368 InnerMatcher: lambdaCapture(capturesVar(InnerMatcher: varDecl(hasType(InnerMatcher: referenceType()))))));
2369 EXPECT_TRUE(matches("template <class ...T> void f(T &...args) {"
2370 " [&...args = args] () mutable {"
2371 " }();"
2372 "}"
2373 "int main() {"
2374 " int a;"
2375 " f(a);"
2376 "}", matcher));
2377 EXPECT_FALSE(matches("template <class ...T> void f(T &...args) {"
2378 " [...args = args] () mutable {"
2379 " }();"
2380 "}"
2381 "int main() {"
2382 " int a;"
2383 " f(a);"
2384 "}", matcher));
2385}
2386
2387TEST_P(ASTMatchersTest, IsDerivedFromRecursion) {
2388 if (!GetParam().isCXX11OrLater())
2389 return;
2390
2391 // Check we don't crash on cycles in the traversal and inheritance hierarchy.
2392 // Clang will normally enforce there are no cycles, but matchers opted to
2393 // traverse primary template for dependent specializations, spuriously
2394 // creating the cycles.
2395 DeclarationMatcher matcher = cxxRecordDecl(isDerivedFrom(BaseName: "X"));
2396 EXPECT_TRUE(notMatches(R"cpp(
2397 template <typename T1, typename T2>
2398 struct M;
2399
2400 template <typename T1>
2401 struct M<T1, void> {};
2402
2403 template <typename T1, typename T2>
2404 struct L : M<T1, T2> {};
2405
2406 template <typename T1, typename T2>
2407 struct M : L<M<T1, T2>, M<T1, T2>> {};
2408 )cpp",
2409 matcher));
2410
2411 // Check the running time is not exponential. The number of subojects to
2412 // traverse grows as fibonacci numbers even though the number of bases to
2413 // traverse is quadratic.
2414 // The test will hang if implementation of matchers traverses all subojects.
2415 EXPECT_TRUE(notMatches(R"cpp(
2416 template <class T> struct A0 {};
2417 template <class T> struct A1 : A0<T> {};
2418 template <class T> struct A2 : A1<T>, A0<T> {};
2419 template <class T> struct A3 : A2<T>, A1<T> {};
2420 template <class T> struct A4 : A3<T>, A2<T> {};
2421 template <class T> struct A5 : A4<T>, A3<T> {};
2422 template <class T> struct A6 : A5<T>, A4<T> {};
2423 template <class T> struct A7 : A6<T>, A5<T> {};
2424 template <class T> struct A8 : A7<T>, A6<T> {};
2425 template <class T> struct A9 : A8<T>, A7<T> {};
2426 template <class T> struct A10 : A9<T>, A8<T> {};
2427 template <class T> struct A11 : A10<T>, A9<T> {};
2428 template <class T> struct A12 : A11<T>, A10<T> {};
2429 template <class T> struct A13 : A12<T>, A11<T> {};
2430 template <class T> struct A14 : A13<T>, A12<T> {};
2431 template <class T> struct A15 : A14<T>, A13<T> {};
2432 template <class T> struct A16 : A15<T>, A14<T> {};
2433 template <class T> struct A17 : A16<T>, A15<T> {};
2434 template <class T> struct A18 : A17<T>, A16<T> {};
2435 template <class T> struct A19 : A18<T>, A17<T> {};
2436 template <class T> struct A20 : A19<T>, A18<T> {};
2437 template <class T> struct A21 : A20<T>, A19<T> {};
2438 template <class T> struct A22 : A21<T>, A20<T> {};
2439 template <class T> struct A23 : A22<T>, A21<T> {};
2440 template <class T> struct A24 : A23<T>, A22<T> {};
2441 template <class T> struct A25 : A24<T>, A23<T> {};
2442 template <class T> struct A26 : A25<T>, A24<T> {};
2443 template <class T> struct A27 : A26<T>, A25<T> {};
2444 template <class T> struct A28 : A27<T>, A26<T> {};
2445 template <class T> struct A29 : A28<T>, A27<T> {};
2446 template <class T> struct A30 : A29<T>, A28<T> {};
2447 template <class T> struct A31 : A30<T>, A29<T> {};
2448 template <class T> struct A32 : A31<T>, A30<T> {};
2449 template <class T> struct A33 : A32<T>, A31<T> {};
2450 template <class T> struct A34 : A33<T>, A32<T> {};
2451 template <class T> struct A35 : A34<T>, A33<T> {};
2452 template <class T> struct A36 : A35<T>, A34<T> {};
2453 template <class T> struct A37 : A36<T>, A35<T> {};
2454 template <class T> struct A38 : A37<T>, A36<T> {};
2455 template <class T> struct A39 : A38<T>, A37<T> {};
2456 template <class T> struct A40 : A39<T>, A38<T> {};
2457)cpp",
2458 matcher));
2459}
2460
2461TEST(ASTMatchersTestObjC, ObjCMessageCalees) {
2462 StatementMatcher MessagingFoo =
2463 objcMessageExpr(callee(InnerMatcher: objcMethodDecl(hasName(Name: "foo"))));
2464
2465 EXPECT_TRUE(matchesObjC("@interface I"
2466 "+ (void)foo;"
2467 "@end\n"
2468 "int main() {"
2469 " [I foo];"
2470 "}",
2471 MessagingFoo));
2472 EXPECT_TRUE(notMatchesObjC("@interface I"
2473 "+ (void)foo;"
2474 "+ (void)bar;"
2475 "@end\n"
2476 "int main() {"
2477 " [I bar];"
2478 "}",
2479 MessagingFoo));
2480 EXPECT_TRUE(matchesObjC("@interface I"
2481 "- (void)foo;"
2482 "- (void)bar;"
2483 "@end\n"
2484 "int main() {"
2485 " I *i;"
2486 " [i foo];"
2487 "}",
2488 MessagingFoo));
2489 EXPECT_TRUE(notMatchesObjC("@interface I"
2490 "- (void)foo;"
2491 "- (void)bar;"
2492 "@end\n"
2493 "int main() {"
2494 " I *i;"
2495 " [i bar];"
2496 "}",
2497 MessagingFoo));
2498}
2499
2500TEST(ASTMatchersTestObjC, ObjCMessageExpr) {
2501 // Don't find ObjCMessageExpr where none are present.
2502 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
2503
2504 StringRef Objc1String = "@interface Str "
2505 " - (Str *)uppercaseString;"
2506 "@end "
2507 "@interface foo "
2508 "- (void)contents;"
2509 "- (void)meth:(Str *)text;"
2510 "@end "
2511 " "
2512 "@implementation foo "
2513 "- (void) meth:(Str *)text { "
2514 " [self contents];"
2515 " Str *up = [text uppercaseString];"
2516 "} "
2517 "@end ";
2518 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(anything())));
2519 EXPECT_TRUE(matchesObjC(Objc1String,
2520 objcMessageExpr(hasAnySelector({"contents", "meth:"}))
2521
2522 ));
2523 EXPECT_TRUE(
2524 matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"))));
2525 EXPECT_TRUE(matchesObjC(
2526 Objc1String, objcMessageExpr(hasAnySelector("contents", "contentsA"))));
2527 EXPECT_FALSE(matchesObjC(
2528 Objc1String, objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
2529 EXPECT_TRUE(
2530 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("cont*"))));
2531 EXPECT_FALSE(
2532 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("?cont*"))));
2533 EXPECT_TRUE(
2534 notMatchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2535 hasNullSelector())));
2536 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2537 hasUnarySelector())));
2538 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2539 numSelectorArgs(0))));
2540 EXPECT_TRUE(
2541 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("uppercase*"),
2542 argumentCountIs(0))));
2543}
2544
2545TEST(ASTMatchersTestObjC, ObjCStringLiteral) {
2546
2547 StringRef Objc1String = "@interface NSObject "
2548 "@end "
2549 "@interface NSString "
2550 "@end "
2551 "@interface Test : NSObject "
2552 "+ (void)someFunction:(NSString *)Desc; "
2553 "@end "
2554 "@implementation Test "
2555 "+ (void)someFunction:(NSString *)Desc { "
2556 " return; "
2557 "} "
2558 "- (void) foo { "
2559 " [Test someFunction:@\"Ola!\"]; "
2560 "}\n"
2561 "@end ";
2562 EXPECT_TRUE(matchesObjC(Objc1String, objcStringLiteral()));
2563}
2564
2565TEST(ASTMatchersTestObjC, ObjCDecls) {
2566 StringRef ObjCString = "@protocol Proto "
2567 "- (void)protoDidThing; "
2568 "@end "
2569 "@interface Thing "
2570 "@property int enabled; "
2571 "@end "
2572 "@interface Thing (ABC) "
2573 "- (void)abc_doThing; "
2574 "@end "
2575 "@implementation Thing "
2576 "{ id _ivar; } "
2577 "- (void)anything {} "
2578 "@end "
2579 "@implementation Thing (ABC) "
2580 "- (void)abc_doThing {} "
2581 "@end ";
2582
2583 EXPECT_TRUE(matchesObjC(ObjCString, objcProtocolDecl(hasName("Proto"))));
2584 EXPECT_TRUE(
2585 matchesObjC(ObjCString, objcImplementationDecl(hasName("Thing"))));
2586 EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryDecl(hasName("ABC"))));
2587 EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryImplDecl(hasName("ABC"))));
2588 EXPECT_TRUE(
2589 matchesObjC(ObjCString, objcMethodDecl(hasName("protoDidThing"))));
2590 EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("abc_doThing"))));
2591 EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("anything"))));
2592 EXPECT_TRUE(matchesObjC(ObjCString, objcIvarDecl(hasName("_ivar"))));
2593 EXPECT_TRUE(matchesObjC(ObjCString, objcPropertyDecl(hasName("enabled"))));
2594}
2595
2596TEST(ASTMatchersTestObjC, ObjCExceptionStmts) {
2597 StringRef ObjCString = "void f(id obj) {"
2598 " @try {"
2599 " @throw obj;"
2600 " } @catch (...) {"
2601 " } @finally {}"
2602 "}";
2603
2604 EXPECT_TRUE(matchesObjC(ObjCString, objcTryStmt()));
2605 EXPECT_TRUE(matchesObjC(ObjCString, objcThrowStmt()));
2606 EXPECT_TRUE(matchesObjC(ObjCString, objcCatchStmt()));
2607 EXPECT_TRUE(matchesObjC(ObjCString, objcFinallyStmt()));
2608}
2609
2610TEST(ASTMatchersTest, DecompositionDecl) {
2611 StringRef Code = R"cpp(
2612void foo()
2613{
2614 int arr[3];
2615 auto &[f, s, t] = arr;
2616
2617 f = 42;
2618}
2619 )cpp";
2620 EXPECT_TRUE(matchesConditionally(
2621 Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("f")))), true,
2622 {"-std=c++17"}));
2623 EXPECT_FALSE(matchesConditionally(
2624 Code, decompositionDecl(hasBinding(42, bindingDecl(hasName("f")))), true,
2625 {"-std=c++17"}));
2626 EXPECT_FALSE(matchesConditionally(
2627 Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("s")))), true,
2628 {"-std=c++17"}));
2629 EXPECT_TRUE(matchesConditionally(
2630 Code, decompositionDecl(hasBinding(1, bindingDecl(hasName("s")))), true,
2631 {"-std=c++17"}));
2632
2633 EXPECT_TRUE(matchesConditionally(
2634 Code,
2635 bindingDecl(decl().bind("self"), hasName("f"),
2636 forDecomposition(decompositionDecl(
2637 hasAnyBinding(bindingDecl(equalsBoundNode("self")))))),
2638 true, {"-std=c++17"}));
2639}
2640
2641TEST(ASTMatchersTestObjC, ObjCAutoreleasePoolStmt) {
2642 StringRef ObjCString = "void f() {"
2643 "@autoreleasepool {"
2644 " int x = 1;"
2645 "}"
2646 "}";
2647 EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
2648 StringRef ObjCStringNoPool = "void f() { int x = 1; }";
2649 EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
2650}
2651
2652TEST(ASTMatchersTestOpenMP, OMPExecutableDirective) {
2653 auto Matcher = stmt(ompExecutableDirective());
2654
2655 StringRef Source0 = R"(
2656void x() {
2657#pragma omp parallel
2658;
2659})";
2660 EXPECT_TRUE(matchesWithOpenMP(Source0, Matcher));
2661
2662 StringRef Source1 = R"(
2663void x() {
2664#pragma omp taskyield
2665;
2666})";
2667 EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2668
2669 StringRef Source2 = R"(
2670void x() {
2671;
2672})";
2673 EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
2674}
2675
2676TEST(ASTMatchersTestOpenMP, OMPDefaultClause) {
2677 auto Matcher = ompExecutableDirective(hasAnyClause(InnerMatcher: ompDefaultClause()));
2678
2679 StringRef Source0 = R"(
2680void x() {
2681;
2682})";
2683 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2684
2685 StringRef Source1 = R"(
2686void x() {
2687#pragma omp parallel
2688;
2689})";
2690 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2691
2692 StringRef Source2 = R"(
2693void x() {
2694#pragma omp parallel default(none)
2695;
2696})";
2697 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2698
2699 StringRef Source3 = R"(
2700void x() {
2701#pragma omp parallel default(shared)
2702;
2703})";
2704 EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2705
2706 StringRef Source4 = R"(
2707void x() {
2708#pragma omp parallel default(firstprivate)
2709;
2710})";
2711 EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
2712
2713 StringRef Source5 = R"(
2714void x(int x) {
2715#pragma omp parallel num_threads(x)
2716;
2717})";
2718 EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
2719}
2720
2721TEST(ASTMatchersTest, Finder_DynamicOnlyAcceptsSomeMatchers) {
2722 MatchFinder Finder;
2723 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
2724 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
2725 EXPECT_TRUE(
2726 Finder.addDynamicMatcher(constantArrayType(hasSize(42)), nullptr));
2727
2728 // Do not accept non-toplevel matchers.
2729 EXPECT_FALSE(Finder.addDynamicMatcher(isMain(), nullptr));
2730 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
2731}
2732
2733TEST(MatchFinderAPI, MatchesDynamic) {
2734 StringRef SourceCode = "struct A { void f() {} };";
2735 auto Matcher = functionDecl(isDefinition()).bind(ID: "method");
2736
2737 auto astUnit = tooling::buildASTFromCode(Code: SourceCode);
2738
2739 auto GlobalBoundNodes = matchDynamic(Matcher, Context&: astUnit->getASTContext());
2740
2741 EXPECT_EQ(GlobalBoundNodes.size(), 1u);
2742 EXPECT_EQ(GlobalBoundNodes[0].getMap().size(), 1u);
2743
2744 auto GlobalMethodNode = GlobalBoundNodes[0].getNodeAs<FunctionDecl>(ID: "method");
2745 EXPECT_TRUE(GlobalMethodNode != nullptr);
2746
2747 auto MethodBoundNodes =
2748 matchDynamic(Matcher, Node: *GlobalMethodNode, Context&: astUnit->getASTContext());
2749 EXPECT_EQ(MethodBoundNodes.size(), 1u);
2750 EXPECT_EQ(MethodBoundNodes[0].getMap().size(), 1u);
2751
2752 auto MethodNode = MethodBoundNodes[0].getNodeAs<FunctionDecl>(ID: "method");
2753 EXPECT_EQ(MethodNode, GlobalMethodNode);
2754}
2755
2756static std::vector<TestClangConfig> allTestClangConfigs() {
2757 std::vector<TestClangConfig> all_configs;
2758 for (TestLanguage lang : {Lang_C89, Lang_C99, Lang_CXX03, Lang_CXX11,
2759 Lang_CXX14, Lang_CXX17, Lang_CXX20, Lang_CXX23}) {
2760 TestClangConfig config;
2761 config.Language = lang;
2762
2763 // Use an unknown-unknown triple so we don't instantiate the full system
2764 // toolchain. On Linux, instantiating the toolchain involves stat'ing
2765 // large portions of /usr/lib, and this slows down not only this test, but
2766 // all other tests, via contention in the kernel.
2767 //
2768 // FIXME: This is a hack to work around the fact that there's no way to do
2769 // the equivalent of runToolOnCodeWithArgs without instantiating a full
2770 // Driver. We should consider having a function, at least for tests, that
2771 // invokes cc1.
2772 config.Target = "i386-unknown-unknown";
2773 all_configs.push_back(x: config);
2774
2775 // Windows target is interesting to test because it enables
2776 // `-fdelayed-template-parsing`.
2777 config.Target = "x86_64-pc-win32-msvc";
2778 all_configs.push_back(x: config);
2779 }
2780 return all_configs;
2781}
2782
2783INSTANTIATE_TEST_SUITE_P(ASTMatchersTests, ASTMatchersTest,
2784 testing::ValuesIn(allTestClangConfigs()));
2785
2786} // namespace ast_matchers
2787} // namespace clang
2788

source code of clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp