Debian Codegraph @

llvm-project/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

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