Debian Codegraph @

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