Debian Codegraph @

clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

raw
1 // unittests/ASTMatchers/ASTMatchersNarrowingTest.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, IsExpandedFromMacro_MatchesInFile) {
22 StringRef input = R"cc(
23 #define MY_MACRO(a) (4 + (a))
24 void Test() { MY_MACRO(4); }
25 )cc";
26 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
27 }
28
29 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesNested) {
30 StringRef input = R"cc(
31 #define MY_MACRO(a) (4 + (a))
32 #define WRAPPER(a) MY_MACRO(a)
33 void Test() { WRAPPER(4); }
34 )cc";
35 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
36 }
37
38 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesIntermediate) {
39 StringRef input = R"cc(
40 #define IMPL(a) (4 + (a))
41 #define MY_MACRO(a) IMPL(a)
42 #define WRAPPER(a) MY_MACRO(a)
43 void Test() { WRAPPER(4); }
44 )cc";
45 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
46 }
47
48 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesTransitive) {
49 StringRef input = R"cc(
50 #define MY_MACRO(a) (4 + (a))
51 #define WRAPPER(a) MY_MACRO(a)
52 void Test() { WRAPPER(4); }
53 )cc";
54 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("WRAPPER"))));
55 }
56
57 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesArgument) {
58 StringRef input = R"cc(
59 #define MY_MACRO(a) (4 + (a))
60 void Test() {
61 int x = 5;
62 MY_MACRO(x);
63 }
64 )cc";
65 EXPECT_TRUE(matches(input, declRefExpr(isExpandedFromMacro("MY_MACRO"))));
66 }
67
68 // Like IsExpandedFromMacro_MatchesArgument, but the argument is itself a
69 // macro.
70 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesArgumentMacroExpansion) {
71 StringRef input = R"cc(
72 #define MY_MACRO(a) (4 + (a))
73 #define IDENTITY(a) (a)
74 void Test() {
75 IDENTITY(MY_MACRO(2));
76 }
77 )cc";
78 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("IDENTITY"))));
79 }
80
81 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesWhenInArgument) {
82 StringRef input = R"cc(
83 #define MY_MACRO(a) (4 + (a))
84 #define IDENTITY(a) (a)
85 void Test() {
86 IDENTITY(MY_MACRO(2));
87 }
88 )cc";
89 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("MY_MACRO"))));
90 }
91
92 TEST_P(ASTMatchersTest, IsExpandedFromMacro_MatchesObjectMacro) {
93 StringRef input = R"cc(
94 #define PLUS (2 + 2)
95 void Test() {
96 PLUS;
97 }
98 )cc";
99 EXPECT_TRUE(matches(input, binaryOperator(isExpandedFromMacro("PLUS"))));
100 }
101
102 TEST(IsExpandedFromMacro, MatchesFromCommandLine) {
103 StringRef input = R"cc(
104 void Test() { FOUR_PLUS_FOUR; }
105 )cc";
106 EXPECT_TRUE(matchesConditionally(
107 input, binaryOperator(isExpandedFromMacro("FOUR_PLUS_FOUR")), true,
108 {"-std=c++11", "-DFOUR_PLUS_FOUR=4+4"}));
109 }
110
111 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesBeginOnly) {
112 StringRef input = R"cc(
113 #define ONE_PLUS 1+
114 void Test() { ONE_PLUS 4; }
115 )cc";
116 EXPECT_TRUE(
117 notMatches(input, binaryOperator(isExpandedFromMacro("ONE_PLUS"))));
118 }
119
120 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesEndOnly) {
121 StringRef input = R"cc(
122 #define PLUS_ONE +1
123 void Test() { 4 PLUS_ONE; }
124 )cc";
125 EXPECT_TRUE(
126 notMatches(input, binaryOperator(isExpandedFromMacro("PLUS_ONE"))));
127 }
128
129 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesDifferentMacro) {
130 StringRef input = R"cc(
131 #define MY_MACRO(a) (4 + (a))
132 void Test() { MY_MACRO(4); }
133 )cc";
134 EXPECT_TRUE(notMatches(input, binaryOperator(isExpandedFromMacro("OTHER"))));
135 }
136
137 TEST_P(ASTMatchersTest, IsExpandedFromMacro_NotMatchesDifferentInstances) {
138 StringRef input = R"cc(
139 #define FOUR 4
140 void Test() { FOUR + FOUR; }
141 )cc";
142 EXPECT_TRUE(notMatches(input, binaryOperator(isExpandedFromMacro("FOUR"))));
143 }
144
145 TEST(IsExpandedFromMacro, IsExpandedFromMacro_MatchesDecls) {
146 StringRef input = R"cc(
147 #define MY_MACRO(a) int i = a;
148 void Test() { MY_MACRO(4); }
149 )cc";
150 EXPECT_TRUE(matches(input, varDecl(isExpandedFromMacro("MY_MACRO"))));
151 }
152
153 TEST(IsExpandedFromMacro, IsExpandedFromMacro_MatchesTypelocs) {
154 StringRef input = R"cc(
155 #define MY_TYPE int
156 void Test() { MY_TYPE i = 4; }
157 )cc";
158 EXPECT_TRUE(matches(input, typeLoc(isExpandedFromMacro("MY_TYPE"))));
159 }
160
161 TEST_P(ASTMatchersTest, AllOf) {
162 const char Program[] = "struct T { };"
163 "int f(int, struct T*, int, int);"
164 "void g(int x) { struct T t; f(x, &t, 3, 4); }";
165 EXPECT_TRUE(matches(
166 Program, callExpr(allOf(callee(functionDecl(hasName("f"))),
167 hasArgument(0, declRefExpr(to(varDecl())))))));
168 EXPECT_TRUE(matches(
169 Program,
170 callExpr(
171 allOf(callee(functionDecl(hasName("f"))),
172 hasArgument(0, declRefExpr(to(varDecl()))),
173 hasArgument(1, hasType(pointsTo(recordDecl(hasName("T")))))))));
174 EXPECT_TRUE(matches(
175 Program, callExpr(allOf(
176 callee(functionDecl(hasName("f"))),
177 hasArgument(0, declRefExpr(to(varDecl()))),
178 hasArgument(1, hasType(pointsTo(recordDecl(hasName("T"))))),
179 hasArgument(2, integerLiteral(equals(3)))))));
180 EXPECT_TRUE(matches(
181 Program, callExpr(allOf(
182 callee(functionDecl(hasName("f"))),
183 hasArgument(0, declRefExpr(to(varDecl()))),
184 hasArgument(1, hasType(pointsTo(recordDecl(hasName("T"))))),
185 hasArgument(2, integerLiteral(equals(3))),
186 hasArgument(3, integerLiteral(equals(4)))))));
187 }
188
189 TEST_P(ASTMatchersTest, Has) {
190 if (!GetParam().isCXX()) {
191 // FIXME: Add a test for `has()` that does not depend on C++.
192 return;
193 }
194
195 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
196 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
197 EXPECT_TRUE(matches("class X {};", HasClassX));
198
199 DeclarationMatcher YHasClassX =
200 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
201 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
202 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
203 EXPECT_TRUE(notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
204 }
205
206 TEST_P(ASTMatchersTest, Has_RecursiveAllOf) {
207 if (!GetParam().isCXX()) {
208 return;
209 }
210
211 DeclarationMatcher Recursive =
212 recordDecl(has(recordDecl(has(recordDecl(hasName("X"))),
213 has(recordDecl(hasName("Y"))), hasName("Z"))),
214 has(recordDecl(has(recordDecl(hasName("A"))),
215 has(recordDecl(hasName("B"))), hasName("C"))),
216 hasName("F"));
217
218 EXPECT_TRUE(matches("class F {"
219 " class Z {"
220 " class X {};"
221 " class Y {};"
222 " };"
223 " class C {"
224 " class A {};"
225 " class B {};"
226 " };"
227 "};",
228 Recursive));
229
230 EXPECT_TRUE(matches("class F {"
231 " class Z {"
232 " class A {};"
233 " class X {};"
234 " class Y {};"
235 " };"
236 " class C {"
237 " class X {};"
238 " class A {};"
239 " class B {};"
240 " };"
241 "};",
242 Recursive));
243
244 EXPECT_TRUE(matches("class O1 {"
245 " class O2 {"
246 " class F {"
247 " class Z {"
248 " class A {};"
249 " class X {};"
250 " class Y {};"
251 " };"
252 " class C {"
253 " class X {};"
254 " class A {};"
255 " class B {};"
256 " };"
257 " };"
258 " };"
259 "};",
260 Recursive));
261 }
262
263 TEST_P(ASTMatchersTest, Has_RecursiveAnyOf) {
264 if (!GetParam().isCXX()) {
265 return;
266 }
267
268 DeclarationMatcher Recursive = recordDecl(
269 anyOf(has(recordDecl(anyOf(has(recordDecl(hasName("X"))),
270 has(recordDecl(hasName("Y"))), hasName("Z")))),
271 has(recordDecl(anyOf(hasName("C"), has(recordDecl(hasName("A"))),
272 has(recordDecl(hasName("B")))))),
273 hasName("F")));
274
275 EXPECT_TRUE(matches("class F {};", Recursive));
276 EXPECT_TRUE(matches("class Z {};", Recursive));
277 EXPECT_TRUE(matches("class C {};", Recursive));
278 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
279 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
280 EXPECT_TRUE(matches("class O1 { class O2 {"
281 " class M { class N { class B {}; }; }; "
282 "}; };",
283 Recursive));
284 }
285
286 TEST_P(ASTMatchersTest, Unless) {
287 if (!GetParam().isCXX()) {
288 // FIXME: Add a test for `unless()` that does not depend on C++.
289 return;
290 }
291
292 DeclarationMatcher NotClassX =
293 cxxRecordDecl(isDerivedFrom("Y"), unless(hasName("X")));
294 EXPECT_TRUE(notMatches("", NotClassX));
295 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
296 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
297 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
298 EXPECT_TRUE(
299 notMatches("class Y {}; class Z {}; class X : public Y {};", NotClassX));
300
301 DeclarationMatcher ClassXHasNotClassY =
302 recordDecl(hasName("X"), has(recordDecl(hasName("Z"))),
303 unless(has(recordDecl(hasName("Y")))));
304 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
305 EXPECT_TRUE(
306 notMatches("class X { class Y {}; class Z {}; };", ClassXHasNotClassY));
307
308 DeclarationMatcher NamedNotRecord =
309 namedDecl(hasName("Foo"), unless(recordDecl()));
310 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
311 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
312 }
313
314 TEST_P(ASTMatchersTest, HasCastKind) {
315 EXPECT_TRUE(
316 matches("char *p = 0;",
317 traverse(TK_AsIs,
318 varDecl(has(castExpr(hasCastKind(CK_NullToPointer)))))));
319 EXPECT_TRUE(notMatches(
320 "char *p = 0;",
321 traverse(TK_AsIs,
322 varDecl(has(castExpr(hasCastKind(CK_DerivedToBase)))))));
323 EXPECT_TRUE(matches("char *p = 0;",
324 traverse(TK_AsIs, varDecl(has(implicitCastExpr(
325 hasCastKind(CK_NullToPointer)))))));
326 }
327
328 TEST_P(ASTMatchersTest, HasDescendant) {
329 if (!GetParam().isCXX()) {
330 // FIXME: Add a test for `hasDescendant()` that does not depend on C++.
331 return;
332 }
333
334 DeclarationMatcher ZDescendantClassX =
335 recordDecl(hasDescendant(recordDecl(hasName("X"))), hasName("Z"));
336 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
337 EXPECT_TRUE(
338 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
339 EXPECT_TRUE(matches("class Z { class A { class Y { class X {}; }; }; };",
340 ZDescendantClassX));
341 EXPECT_TRUE(
342 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
343 ZDescendantClassX));
344 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
345
346 DeclarationMatcher ZDescendantClassXHasClassY = recordDecl(
347 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))), hasName("X"))),
348 hasName("Z"));
349 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
350 ZDescendantClassXHasClassY));
351 EXPECT_TRUE(
352 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
353 ZDescendantClassXHasClassY));
354 EXPECT_TRUE(notMatches("class Z {"
355 " class A {"
356 " class B {"
357 " class X {"
358 " class C {"
359 " class Y {};"
360 " };"
361 " };"
362 " }; "
363 " };"
364 "};",
365 ZDescendantClassXHasClassY));
366
367 DeclarationMatcher ZDescendantClassXDescendantClassY =
368 recordDecl(hasDescendant(recordDecl(
369 hasDescendant(recordDecl(hasName("Y"))), hasName("X"))),
370 hasName("Z"));
371 EXPECT_TRUE(
372 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
373 ZDescendantClassXDescendantClassY));
374 EXPECT_TRUE(matches("class Z {"
375 " class A {"
376 " class X {"
377 " class B {"
378 " class Y {};"
379 " };"
380 " class Y {};"
381 " };"
382 " };"
383 "};",
384 ZDescendantClassXDescendantClassY));
385 }
386
387 TEST_P(ASTMatchersTest, HasDescendant_Memoization) {
388 DeclarationMatcher CannotMemoize =
389 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
390 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
391 }
392
393 TEST_P(ASTMatchersTest, HasDescendant_MemoizationUsesRestrictKind) {
394 auto Name = hasName("i");
395 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
396 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
397 // Matching VD first should not make a cache hit for RD.
398 EXPECT_TRUE(notMatches("void f() { int i; }",
399 decl(hasDescendant(VD), hasDescendant(RD))));
400 EXPECT_TRUE(notMatches("void f() { int i; }",
401 decl(hasDescendant(RD), hasDescendant(VD))));
402 // Not matching RD first should not make a cache hit for VD either.
403 EXPECT_TRUE(matches("void f() { int i; }",
404 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
405 }
406
407 TEST_P(ASTMatchersTest, HasAncestor_Memoization) {
408 if (!GetParam().isCXX()) {
409 return;
410 }
411
412 // This triggers an hasAncestor with a TemplateArgument in the bound nodes.
413 // That node can't be memoized so we have to check for it before trying to put
414 // it on the cache.
415 DeclarationMatcher CannotMemoize = classTemplateSpecializationDecl(
416 hasAnyTemplateArgument(templateArgument().bind("targ")),
417 forEach(fieldDecl(hasAncestor(forStmt()))));
418
419 EXPECT_TRUE(notMatches("template <typename T> struct S;"
420 "template <> struct S<int>{ int i; int j; };",
421 CannotMemoize));
422 }
423
424 TEST_P(ASTMatchersTest, HasAttr) {
425 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
426 decl(hasAttr(clang::attr::WarnUnused))));
427 EXPECT_FALSE(matches("struct X {};", decl(hasAttr(clang::attr::WarnUnused))));
428 }
429
430 TEST_P(ASTMatchersTest, AnyOf) {
431 if (!GetParam().isCXX()) {
432 // FIXME: Add a test for `anyOf()` that does not depend on C++.
433 return;
434 }
435
436 DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
437 anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
438 EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
439 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
440 EXPECT_TRUE(
441 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
442 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
443
444 DeclarationMatcher XOrYOrZOrU =
445 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
446 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
447 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
448
449 DeclarationMatcher XOrYOrZOrUOrV = recordDecl(anyOf(
450 hasName("X"), hasName("Y"), hasName("Z"), hasName("U"), hasName("V")));
451 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
452 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
453 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
454 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
455 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
456 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
457
458 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
459 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
460 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
461 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
462
463 EXPECT_TRUE(
464 matches("void f() try { } catch (int) { } catch (...) { }",
465 cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
466 }
467
468 TEST_P(ASTMatchersTest, MapAnyOf) {
469 if (!GetParam().isCXX()) {
470 return;
471 }
472
473 if (GetParam().hasDelayedTemplateParsing()) {
474 return;
475 }
476
477 StringRef Code = R"cpp(
478 void F() {
479 if (true) {}
480 for ( ; false; ) {}
481 }
482 )cpp";
483
484 auto trueExpr = cxxBoolLiteral(equals(true));
485 auto falseExpr = cxxBoolLiteral(equals(false));
486
487 EXPECT_TRUE(matches(
488 Code, traverse(TK_IgnoreUnlessSpelledInSource,
489 mapAnyOf(ifStmt, forStmt).with(hasCondition(trueExpr)))));
490 EXPECT_TRUE(matches(
491 Code, traverse(TK_IgnoreUnlessSpelledInSource,
492 mapAnyOf(ifStmt, forStmt).with(hasCondition(falseExpr)))));
493
494 EXPECT_TRUE(
495 matches(Code, cxxBoolLiteral(equals(true),
496 hasAncestor(mapAnyOf(ifStmt, forStmt)))));
497
498 EXPECT_TRUE(
499 matches(Code, cxxBoolLiteral(equals(false),
500 hasAncestor(mapAnyOf(ifStmt, forStmt)))));
501
502 EXPECT_TRUE(
503 notMatches(Code, floatLiteral(hasAncestor(mapAnyOf(ifStmt, forStmt)))));
504
505 Code = R"cpp(
506 void func(bool b) {}
507 struct S {
508 S(bool b) {}
509 };
510 void F() {
511 func(false);
512 S s(true);
513 }
514 )cpp";
515 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
516 mapAnyOf(callExpr, cxxConstructExpr)
517 .with(hasArgument(0, trueExpr)))));
518 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
519 mapAnyOf(callExpr, cxxConstructExpr)
520 .with(hasArgument(0, falseExpr)))));
521
522 EXPECT_TRUE(
523 matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
524 mapAnyOf(callExpr, cxxConstructExpr)
525 .with(hasArgument(0, expr()),
526 hasDeclaration(functionDecl())))));
527
528 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
529 mapAnyOf(callExpr, cxxConstructExpr))));
530
531 EXPECT_TRUE(matches(
532 Code, traverse(TK_IgnoreUnlessSpelledInSource,
533 mapAnyOf(callExpr, cxxConstructExpr).bind("call"))));
534
535 Code = R"cpp(
536 struct HasOpNeqMem
537 {
538 bool operator!=(const HasOpNeqMem& other) const
539 {
540 return true;
541 }
542 };
543 struct HasOpFree
544 {
545 };
546 bool operator!=(const HasOpFree& lhs, const HasOpFree& rhs)
547 {
548 return true;
549 }
550
551 void binop()
552 {
553 int s1;
554 int s2;
555 if (s1 != s2)
556 return;
557 }
558
559 void opMem()
560 {
561 HasOpNeqMem s1;
562 HasOpNeqMem s2;
563 if (s1 != s2)
564 return;
565 }
566
567 void opFree()
568 {
569 HasOpFree s1;
570 HasOpFree s2;
571 if (s1 != s2)
572 return;
573 }
574
575 template<typename T>
576 void templ()
577 {
578 T s1;
579 T s2;
580 if (s1 != s2)
581 return;
582 }
583 )cpp";
584
585 EXPECT_TRUE(matches(
586 Code,
587 traverse(TK_IgnoreUnlessSpelledInSource,
588 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
589 .with(hasOperatorName("!="),
590 forFunction(functionDecl(hasName("binop"))),
591 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
592 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
593
594 EXPECT_TRUE(matches(
595 Code,
596 traverse(TK_IgnoreUnlessSpelledInSource,
597 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
598 .with(hasOperatorName("!="),
599 forFunction(functionDecl(hasName("opMem"))),
600 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
601 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
602
603 EXPECT_TRUE(matches(
604 Code,
605 traverse(TK_IgnoreUnlessSpelledInSource,
606 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
607 .with(hasOperatorName("!="),
608 forFunction(functionDecl(hasName("opFree"))),
609 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
610 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
611
612 EXPECT_TRUE(matches(
613 Code, traverse(TK_IgnoreUnlessSpelledInSource,
614 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
615 .with(hasOperatorName("!="),
616 forFunction(functionDecl(hasName("binop"))),
617 hasEitherOperand(
618 declRefExpr(to(varDecl(hasName("s1"))))),
619 hasEitherOperand(
620 declRefExpr(to(varDecl(hasName("s2")))))))));
621
622 EXPECT_TRUE(matches(
623 Code, traverse(TK_IgnoreUnlessSpelledInSource,
624 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
625 .with(hasOperatorName("!="),
626 forFunction(functionDecl(hasName("opMem"))),
627 hasEitherOperand(
628 declRefExpr(to(varDecl(hasName("s1"))))),
629 hasEitherOperand(
630 declRefExpr(to(varDecl(hasName("s2")))))))));
631
632 EXPECT_TRUE(matches(
633 Code, traverse(TK_IgnoreUnlessSpelledInSource,
634 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
635 .with(hasOperatorName("!="),
636 forFunction(functionDecl(hasName("opFree"))),
637 hasEitherOperand(
638 declRefExpr(to(varDecl(hasName("s1"))))),
639 hasEitherOperand(
640 declRefExpr(to(varDecl(hasName("s2")))))))));
641
642 EXPECT_TRUE(matches(
643 Code,
644 traverse(
645 TK_IgnoreUnlessSpelledInSource,
646 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
647 .with(hasOperatorName("!="),
648 forFunction(functionDecl(hasName("binop"))),
649 hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
650 declRefExpr(to(varDecl(hasName("s2"))))),
651 hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
652 declRefExpr(to(varDecl(hasName("s1")))))))));
653
654 EXPECT_TRUE(matches(
655 Code,
656 traverse(
657 TK_IgnoreUnlessSpelledInSource,
658 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
659 .with(hasOperatorName("!="),
660 forFunction(functionDecl(hasName("opMem"))),
661 hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
662 declRefExpr(to(varDecl(hasName("s2"))))),
663 hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
664 declRefExpr(to(varDecl(hasName("s1")))))))));
665
666 EXPECT_TRUE(matches(
667 Code,
668 traverse(
669 TK_IgnoreUnlessSpelledInSource,
670 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
671 .with(hasOperatorName("!="),
672 forFunction(functionDecl(hasName("opFree"))),
673 hasOperands(declRefExpr(to(varDecl(hasName("s1")))),
674 declRefExpr(to(varDecl(hasName("s2"))))),
675 hasOperands(declRefExpr(to(varDecl(hasName("s2")))),
676 declRefExpr(to(varDecl(hasName("s1")))))))));
677
678 EXPECT_TRUE(matches(
679 Code, traverse(TK_IgnoreUnlessSpelledInSource,
680 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
681 .with(hasAnyOperatorName("==", "!="),
682 forFunction(functionDecl(hasName("binop")))))));
683
684 EXPECT_TRUE(matches(
685 Code, traverse(TK_IgnoreUnlessSpelledInSource,
686 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
687 .with(hasAnyOperatorName("==", "!="),
688 forFunction(functionDecl(hasName("opMem")))))));
689
690 EXPECT_TRUE(matches(
691 Code, traverse(TK_IgnoreUnlessSpelledInSource,
692 mapAnyOf(binaryOperator, cxxOperatorCallExpr)
693 .with(hasAnyOperatorName("==", "!="),
694 forFunction(functionDecl(hasName("opFree")))))));
695
696 EXPECT_TRUE(matches(
697 Code, traverse(TK_IgnoreUnlessSpelledInSource,
698 binaryOperation(
699 hasOperatorName("!="),
700 forFunction(functionDecl(hasName("binop"))),
701 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
702 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
703
704 EXPECT_TRUE(matches(
705 Code, traverse(TK_IgnoreUnlessSpelledInSource,
706 binaryOperation(
707 hasOperatorName("!="),
708 forFunction(functionDecl(hasName("opMem"))),
709 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
710 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
711
712 EXPECT_TRUE(matches(
713 Code, traverse(TK_IgnoreUnlessSpelledInSource,
714 binaryOperation(
715 hasOperatorName("!="),
716 forFunction(functionDecl(hasName("opFree"))),
717 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
718 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
719
720 EXPECT_TRUE(matches(
721 Code, traverse(TK_IgnoreUnlessSpelledInSource,
722 binaryOperation(
723 hasOperatorName("!="),
724 forFunction(functionDecl(hasName("templ"))),
725 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
726 hasRHS(declRefExpr(to(varDecl(hasName("s2")))))))));
727
728 Code = R"cpp(
729 struct HasOpEq
730 {
731 bool operator==(const HasOpEq &) const;
732 };
733
734 void inverse()
735 {
736 HasOpEq s1;
737 HasOpEq s2;
738 if (s1 != s2)
739 return;
740 }
741
742 namespace std {
743 struct strong_ordering {
744 int n;
745 constexpr operator int() const { return n; }
746 static const strong_ordering equal, greater, less;
747 };
748 constexpr strong_ordering strong_ordering::equal = {0};
749 constexpr strong_ordering strong_ordering::greater = {1};
750 constexpr strong_ordering strong_ordering::less = {-1};
751 }
752
753 struct HasSpaceshipMem {
754 int a;
755 constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
756 };
757
758 void rewritten()
759 {
760 HasSpaceshipMem s1;
761 HasSpaceshipMem s2;
762 if (s1 != s2)
763 return;
764 }
765 )cpp";
766
767 EXPECT_TRUE(matchesConditionally(
768 Code,
769 traverse(
770 TK_IgnoreUnlessSpelledInSource,
771 binaryOperation(hasOperatorName("!="),
772 forFunction(functionDecl(hasName("inverse"))),
773 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
774 hasRHS(declRefExpr(to(varDecl(hasName("s2"))))))),
775 true, {"-std=c++20"}));
776
777 EXPECT_TRUE(matchesConditionally(
778 Code,
779 traverse(
780 TK_IgnoreUnlessSpelledInSource,
781 binaryOperation(hasOperatorName("!="),
782 forFunction(functionDecl(hasName("rewritten"))),
783 hasLHS(declRefExpr(to(varDecl(hasName("s1"))))),
784 hasRHS(declRefExpr(to(varDecl(hasName("s2"))))))),
785 true, {"-std=c++20"}));
786
787 Code = R"cpp(
788 struct HasOpBangMem
789 {
790 bool operator!() const
791 {
792 return false;
793 }
794 };
795 struct HasOpBangFree
796 {
797 };
798 bool operator!(HasOpBangFree const&)
799 {
800 return false;
801 }
802
803 void unop()
804 {
805 int s1;
806 if (!s1)
807 return;
808 }
809
810 void opMem()
811 {
812 HasOpBangMem s1;
813 if (!s1)
814 return;
815 }
816
817 void opFree()
818 {
819 HasOpBangFree s1;
820 if (!s1)
821 return;
822 }
823 )cpp";
824
825 EXPECT_TRUE(matches(
826 Code, traverse(TK_IgnoreUnlessSpelledInSource,
827 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
828 .with(hasOperatorName("!"),
829 forFunction(functionDecl(hasName("unop"))),
830 hasUnaryOperand(
831 declRefExpr(to(varDecl(hasName("s1")))))))));
832
833 EXPECT_TRUE(matches(
834 Code, traverse(TK_IgnoreUnlessSpelledInSource,
835 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
836 .with(hasOperatorName("!"),
837 forFunction(functionDecl(hasName("opMem"))),
838 hasUnaryOperand(
839 declRefExpr(to(varDecl(hasName("s1")))))))));
840
841 EXPECT_TRUE(matches(
842 Code, traverse(TK_IgnoreUnlessSpelledInSource,
843 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
844 .with(hasOperatorName("!"),
845 forFunction(functionDecl(hasName("opFree"))),
846 hasUnaryOperand(
847 declRefExpr(to(varDecl(hasName("s1")))))))));
848
849 EXPECT_TRUE(matches(
850 Code, traverse(TK_IgnoreUnlessSpelledInSource,
851 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
852 .with(hasAnyOperatorName("+", "!"),
853 forFunction(functionDecl(hasName("unop")))))));
854
855 EXPECT_TRUE(matches(
856 Code, traverse(TK_IgnoreUnlessSpelledInSource,
857 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
858 .with(hasAnyOperatorName("+", "!"),
859 forFunction(functionDecl(hasName("opMem")))))));
860
861 EXPECT_TRUE(matches(
862 Code, traverse(TK_IgnoreUnlessSpelledInSource,
863 mapAnyOf(unaryOperator, cxxOperatorCallExpr)
864 .with(hasAnyOperatorName("+", "!"),
865 forFunction(functionDecl(hasName("opFree")))))));
866
867 Code = R"cpp(
868 struct ConstructorTakesInt
869 {
870 ConstructorTakesInt(int i) {}
871 };
872
873 void callTakesInt(int i)
874 {
875
876 }
877
878 void doCall()
879 {
880 callTakesInt(42);
881 }
882
883 void doConstruct()
884 {
885 ConstructorTakesInt cti(42);
886 }
887 )cpp";
888
889 EXPECT_TRUE(matches(
890 Code, traverse(TK_IgnoreUnlessSpelledInSource,
891 invocation(forFunction(functionDecl(hasName("doCall"))),
892 hasArgument(0, integerLiteral(equals(42))),
893 hasAnyArgument(integerLiteral(equals(42))),
894 forEachArgumentWithParam(
895 integerLiteral(equals(42)),
896 parmVarDecl(hasName("i")))))));
897
898 EXPECT_TRUE(matches(
899 Code,
900 traverse(
901 TK_IgnoreUnlessSpelledInSource,
902 invocation(forFunction(functionDecl(hasName("doConstruct"))),
903 hasArgument(0, integerLiteral(equals(42))),
904 hasAnyArgument(integerLiteral(equals(42))),
905 forEachArgumentWithParam(integerLiteral(equals(42)),
906 parmVarDecl(hasName("i")))))));
907 }
908
909 TEST_P(ASTMatchersTest, IsDerivedFrom) {
910 if (!GetParam().isCXX()) {
911 return;
912 }
913
914 DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
915
916 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
917 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
918 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
919 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
920 EXPECT_TRUE(notMatches("", IsDerivedFromX));
921 EXPECT_TRUE(matches("class X {}; template<int N> class Y : Y<N-1>, X {};",
922 IsDerivedFromX));
923 EXPECT_TRUE(matches("class X {}; template<int N> class Y : X, Y<N-1> {};",
924 IsDerivedFromX));
925
926 DeclarationMatcher IsZDerivedFromX =
927 cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
928 EXPECT_TRUE(matches("class X {};"
929 "template<int N> class Y : Y<N-1> {};"
930 "template<> class Y<0> : X {};"
931 "class Z : Y<1> {};",
932 IsZDerivedFromX));
933
934 DeclarationMatcher IsDirectlyDerivedFromX =
935 cxxRecordDecl(isDirectlyDerivedFrom("X"));
936
937 EXPECT_TRUE(
938 matches("class X {}; class Y : public X {};", IsDirectlyDerivedFromX));
939 EXPECT_TRUE(notMatches("class X {};", IsDirectlyDerivedFromX));
940 EXPECT_TRUE(notMatches("class X;", IsDirectlyDerivedFromX));
941 EXPECT_TRUE(notMatches("class Y;", IsDirectlyDerivedFromX));
942 EXPECT_TRUE(notMatches("", IsDirectlyDerivedFromX));
943
944 DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
945
946 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
947 EXPECT_TRUE(matches("class X {};", IsAX));
948 EXPECT_TRUE(matches("class X;", IsAX));
949 EXPECT_TRUE(notMatches("class Y;", IsAX));
950 EXPECT_TRUE(notMatches("", IsAX));
951
952 DeclarationMatcher ZIsDerivedFromX =
953 cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
954 DeclarationMatcher ZIsDirectlyDerivedFromX =
955 cxxRecordDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
956 EXPECT_TRUE(
957 matches("class X {}; class Y : public X {}; class Z : public Y {};",
958 ZIsDerivedFromX));
959 EXPECT_TRUE(
960 notMatches("class X {}; class Y : public X {}; class Z : public Y {};",
961 ZIsDirectlyDerivedFromX));
962 EXPECT_TRUE(matches("class X {};"
963 "template<class T> class Y : public X {};"
964 "class Z : public Y<int> {};",
965 ZIsDerivedFromX));
966 EXPECT_TRUE(notMatches("class X {};"
967 "template<class T> class Y : public X {};"
968 "class Z : public Y<int> {};",
969 ZIsDirectlyDerivedFromX));
970 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
971 ZIsDerivedFromX));
972 EXPECT_TRUE(matches("template<class T> class X {}; "
973 "template<class T> class Z : public X<T> {};",
974 ZIsDerivedFromX));
975 EXPECT_TRUE(matches("template<class T, class U=T> class X {}; "
976 "template<class T> class Z : public X<T> {};",
977 ZIsDerivedFromX));
978 EXPECT_TRUE(
979 notMatches("template<class X> class A { class Z : public X {}; };",
980 ZIsDerivedFromX));
981 EXPECT_TRUE(
982 matches("template<class X> class A { public: class Z : public X {}; }; "
983 "class X{}; void y() { A<X>::Z z; }",
984 ZIsDerivedFromX));
985 EXPECT_TRUE(
986 matches("template <class T> class X {}; "
987 "template<class Y> class A { class Z : public X<Y> {}; };",
988 ZIsDerivedFromX));
989 EXPECT_TRUE(notMatches("template<template<class T> class X> class A { "
990 " class Z : public X<int> {}; };",
991 ZIsDerivedFromX));
992 EXPECT_TRUE(matches("template<template<class T> class X> class A { "
993 " public: class Z : public X<int> {}; }; "
994 "template<class T> class X {}; void y() { A<X>::Z z; }",
995 ZIsDerivedFromX));
996 EXPECT_TRUE(
997 notMatches("template<class X> class A { class Z : public X::D {}; };",
998 ZIsDerivedFromX));
999 EXPECT_TRUE(matches("template<class X> class A { public: "
1000 " class Z : public X::D {}; }; "
1001 "class Y { public: class X {}; typedef X D; }; "
1002 "void y() { A<Y>::Z z; }",
1003 ZIsDerivedFromX));
1004 EXPECT_TRUE(matches("class X {}; typedef X Y; class Z : public Y {};",
1005 ZIsDerivedFromX));
1006 EXPECT_TRUE(matches("template<class T> class Y { typedef typename T::U X; "
1007 " class Z : public X {}; };",
1008 ZIsDerivedFromX));
1009 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};", ZIsDerivedFromX));
1010 EXPECT_TRUE(
1011 notMatches("template<class T> class X {}; "
1012 "template<class T> class A { class Z : public X<T>::D {}; };",
1013 ZIsDerivedFromX));
1014 EXPECT_TRUE(
1015 matches("template<class T> class X { public: typedef X<T> D; }; "
1016 "template<class T> class A { public: "
1017 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
1018 ZIsDerivedFromX));
1019 EXPECT_TRUE(
1020 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
1021 ZIsDerivedFromX));
1022 EXPECT_TRUE(
1023 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
1024 ZIsDerivedFromX));
1025 EXPECT_TRUE(matches("class X {}; class Y : public X {}; "
1026 "typedef Y V; typedef V W; class Z : public W {};",
1027 ZIsDerivedFromX));
1028 EXPECT_TRUE(notMatches("class X {}; class Y : public X {}; "
1029 "typedef Y V; typedef V W; class Z : public W {};",
1030 ZIsDirectlyDerivedFromX));
1031 EXPECT_TRUE(
1032 matches("template<class T, class U> class X {}; "
1033 "template<class T> class A { class Z : public X<T, int> {}; };",
1034 ZIsDerivedFromX));
1035 EXPECT_TRUE(
1036 notMatches("template<class X> class D { typedef X A; typedef A B; "
1037 " typedef B C; class Z : public C {}; };",
1038 ZIsDerivedFromX));
1039 EXPECT_TRUE(matches("class X {}; typedef X A; typedef A B; "
1040 "class Z : public B {};",
1041 ZIsDerivedFromX));
1042 EXPECT_TRUE(matches("class X {}; typedef X A; typedef A B; typedef B C; "
1043 "class Z : public C {};",
1044 ZIsDerivedFromX));
1045 EXPECT_TRUE(matches("class U {}; typedef U X; typedef X V; "
1046 "class Z : public V {};",
1047 ZIsDerivedFromX));
1048 EXPECT_TRUE(matches("class Base {}; typedef Base X; "
1049 "class Z : public Base {};",
1050 ZIsDerivedFromX));
1051 EXPECT_TRUE(matches("class Base {}; typedef Base Base2; typedef Base2 X; "
1052 "class Z : public Base {};",
1053 ZIsDerivedFromX));
1054 EXPECT_TRUE(notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
1055 "class Z : public Base {};",
1056 ZIsDerivedFromX));
1057 EXPECT_TRUE(matches("class A {}; typedef A X; typedef A Y; "
1058 "class Z : public Y {};",
1059 ZIsDerivedFromX));
1060 EXPECT_TRUE(notMatches("template <typename T> class Z;"
1061 "template <> class Z<void> {};"
1062 "template <typename T> class Z : public Z<void> {};",
1063 IsDerivedFromX));
1064 EXPECT_TRUE(matches("template <typename T> class X;"
1065 "template <> class X<void> {};"
1066 "template <typename T> class X : public X<void> {};",
1067 IsDerivedFromX));
1068 EXPECT_TRUE(
1069 matches("class X {};"
1070 "template <typename T> class Z;"
1071 "template <> class Z<void> {};"
1072 "template <typename T> class Z : public Z<void>, public X {};",
1073 ZIsDerivedFromX));
1074 EXPECT_TRUE(
1075 notMatches("template<int> struct X;"
1076 "template<int i> struct X : public X<i-1> {};",
1077 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
1078 EXPECT_TRUE(matches(
1079 "struct A {};"
1080 "template<int> struct X;"
1081 "template<int i> struct X : public X<i-1> {};"
1082 "template<> struct X<0> : public A {};"
1083 "struct B : public X<42> {};",
1084 cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
1085 EXPECT_TRUE(notMatches(
1086 "struct A {};"
1087 "template<int> struct X;"
1088 "template<int i> struct X : public X<i-1> {};"
1089 "template<> struct X<0> : public A {};"
1090 "struct B : public X<42> {};",
1091 cxxRecordDecl(hasName("B"),
1092 isDirectlyDerivedFrom(recordDecl(hasName("A"))))));
1093
1094 // FIXME: Once we have better matchers for template type matching,
1095 // get rid of the Variable(...) matching and match the right template
1096 // declarations directly.
1097 const char *RecursiveTemplateOneParameter =
1098 "class Base1 {}; class Base2 {};"
1099 "template <typename T> class Z;"
1100 "template <> class Z<void> : public Base1 {};"
1101 "template <> class Z<int> : public Base2 {};"
1102 "template <> class Z<float> : public Z<void> {};"
1103 "template <> class Z<double> : public Z<int> {};"
1104 "template <typename T> class Z : public Z<float>, public Z<double> {};"
1105 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
1106 EXPECT_TRUE(matches(
1107 RecursiveTemplateOneParameter,
1108 varDecl(hasName("z_float"),
1109 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
1110 EXPECT_TRUE(notMatches(
1111 RecursiveTemplateOneParameter,
1112 varDecl(hasName("z_float"),
1113 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
1114 EXPECT_TRUE(
1115 matches(RecursiveTemplateOneParameter,
1116 varDecl(hasName("z_char"),
1117 hasInitializer(hasType(cxxRecordDecl(
1118 isDerivedFrom("Base1"), isDerivedFrom("Base2")))))));
1119
1120 const char *RecursiveTemplateTwoParameters =
1121 "class Base1 {}; class Base2 {};"
1122 "template <typename T1, typename T2> class Z;"
1123 "template <typename T> class Z<void, T> : public Base1 {};"
1124 "template <typename T> class Z<int, T> : public Base2 {};"
1125 "template <typename T> class Z<float, T> : public Z<void, T> {};"
1126 "template <typename T> class Z<double, T> : public Z<int, T> {};"
1127 "template <typename T1, typename T2> class Z : "
1128 " public Z<float, T2>, public Z<double, T2> {};"
1129 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
1130 " Z<char, void> z_char; }";
1131 EXPECT_TRUE(matches(
1132 RecursiveTemplateTwoParameters,
1133 varDecl(hasName("z_float"),
1134 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
1135 EXPECT_TRUE(notMatches(
1136 RecursiveTemplateTwoParameters,
1137 varDecl(hasName("z_float"),
1138 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
1139 EXPECT_TRUE(
1140 matches(RecursiveTemplateTwoParameters,
1141 varDecl(hasName("z_char"),
1142 hasInitializer(hasType(cxxRecordDecl(
1143 isDerivedFrom("Base1"), isDerivedFrom("Base2")))))));
1144 EXPECT_TRUE(matches("namespace ns { class X {}; class Y : public X {}; }",
1145 cxxRecordDecl(isDerivedFrom("::ns::X"))));
1146 EXPECT_TRUE(notMatches("class X {}; class Y : public X {};",
1147 cxxRecordDecl(isDerivedFrom("::ns::X"))));
1148
1149 EXPECT_TRUE(matches(
1150 "class X {}; class Y : public X {};",
1151 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
1152
1153 EXPECT_TRUE(matches("template<typename T> class X {};"
1154 "template<typename T> using Z = X<T>;"
1155 "template <typename T> class Y : Z<T> {};",
1156 cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
1157 }
1158
1159 TEST_P(ASTMatchersTest, IsDerivedFrom_EmptyName) {
1160 if (!GetParam().isCXX()) {
1161 return;
1162 }
1163
1164 const char *const Code = "class X {}; class Y : public X {};";
1165 EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDerivedFrom(""))));
1166 EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDirectlyDerivedFrom(""))));
1167 EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isSameOrDerivedFrom(""))));
1168 }
1169
1170 TEST_P(ASTMatchersTest, IsDerivedFrom_ObjC) {
1171 DeclarationMatcher IsDerivedFromX = objcInterfaceDecl(isDerivedFrom("X"));
1172 EXPECT_TRUE(
1173 matchesObjC("@interface X @end @interface Y : X @end", IsDerivedFromX));
1174 EXPECT_TRUE(matchesObjC(
1175 "@interface X @end @interface Y<__covariant ObjectType> : X @end",
1176 IsDerivedFromX));
1177 EXPECT_TRUE(matchesObjC(
1178 "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1179 IsDerivedFromX));
1180 EXPECT_TRUE(matchesObjC(
1181 "@interface X @end typedef X Y; @interface Z : Y @end", IsDerivedFromX));
1182 EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDerivedFromX));
1183 EXPECT_TRUE(notMatchesObjC("@class X;", IsDerivedFromX));
1184 EXPECT_TRUE(notMatchesObjC("@class Y;", IsDerivedFromX));
1185 EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
1186 IsDerivedFromX));
1187 EXPECT_TRUE(notMatchesObjC("@interface X @end typedef X Y;", IsDerivedFromX));
1188
1189 DeclarationMatcher IsDirectlyDerivedFromX =
1190 objcInterfaceDecl(isDirectlyDerivedFrom("X"));
1191 EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end",
1192 IsDirectlyDerivedFromX));
1193 EXPECT_TRUE(matchesObjC(
1194 "@interface X @end @interface Y<__covariant ObjectType> : X @end",
1195 IsDirectlyDerivedFromX));
1196 EXPECT_TRUE(matchesObjC(
1197 "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1198 IsDirectlyDerivedFromX));
1199 EXPECT_TRUE(
1200 matchesObjC("@interface X @end typedef X Y; @interface Z : Y @end",
1201 IsDirectlyDerivedFromX));
1202 EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDirectlyDerivedFromX));
1203 EXPECT_TRUE(notMatchesObjC("@class X;", IsDirectlyDerivedFromX));
1204 EXPECT_TRUE(notMatchesObjC("@class Y;", IsDirectlyDerivedFromX));
1205 EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
1206 IsDirectlyDerivedFromX));
1207 EXPECT_TRUE(
1208 notMatchesObjC("@interface X @end typedef X Y;", IsDirectlyDerivedFromX));
1209
1210 DeclarationMatcher IsAX = objcInterfaceDecl(isSameOrDerivedFrom("X"));
1211 EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end", IsAX));
1212 EXPECT_TRUE(matchesObjC("@interface X @end", IsAX));
1213 EXPECT_TRUE(matchesObjC("@class X;", IsAX));
1214 EXPECT_TRUE(notMatchesObjC("@interface Y @end", IsAX));
1215 EXPECT_TRUE(notMatchesObjC("@class Y;", IsAX));
1216
1217 DeclarationMatcher ZIsDerivedFromX =
1218 objcInterfaceDecl(hasName("Z"), isDerivedFrom("X"));
1219 DeclarationMatcher ZIsDirectlyDerivedFromX =
1220 objcInterfaceDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
1221 EXPECT_TRUE(matchesObjC(
1222 "@interface X @end @interface Y : X @end @interface Z : Y @end",
1223 ZIsDerivedFromX));
1224 EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end typedef Y "
1225 "V; typedef V W; @interface Z : W @end",
1226 ZIsDerivedFromX));
1227 EXPECT_TRUE(matchesObjC(
1228 "@interface X @end typedef X Y; @interface Z : Y @end", ZIsDerivedFromX));
1229 EXPECT_TRUE(
1230 matchesObjC("@interface X @end typedef X Y; @interface Z : Y @end",
1231 ZIsDirectlyDerivedFromX));
1232 EXPECT_TRUE(matchesObjC(
1233 "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
1234 ZIsDerivedFromX));
1235 EXPECT_TRUE(matchesObjC(
1236 "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
1237 ZIsDirectlyDerivedFromX));
1238 EXPECT_TRUE(matchesObjC(
1239 "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1240 ZIsDerivedFromX));
1241 EXPECT_TRUE(matchesObjC(
1242 "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
1243 ZIsDirectlyDerivedFromX));
1244 EXPECT_TRUE(matchesObjC(
1245 "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
1246 ZIsDerivedFromX));
1247 EXPECT_TRUE(matchesObjC(
1248 "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
1249 ZIsDirectlyDerivedFromX));
1250 EXPECT_TRUE(matchesObjC(
1251 "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
1252 "@interface Z : Y @end",
1253 ZIsDerivedFromX));
1254 EXPECT_TRUE(matchesObjC(
1255 "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
1256 "@interface Z : Y @end",
1257 ZIsDirectlyDerivedFromX));
1258 EXPECT_TRUE(matchesObjC(
1259 "@interface Y @end typedef Y X; @interface Z : X @end", ZIsDerivedFromX));
1260 EXPECT_TRUE(
1261 matchesObjC("@interface Y @end typedef Y X; @interface Z : X @end",
1262 ZIsDirectlyDerivedFromX));
1263 EXPECT_TRUE(
1264 matchesObjC("@interface A @end @compatibility_alias Y A; typedef Y X;"
1265 "@interface Z : A @end",
1266 ZIsDerivedFromX));
1267 EXPECT_TRUE(
1268 matchesObjC("@interface A @end @compatibility_alias Y A; typedef Y X;"
1269 "@interface Z : A @end",
1270 ZIsDirectlyDerivedFromX));
1271 EXPECT_TRUE(
1272 matchesObjC("@interface A @end typedef A Y; @compatibility_alias X Y;"
1273 "@interface Z : A @end",
1274 ZIsDerivedFromX));
1275 EXPECT_TRUE(
1276 matchesObjC("@interface A @end typedef A Y; @compatibility_alias X Y;"
1277 "@interface Z : A @end",
1278 ZIsDirectlyDerivedFromX));
1279 }
1280
1281 TEST_P(ASTMatchersTest, IsLambda) {
1282 if (!GetParam().isCXX11OrLater()) {
1283 return;
1284 }
1285
1286 const auto IsLambda = cxxMethodDecl(ofClass(cxxRecordDecl(isLambda())));
1287 EXPECT_TRUE(matches("auto x = []{};", IsLambda));
1288 EXPECT_TRUE(notMatches("struct S { void operator()() const; };", IsLambda));
1289 }
1290
1291 TEST_P(ASTMatchersTest, Bind) {
1292 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
1293
1294 EXPECT_TRUE(matchAndVerifyResultTrue(
1295 "class X {};", ClassX,
1296 std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x")));
1297
1298 EXPECT_TRUE(matchAndVerifyResultFalse(
1299 "class X {};", ClassX,
1300 std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("other-id")));
1301
1302 TypeMatcher TypeAHasClassB = hasDeclaration(
1303 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
1304
1305 EXPECT_TRUE(matchAndVerifyResultTrue(
1306 "class A { public: A *a; class B {}; };", TypeAHasClassB,
1307 std::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
1308
1309 StatementMatcher MethodX =
1310 callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
1311
1312 EXPECT_TRUE(matchAndVerifyResultTrue(
1313 "class A { void x() { x(); } };", MethodX,
1314 std::make_unique<VerifyIdIsBoundTo<CXXMemberCallExpr>>("x")));
1315 }
1316
1317 TEST_P(ASTMatchersTest, Bind_SameNameInAlternatives) {
1318 StatementMatcher matcher = anyOf(
1319 binaryOperator(hasOperatorName("+"), hasLHS(expr().bind("x")),
1320 hasRHS(integerLiteral(equals(0)))),
1321 binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))),
1322 hasRHS(expr().bind("x"))));
1323
1324 EXPECT_TRUE(matchAndVerifyResultTrue(
1325 // The first branch of the matcher binds x to 0 but then fails.
1326 // The second branch binds x to f() and succeeds.
1327 "int f() { return 0 + f(); }", matcher,
1328 std::make_unique<VerifyIdIsBoundTo<CallExpr>>("x")));
1329 }
1330
1331 TEST_P(ASTMatchersTest, Bind_BindsIDForMemoizedResults) {
1332 // Using the same matcher in two match expressions will make memoization
1333 // kick in.
1334 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
1335 EXPECT_TRUE(matchAndVerifyResultTrue(
1336 "class A { class B { class X {}; }; };",
1337 DeclarationMatcher(
1338 anyOf(recordDecl(hasName("A"), hasDescendant(ClassX)),
1339 recordDecl(hasName("B"), hasDescendant(ClassX)))),
1340 std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 2)));
1341 }
1342
1343 TEST_P(ASTMatchersTest, HasType_MatchesAsString) {
1344 if (!GetParam().isCXX()) {
1345 // FIXME: Add a test for `hasType()` that does not depend on C++.
1346 return;
1347 }
1348
1349 EXPECT_TRUE(
1350 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
1351 cxxMemberCallExpr(on(hasType(asString("Y *"))))));
1352 EXPECT_TRUE(
1353 matches("class X { void x(int x) {} };",
1354 cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
1355 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
1356 fieldDecl(hasType(asString("ns::A")))));
1357 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
1358 fieldDecl(hasType(asString("A")))));
1359 }
1360
1361 TEST_P(ASTMatchersTest, HasOverloadedOperatorName) {
1362 if (!GetParam().isCXX()) {
1363 return;
1364 }
1365
1366 StatementMatcher OpCallAndAnd =
1367 cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
1368 EXPECT_TRUE(matches("class Y { }; "
1369 "bool operator&&(Y x, Y y) { return true; }; "
1370 "Y a; Y b; bool c = a && b;",
1371 OpCallAndAnd));
1372 StatementMatcher OpCallLessLess =
1373 cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
1374 EXPECT_TRUE(notMatches("class Y { }; "
1375 "bool operator&&(Y x, Y y) { return true; }; "
1376 "Y a; Y b; bool c = a && b;",
1377 OpCallLessLess));
1378 StatementMatcher OpStarCall =
1379 cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
1380 EXPECT_TRUE(
1381 matches("class Y; int operator*(Y &); void f(Y &y) { *y; }", OpStarCall));
1382 DeclarationMatcher ClassWithOpStar =
1383 cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
1384 EXPECT_TRUE(matches("class Y { int operator*(); };", ClassWithOpStar));
1385 EXPECT_TRUE(notMatches("class Y { void myOperator(); };", ClassWithOpStar));
1386 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1387 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1388 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
1389 DeclarationMatcher AnyAndOp =
1390 functionDecl(hasAnyOverloadedOperatorName("&", "&&"));
1391 EXPECT_TRUE(matches("class Y; Y operator&(Y &, Y &);", AnyAndOp));
1392 EXPECT_TRUE(matches("class Y; Y operator&&(Y &, Y &);", AnyAndOp));
1393 EXPECT_TRUE(matches("class Y { Y operator&(Y &); };", AnyAndOp));
1394 EXPECT_TRUE(matches("class Y { Y operator&&(Y &); };", AnyAndOp));
1395 }
1396
1397 TEST_P(ASTMatchersTest, HasOverloadedOperatorName_MatchesNestedCalls) {
1398 if (!GetParam().isCXX()) {
1399 return;
1400 }
1401
1402 EXPECT_TRUE(matchAndVerifyResultTrue(
1403 "class Y { }; "
1404 "Y& operator&&(Y& x, Y& y) { return x; }; "
1405 "Y a; Y b; Y c; Y d = a && b && c;",
1406 cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1407 std::make_unique<VerifyIdIsBoundTo<CXXOperatorCallExpr>>("x", 2)));
1408 EXPECT_TRUE(matches("class Y { }; "
1409 "Y& operator&&(Y& x, Y& y) { return x; }; "
1410 "Y a; Y b; Y c; Y d = a && b && c;",
1411 cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
1412 EXPECT_TRUE(
1413 matches("class Y { }; "
1414 "Y& operator&&(Y& x, Y& y) { return x; }; "
1415 "Y a; Y b; Y c; Y d = a && b && c;",
1416 cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
1417 }
1418
1419 TEST_P(ASTMatchersTest, HasLocalStorage) {
1420 auto M = varDecl(hasName("X"), hasLocalStorage());
1421 EXPECT_TRUE(matches("void f() { int X; }", M));
1422 EXPECT_TRUE(notMatches("int X;", M));
1423 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1424 }
1425
1426 TEST_P(ASTMatchersTest, HasGlobalStorage) {
1427 auto M = varDecl(hasName("X"), hasGlobalStorage());
1428 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1429 EXPECT_TRUE(matches("int X;", M));
1430 EXPECT_TRUE(matches("void f() { static int X; }", M));
1431 }
1432
1433 TEST_P(ASTMatchersTest, IsStaticLocal) {
1434 auto M = varDecl(isStaticLocal());
1435 EXPECT_TRUE(matches("void f() { static int X; }", M));
1436 EXPECT_TRUE(notMatches("static int X;", M));
1437 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1438 EXPECT_TRUE(notMatches("int X;", M));
1439 }
1440
1441 TEST_P(ASTMatchersTest, IsInitCapture) {
1442 if (!GetParam().isCXX11OrLater()) {
1443 return;
1444 }
1445 auto M = varDecl(hasName("vd"), isInitCapture());
1446 EXPECT_TRUE(notMatches(
1447 "int main() { int vd = 3; auto f = [vd]() { return vd; }; }", M));
1448
1449 if (!GetParam().isCXX14OrLater()) {
1450 return;
1451 }
1452 EXPECT_TRUE(matches("int main() { auto f = [vd=3]() { return vd; }; }", M));
1453 EXPECT_TRUE(matches(
1454 "int main() { int x = 3; auto f = [vd=x]() { return vd; }; }", M));
1455 }
1456
1457 TEST_P(ASTMatchersTest, StorageDuration) {
1458 StringRef T =
1459 "void f() { int x; static int y; } int a;static int b;extern int c;";
1460
1461 EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
1462 EXPECT_TRUE(
1463 notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
1464 EXPECT_TRUE(
1465 notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
1466
1467 EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
1468 EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
1469 EXPECT_TRUE(matches(T, varDecl(hasName("b"), hasStaticStorageDuration())));
1470 EXPECT_TRUE(matches(T, varDecl(hasName("c"), hasStaticStorageDuration())));
1471 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
1472
1473 // FIXME: Add thread_local variables to the source code snippet.
1474 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
1475 EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
1476 EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
1477 }
1478
1479 TEST_P(ASTMatchersTest, VarDecl_MatchesFunctionParameter) {
1480 EXPECT_TRUE(matches("void f(int i) {}", varDecl(hasName("i"))));
1481 }
1482
1483 TEST_P(ASTMatchersTest, SizeOfExpr_MatchesCorrectType) {
1484 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1485 sizeOfExpr(hasArgumentOfType(asString("int")))));
1486 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1487 sizeOfExpr(hasArgumentOfType(asString("float")))));
1488 EXPECT_TRUE(matches(
1489 "struct A {}; void x() { struct A a; int b = sizeof(a); }",
1490 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
1491 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1492 sizeOfExpr(hasArgumentOfType(
1493 hasDeclaration(recordDecl(hasName("string")))))));
1494 }
1495
1496 TEST_P(ASTMatchersTest, IsInteger_MatchesIntegers) {
1497 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1498 EXPECT_TRUE(
1499 matches("long long i = 0; void f(long long) { }; void g() {f(i);}",
1500 callExpr(hasArgument(
1501 0, declRefExpr(to(varDecl(hasType(isInteger()))))))));
1502 }
1503
1504 TEST_P(ASTMatchersTest, IsInteger_ReportsNoFalsePositives) {
1505 if (!GetParam().isCXX()) {
1506 // FIXME: Add a similar negative test for `isInteger()` that does not depend
1507 // on C++.
1508 return;
1509 }
1510
1511 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
1512 EXPECT_TRUE(
1513 notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
1514 callExpr(hasArgument(
1515 0, declRefExpr(to(varDecl(hasType(isInteger()))))))));
1516 }
1517
1518 TEST_P(ASTMatchersTest, IsSignedInteger_MatchesSignedIntegers) {
1519 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isSignedInteger()))));
1520 EXPECT_TRUE(
1521 notMatches("unsigned i = 0;", varDecl(hasType(isSignedInteger()))));
1522 }
1523
1524 TEST_P(ASTMatchersTest, IsUnsignedInteger_MatchesUnsignedIntegers) {
1525 EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isUnsignedInteger()))));
1526 EXPECT_TRUE(
1527 matches("unsigned i = 0;", varDecl(hasType(isUnsignedInteger()))));
1528 }
1529
1530 TEST_P(ASTMatchersTest, IsAnyPointer_MatchesPointers) {
1531 if (!GetParam().isCXX11OrLater()) {
1532 // FIXME: Add a test for `isAnyPointer()` that does not depend on C++.
1533 return;
1534 }
1535
1536 EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
1537 }
1538
1539 TEST_P(ASTMatchersTest, IsAnyPointer_MatchesObjcPointer) {
1540 EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
1541 varDecl(hasType(isAnyPointer()))));
1542 }
1543
1544 TEST_P(ASTMatchersTest, IsAnyPointer_ReportsNoFalsePositives) {
1545 EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
1546 }
1547
1548 TEST_P(ASTMatchersTest, IsAnyCharacter_MatchesCharacters) {
1549 EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
1550 }
1551
1552 TEST_P(ASTMatchersTest, IsAnyCharacter_ReportsNoFalsePositives) {
1553 EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
1554 }
1555
1556 TEST_P(ASTMatchersTest, IsArrow_MatchesMemberVariablesViaArrow) {
1557 if (!GetParam().isCXX()) {
1558 // FIXME: Add a test for `isArrow()` that does not depend on C++.
1559 return;
1560 }
1561 if (GetParam().hasDelayedTemplateParsing()) {
1562 // FIXME: Fix this test to work with delayed template parsing.
1563 return;
1564 }
1565
1566 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
1567 memberExpr(isArrow())));
1568 EXPECT_TRUE(
1569 matches("class Y { void x() { y; } int y; };", memberExpr(isArrow())));
1570 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
1571 memberExpr(isArrow())));
1572 EXPECT_TRUE(
1573 matches("template <class T> class Y { void x() { this->m; } int m; };",
1574 memberExpr(isArrow())));
1575 EXPECT_TRUE(notMatches(
1576 "template <class T> class Y { void x() { (*this).m; } int m; };",
1577 memberExpr(isArrow())));
1578 }
1579
1580 TEST_P(ASTMatchersTest, IsArrow_MatchesStaticMemberVariablesViaArrow) {
1581 if (!GetParam().isCXX()) {
1582 // FIXME: Add a test for `isArrow()` that does not depend on C++.
1583 return;
1584 }
1585
1586 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
1587 memberExpr(isArrow())));
1588 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
1589 memberExpr(isArrow())));
1590 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
1591 memberExpr(isArrow())));
1592 }
1593
1594 TEST_P(ASTMatchersTest, IsArrow_MatchesMemberCallsViaArrow) {
1595 if (!GetParam().isCXX()) {
1596 // FIXME: Add a test for `isArrow()` that does not depend on C++.
1597 return;
1598 }
1599 if (GetParam().hasDelayedTemplateParsing()) {
1600 // FIXME: Fix this test to work with delayed template parsing.
1601 return;
1602 }
1603
1604 EXPECT_TRUE(
1605 matches("class Y { void x() { this->x(); } };", memberExpr(isArrow())));
1606 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr(isArrow())));
1607 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
1608 memberExpr(isArrow())));
1609 EXPECT_TRUE(
1610 matches("class Y { template <class T> void x() { this->x<T>(); } };",
1611 unresolvedMemberExpr(isArrow())));
1612 EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
1613 unresolvedMemberExpr(isArrow())));
1614 EXPECT_TRUE(
1615 notMatches("class Y { template <class T> void x() { (*this).x<T>(); } };",
1616 unresolvedMemberExpr(isArrow())));
1617 }
1618
1619 TEST_P(ASTMatchersTest, IsExplicit_CXXConversionDecl) {
1620 if (!GetParam().isCXX11OrLater()) {
1621 return;
1622 }
1623
1624 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
1625 cxxConversionDecl(isExplicit())));
1626 EXPECT_TRUE(notMatches("struct S { operator int(); };",
1627 cxxConversionDecl(isExplicit())));
1628 }
1629
1630 TEST_P(ASTMatchersTest, IsExplicit_CXXConversionDecl_CXX20) {
1631 if (!GetParam().isCXX20OrLater()) {
1632 return;
1633 }
1634
1635 EXPECT_TRUE(
1636 notMatches("template<bool b> struct S { explicit(b) operator int(); };",
1637 cxxConversionDecl(isExplicit())));
1638 EXPECT_TRUE(matches("struct S { explicit(true) operator int(); };",
1639 cxxConversionDecl(isExplicit())));
1640 EXPECT_TRUE(notMatches("struct S { explicit(false) operator int(); };",
1641 cxxConversionDecl(isExplicit())));
1642 }
1643
1644 TEST_P(ASTMatchersTest, ArgumentCountAtLeast_CallExpr) {
1645 StatementMatcher Call2PlusArgs = callExpr(argumentCountAtLeast(2));
1646
1647 EXPECT_TRUE(notMatches("void x(void) { x(); }", Call2PlusArgs));
1648 EXPECT_TRUE(notMatches("void x(int) { x(0); }", Call2PlusArgs));
1649 EXPECT_TRUE(matches("void x(int, int) { x(0, 0); }", Call2PlusArgs));
1650 EXPECT_TRUE(matches("void x(int, int, int) { x(0, 0, 0); }", Call2PlusArgs));
1651
1652 if (!GetParam().isCXX()) {
1653 return;
1654 }
1655
1656 EXPECT_TRUE(
1657 notMatches("void x(int = 1) { x(); }", traverse(TK_AsIs, Call2PlusArgs)));
1658 EXPECT_TRUE(matches("void x(int, int = 1) { x(0); }",
1659 traverse(TK_AsIs, Call2PlusArgs)));
1660 EXPECT_TRUE(matches("void x(int, int = 1, int = 1) { x(0); }",
1661 traverse(TK_AsIs, Call2PlusArgs)));
1662 EXPECT_TRUE(matches("void x(int, int, int = 1) { x(0, 0); }",
1663 traverse(TK_AsIs, Call2PlusArgs)));
1664 EXPECT_TRUE(matches("void x(int, int, int, int = 1) { x(0, 0, 0); }",
1665 traverse(TK_AsIs, Call2PlusArgs)));
1666
1667 EXPECT_TRUE(
1668 notMatches("void x(int = 1) { x(); }",
1669 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1670 EXPECT_TRUE(
1671 notMatches("void x(int, int = 1) { x(0); }",
1672 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1673 EXPECT_TRUE(
1674 notMatches("void x(int, int = 1, int = 1) { x(0); }",
1675 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1676 EXPECT_TRUE(matches("void x(int, int, int = 1) { x(0, 0); }",
1677 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1678 EXPECT_TRUE(matches("void x(int, int, int, int = 1) { x(0, 0, 0); }",
1679 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1680 }
1681
1682 TEST_P(ASTMatchersTest, ArgumentCountAtLeast_CallExpr_CXX) {
1683 if (!GetParam().isCXX()) {
1684 return;
1685 }
1686
1687 StatementMatcher Call2PlusArgs = callExpr(argumentCountAtLeast(2));
1688 EXPECT_TRUE(notMatches("class X { void x() { x(); } };", Call2PlusArgs));
1689 EXPECT_TRUE(notMatches("class X { void x(int) { x(0); } };", Call2PlusArgs));
1690 EXPECT_TRUE(
1691 matches("class X { void x(int, int) { x(0, 0); } };", Call2PlusArgs));
1692 EXPECT_TRUE(matches("class X { void x(int, int, int) { x(0, 0, 0); } };",
1693 Call2PlusArgs));
1694
1695 EXPECT_TRUE(notMatches("class X { void x(int = 1) { x(0); } };",
1696 traverse(TK_AsIs, Call2PlusArgs)));
1697 EXPECT_TRUE(matches("class X { void x(int, int = 1) { x(0); } };",
1698 traverse(TK_AsIs, Call2PlusArgs)));
1699 EXPECT_TRUE(matches("class X { void x(int, int = 1, int = 1) { x(0); } };",
1700 traverse(TK_AsIs, Call2PlusArgs)));
1701 EXPECT_TRUE(matches("class X { void x(int, int, int = 1) { x(0, 0); } };",
1702 traverse(TK_AsIs, Call2PlusArgs)));
1703 EXPECT_TRUE(
1704 matches("class X { void x(int, int, int, int = 1) { x(0, 0, 0); } };",
1705 traverse(TK_AsIs, Call2PlusArgs)));
1706
1707 EXPECT_TRUE(
1708 notMatches("class X { void x(int = 1) { x(0); } };",
1709 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1710 EXPECT_TRUE(
1711 notMatches("class X { void x(int, int = 1) { x(0); } };",
1712 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1713 EXPECT_TRUE(
1714 notMatches("class X { void x(int, int = 1, int = 1) { x(0); } };",
1715 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1716 EXPECT_TRUE(matches("class X { void x(int, int, int = 1) { x(0, 0); } };",
1717 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1718 EXPECT_TRUE(
1719 matches("class X { void x(int, int, int, int = 1) { x(0, 0, 0); } };",
1720 traverse(TK_IgnoreUnlessSpelledInSource, Call2PlusArgs)));
1721
1722 EXPECT_TRUE(
1723 notMatches("class X { static void x() { x(); } };", Call2PlusArgs));
1724 EXPECT_TRUE(
1725 notMatches("class X { static void x(int) { x(0); } };", Call2PlusArgs));
1726 EXPECT_TRUE(matches("class X { static void x(int, int) { x(0, 0); } };",
1727 Call2PlusArgs));
1728 EXPECT_TRUE(
1729 matches("class X { static void x(int, int, int) { x(0, 0, 0); } };",
1730 Call2PlusArgs));
1731 }
1732
1733 TEST_P(ASTMatchersTest, ArgumentCountIs_CallExpr) {
1734 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
1735
1736 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1737 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1738 }
1739
1740 TEST_P(ASTMatchersTest, ArgumentCountIs_CallExpr_CXX) {
1741 if (!GetParam().isCXX()) {
1742 return;
1743 }
1744
1745 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
1746 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1747 }
1748
1749 TEST_P(ASTMatchersTest, ParameterCountIs) {
1750 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1751 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1752 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1753 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1754 EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
1755 }
1756
1757 TEST_P(ASTMatchersTest, ParameterCountIs_CXX) {
1758 if (!GetParam().isCXX()) {
1759 return;
1760 }
1761
1762 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1763 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1764 }
1765
1766 TEST_P(ASTMatchersTest, References) {
1767 if (!GetParam().isCXX()) {
1768 // FIXME: Add a test for `references()` that does not depend on C++.
1769 return;
1770 }
1771
1772 DeclarationMatcher ReferenceClassX =
1773 varDecl(hasType(references(recordDecl(hasName("X")))));
1774 EXPECT_TRUE(
1775 matches("class X {}; void y(X y) { X &x = y; }", ReferenceClassX));
1776 EXPECT_TRUE(
1777 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
1778 // The match here is on the implicit copy constructor code for
1779 // class X, not on code 'X x = y'.
1780 EXPECT_TRUE(matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1781 EXPECT_TRUE(notMatches("class X {}; extern X x;", ReferenceClassX));
1782 EXPECT_TRUE(
1783 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1784 }
1785
1786 TEST_P(ASTMatchersTest, HasLocalQualifiers) {
1787 if (!GetParam().isCXX11OrLater()) {
1788 // FIXME: Add a test for `hasLocalQualifiers()` that does not depend on C++.
1789 return;
1790 }
1791
1792 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1793 varDecl(hasType(hasLocalQualifiers()))));
1794 EXPECT_TRUE(matches("int *const j = nullptr;",
1795 varDecl(hasType(hasLocalQualifiers()))));
1796 EXPECT_TRUE(
1797 matches("int *volatile k;", varDecl(hasType(hasLocalQualifiers()))));
1798 EXPECT_TRUE(notMatches("int m;", varDecl(hasType(hasLocalQualifiers()))));
1799 }
1800
1801 TEST_P(ASTMatchersTest, IsExternC_MatchesExternCFunctionDeclarations) {
1802 if (!GetParam().isCXX()) {
1803 return;
1804 }
1805
1806 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1807 EXPECT_TRUE(
1808 matches("extern \"C\" { void f() {} }", functionDecl(isExternC())));
1809 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
1810 }
1811
1812 TEST_P(ASTMatchersTest, IsExternC_MatchesExternCVariableDeclarations) {
1813 if (!GetParam().isCXX()) {
1814 return;
1815 }
1816
1817 EXPECT_TRUE(matches("extern \"C\" int i;", varDecl(isExternC())));
1818 EXPECT_TRUE(matches("extern \"C\" { int i; }", varDecl(isExternC())));
1819 EXPECT_TRUE(notMatches("int i;", varDecl(isExternC())));
1820 }
1821
1822 TEST_P(ASTMatchersTest, IsStaticStorageClass) {
1823 EXPECT_TRUE(
1824 matches("static void f() {}", functionDecl(isStaticStorageClass())));
1825 EXPECT_TRUE(matches("static int i = 1;", varDecl(isStaticStorageClass())));
1826 EXPECT_TRUE(notMatches("int i = 1;", varDecl(isStaticStorageClass())));
1827 EXPECT_TRUE(notMatches("extern int i;", varDecl(isStaticStorageClass())));
1828 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isStaticStorageClass())));
1829 }
1830
1831 TEST_P(ASTMatchersTest, IsDefaulted) {
1832 if (!GetParam().isCXX()) {
1833 return;
1834 }
1835
1836 EXPECT_TRUE(notMatches("class A { ~A(); };",
1837 functionDecl(hasName("~A"), isDefaulted())));
1838 EXPECT_TRUE(matches("class B { ~B() = default; };",
1839 functionDecl(hasName("~B"), isDefaulted())));
1840 }
1841
1842 TEST_P(ASTMatchersTest, IsDeleted) {
1843 if (!GetParam().isCXX()) {
1844 return;
1845 }
1846
1847 EXPECT_TRUE(
1848 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1849 EXPECT_TRUE(matches("void Func() = delete;",
1850 functionDecl(hasName("Func"), isDeleted())));
1851 }
1852
1853 TEST_P(ASTMatchersTest, IsNoThrow_DynamicExceptionSpec) {
1854 if (!GetParam().supportsCXXDynamicExceptionSpecification()) {
1855 return;
1856 }
1857
1858 EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1859 EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1860 EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1861
1862 EXPECT_TRUE(notMatches("void f();", functionProtoType(isNoThrow())));
1863 EXPECT_TRUE(
1864 notMatches("void f() throw(int);", functionProtoType(isNoThrow())));
1865 EXPECT_TRUE(matches("void f() throw();", functionProtoType(isNoThrow())));
1866 }
1867
1868 TEST_P(ASTMatchersTest, IsNoThrow_CXX11) {
1869 if (!GetParam().isCXX11OrLater()) {
1870 return;
1871 }
1872
1873 EXPECT_TRUE(
1874 notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1875 EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1876
1877 EXPECT_TRUE(
1878 notMatches("void f() noexcept(false);", functionProtoType(isNoThrow())));
1879 EXPECT_TRUE(matches("void f() noexcept;", functionProtoType(isNoThrow())));
1880 }
1881
1882 TEST_P(ASTMatchersTest, IsConsteval) {
1883 if (!GetParam().isCXX20OrLater())
1884 return;
1885
1886 EXPECT_TRUE(matches("consteval int bar();",
1887 functionDecl(hasName("bar"), isConsteval())));
1888 EXPECT_TRUE(notMatches("constexpr int bar();",
1889 functionDecl(hasName("bar"), isConsteval())));
1890 EXPECT_TRUE(
1891 notMatches("int bar();", functionDecl(hasName("bar"), isConsteval())));
1892 }
1893
1894 TEST_P(ASTMatchersTest, IsConsteval_MatchesIfConsteval) {
1895 if (!GetParam().isCXX20OrLater())
1896 return;
1897
1898 EXPECT_TRUE(matches("void baz() { if consteval {} }", ifStmt(isConsteval())));
1899 EXPECT_TRUE(
1900 matches("void baz() { if ! consteval {} }", ifStmt(isConsteval())));
1901 EXPECT_TRUE(matches("void baz() { if ! consteval {} else {} }",
1902 ifStmt(isConsteval())));
1903 EXPECT_TRUE(
1904 matches("void baz() { if not consteval {} }", ifStmt(isConsteval())));
1905 EXPECT_TRUE(notMatches("void baz() { if constexpr(1 > 0) {} }",
1906 ifStmt(isConsteval())));
1907 EXPECT_TRUE(
1908 notMatches("void baz() { if (1 > 0) {} }", ifStmt(isConsteval())));
1909 }
1910
1911 TEST_P(ASTMatchersTest, IsConstexpr) {
1912 if (!GetParam().isCXX11OrLater()) {
1913 return;
1914 }
1915
1916 EXPECT_TRUE(matches("constexpr int foo = 42;",
1917 varDecl(hasName("foo"), isConstexpr())));
1918 EXPECT_TRUE(matches("constexpr int bar();",
1919 functionDecl(hasName("bar"), isConstexpr())));
1920 }
1921
1922 TEST_P(ASTMatchersTest, IsConstexpr_MatchesIfConstexpr) {
1923 if (!GetParam().isCXX17OrLater()) {
1924 return;
1925 }
1926
1927 EXPECT_TRUE(
1928 matches("void baz() { if constexpr(1 > 0) {} }", ifStmt(isConstexpr())));
1929 EXPECT_TRUE(
1930 notMatches("void baz() { if (1 > 0) {} }", ifStmt(isConstexpr())));
1931 }
1932
1933 TEST_P(ASTMatchersTest, IsConstinit) {
1934 if (!GetParam().isCXX20OrLater())
1935 return;
1936
1937 EXPECT_TRUE(matches("constinit int foo = 1;",
1938 varDecl(hasName("foo"), isConstinit())));
1939 EXPECT_TRUE(matches("extern constinit int foo;",
1940 varDecl(hasName("foo"), isConstinit())));
1941 EXPECT_TRUE(matches("constinit const char* foo = \"bar\";",
1942 varDecl(hasName("foo"), isConstinit())));
1943 EXPECT_TRUE(
1944 notMatches("[[clang::require_constant_initialization]] int foo = 1;",
1945 varDecl(hasName("foo"), isConstinit())));
1946 EXPECT_TRUE(notMatches("constexpr int foo = 1;",
1947 varDecl(hasName("foo"), isConstinit())));
1948 EXPECT_TRUE(notMatches("static inline int foo = 1;",
1949 varDecl(hasName("foo"), isConstinit())));
1950 }
1951
1952 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers) {
1953 EXPECT_TRUE(notMatches("void baz() { if (1 > 0) {} }",
1954 ifStmt(hasInitStatement(anything()))));
1955 EXPECT_TRUE(notMatches("void baz(int i) { switch (i) { default: break; } }",
1956 switchStmt(hasInitStatement(anything()))));
1957 }
1958
1959 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers_CXX) {
1960 if (!GetParam().isCXX()) {
1961 return;
1962 }
1963
1964 EXPECT_TRUE(notMatches("void baz() { if (int i = 1) {} }",
1965 ifStmt(hasInitStatement(anything()))));
1966 }
1967
1968 TEST_P(ASTMatchersTest, HasInitStatement_MatchesSelectionInitializers_CXX17) {
1969 if (!GetParam().isCXX17OrLater()) {
1970 return;
1971 }
1972
1973 EXPECT_TRUE(matches("void baz() { if (int i = 1; i > 0) {} }",
1974 ifStmt(hasInitStatement(anything()))));
1975 EXPECT_TRUE(
1976 matches("void baz(int i) { switch (int j = i; j) { default: break; } }",
1977 switchStmt(hasInitStatement(anything()))));
1978 }
1979
1980 TEST_P(ASTMatchersTest, HasInitStatement_MatchesRangeForInitializers) {
1981 if (!GetParam().isCXX20OrLater()) {
1982 return;
1983 }
1984
1985 EXPECT_TRUE(matches("void baz() {"
1986 "int items[] = {};"
1987 "for (auto &arr = items; auto &item : arr) {}"
1988 "}",
1989 cxxForRangeStmt(hasInitStatement(anything()))));
1990 EXPECT_TRUE(notMatches("void baz() {"
1991 "int items[] = {};"
1992 "for (auto &item : items) {}"
1993 "}",
1994 cxxForRangeStmt(hasInitStatement(anything()))));
1995 }
1996
1997 TEST_P(ASTMatchersTest, TemplateArgumentCountIs) {
1998 if (!GetParam().isCXX()) {
1999 return;
2000 }
2001
2002 EXPECT_TRUE(
2003 matches("template<typename T> struct C {}; C<int> c;",
2004 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
2005 EXPECT_TRUE(
2006 notMatches("template<typename T> struct C {}; C<int> c;",
2007 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
2008
2009 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
2010 templateSpecializationType(templateArgumentCountIs(1))));
2011 EXPECT_TRUE(
2012 notMatches("template<typename T> struct C {}; C<int> c;",
2013 templateSpecializationType(templateArgumentCountIs(2))));
2014 }
2015
2016 TEST_P(ASTMatchersTest, IsIntegral) {
2017 if (!GetParam().isCXX()) {
2018 return;
2019 }
2020
2021 EXPECT_TRUE(matches(
2022 "template<int T> struct C {}; C<42> c;",
2023 classTemplateSpecializationDecl(hasAnyTemplateArgument(isIntegral()))));
2024 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
2025 classTemplateSpecializationDecl(hasAnyTemplateArgument(
2026 templateArgument(isIntegral())))));
2027 }
2028
2029 TEST_P(ASTMatchersTest, EqualsIntegralValue) {
2030 if (!GetParam().isCXX()) {
2031 return;
2032 }
2033
2034 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
2035 classTemplateSpecializationDecl(
2036 hasAnyTemplateArgument(equalsIntegralValue("42")))));
2037 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
2038 classTemplateSpecializationDecl(
2039 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
2040 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
2041 classTemplateSpecializationDecl(
2042 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
2043 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
2044 classTemplateSpecializationDecl(hasAnyTemplateArgument(
2045 equalsIntegralValue("0042")))));
2046 }
2047
2048 TEST_P(ASTMatchersTest, AccessSpecDecl) {
2049 if (!GetParam().isCXX()) {
2050 return;
2051 }
2052
2053 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
2054 EXPECT_TRUE(
2055 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
2056 EXPECT_TRUE(
2057 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
2058 EXPECT_TRUE(
2059 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
2060
2061 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
2062 }
2063
2064 TEST_P(ASTMatchersTest, IsFinal) {
2065 if (!GetParam().isCXX11OrLater()) {
2066 return;
2067 }
2068
2069 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
2070 EXPECT_TRUE(matches("class X { virtual void f() final; };",
2071 cxxMethodDecl(isFinal())));
2072 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
2073 EXPECT_TRUE(
2074 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
2075 }
2076
2077 TEST_P(ASTMatchersTest, IsVirtual) {
2078 if (!GetParam().isCXX()) {
2079 return;
2080 }
2081
2082 EXPECT_TRUE(matches("class X { virtual int f(); };",
2083 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
2084 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
2085 }
2086
2087 TEST_P(ASTMatchersTest, IsVirtualAsWritten) {
2088 if (!GetParam().isCXX()) {
2089 return;
2090 }
2091
2092 EXPECT_TRUE(matches("class A { virtual int f(); };"
2093 "class B : public A { int f(); };",
2094 cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
2095 EXPECT_TRUE(
2096 notMatches("class A { virtual int f(); };"
2097 "class B : public A { int f(); };",
2098 cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
2099 }
2100
2101 TEST_P(ASTMatchersTest, IsPure) {
2102 if (!GetParam().isCXX()) {
2103 return;
2104 }
2105
2106 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
2107 cxxMethodDecl(isPure(), hasName("::X::f"))));
2108 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
2109 }
2110
2111 TEST_P(ASTMatchersTest, IsExplicitObjectMemberFunction) {
2112 if (!GetParam().isCXX23OrLater()) {
2113 return;
2114 }
2115
2116 auto ExpObjParamFn = cxxMethodDecl(isExplicitObjectMemberFunction());
2117 EXPECT_TRUE(
2118 notMatches("struct A { static int operator()(int); };", ExpObjParamFn));
2119 EXPECT_TRUE(notMatches("struct A { int operator+(int); };", ExpObjParamFn));
2120 EXPECT_TRUE(
2121 matches("struct A { int operator-(this A, int); };", ExpObjParamFn));
2122 EXPECT_TRUE(matches("struct A { void fun(this A &&self); };", ExpObjParamFn));
2123 }
2124
2125 TEST_P(ASTMatchersTest, IsCopyAssignmentOperator) {
2126 if (!GetParam().isCXX()) {
2127 return;
2128 }
2129
2130 auto CopyAssignment =
2131 cxxMethodDecl(isCopyAssignmentOperator(), unless(isImplicit()));
2132 EXPECT_TRUE(matches("class X { X &operator=(X); };", CopyAssignment));
2133 EXPECT_TRUE(matches("class X { X &operator=(X &); };", CopyAssignment));
2134 EXPECT_TRUE(matches("class X { X &operator=(const X &); };", CopyAssignment));
2135 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };", //
2136 CopyAssignment));
2137 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
2138 CopyAssignment));
2139 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };", CopyAssignment));
2140 }
2141
2142 TEST_P(ASTMatchersTest, IsMoveAssignmentOperator) {
2143 if (!GetParam().isCXX()) {
2144 return;
2145 }
2146
2147 auto MoveAssignment =
2148 cxxMethodDecl(isMoveAssignmentOperator(), unless(isImplicit()));
2149 EXPECT_TRUE(notMatches("class X { X &operator=(X); };", MoveAssignment));
2150 EXPECT_TRUE(matches("class X { X &operator=(X &&); };", MoveAssignment));
2151 EXPECT_TRUE(matches("class X { X &operator=(const X &&); };", //
2152 MoveAssignment));
2153 EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };", //
2154 MoveAssignment));
2155 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
2156 MoveAssignment));
2157 EXPECT_TRUE(notMatches("class X { X &operator=(X &); };", MoveAssignment));
2158 }
2159
2160 TEST_P(ASTMatchersTest, IsConst) {
2161 if (!GetParam().isCXX()) {
2162 return;
2163 }
2164
2165 EXPECT_TRUE(
2166 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
2167 EXPECT_TRUE(
2168 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
2169 }
2170
2171 TEST_P(ASTMatchersTest, IsOverride) {
2172 if (!GetParam().isCXX()) {
2173 return;
2174 }
2175
2176 EXPECT_TRUE(matches("class X { virtual int f(); }; "
2177 "class Y : public X { int f(); };",
2178 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
2179 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
2180 "class Y : public X { int f(); };",
2181 cxxMethodDecl(isOverride(), hasName("::X::f"))));
2182 EXPECT_TRUE(notMatches("class X { int f(); }; "
2183 "class Y : public X { int f(); };",
2184 cxxMethodDecl(isOverride())));
2185 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
2186 cxxMethodDecl(isOverride())));
2187 EXPECT_TRUE(
2188 matches("template <typename Base> struct Y : Base { void f() override;};",
2189 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
2190 }
2191
2192 TEST_P(ASTMatchersTest, HasArgument_CXXConstructorDecl) {
2193 if (!GetParam().isCXX()) {
2194 return;
2195 }
2196
2197 auto Constructor = traverse(
2198 TK_AsIs,
2199 cxxConstructExpr(hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))));
2200
2201 EXPECT_TRUE(matches(
2202 "class X { public: X(int); }; void x() { int y; X x(y); }", Constructor));
2203 EXPECT_TRUE(
2204 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
2205 Constructor));
2206 EXPECT_TRUE(
2207 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
2208 Constructor));
2209 EXPECT_TRUE(notMatches(
2210 "class X { public: X(int); }; void x() { int z; X x(z); }", Constructor));
2211
2212 StatementMatcher WrongIndex =
2213 traverse(TK_AsIs, cxxConstructExpr(hasArgument(
2214 42, declRefExpr(to(varDecl(hasName("y")))))));
2215 EXPECT_TRUE(notMatches(
2216 "class X { public: X(int); }; void x() { int y; X x(y); }", WrongIndex));
2217 }
2218
2219 TEST_P(ASTMatchersTest, ArgumentCountIs_CXXConstructExpr) {
2220 if (!GetParam().isCXX()) {
2221 return;
2222 }
2223
2224 auto Constructor1Arg =
2225 traverse(TK_AsIs, cxxConstructExpr(argumentCountIs(1)));
2226
2227 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x(0); }",
2228 Constructor1Arg));
2229 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = X(0); }",
2230 Constructor1Arg));
2231 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
2232 Constructor1Arg));
2233 EXPECT_TRUE(
2234 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
2235 Constructor1Arg));
2236 }
2237
2238 TEST(ASTMatchersTest, NamesMember_CXXDependentScopeMemberExpr) {
2239
2240 // Member functions:
2241 {
2242 auto Code = "template <typename T> struct S{ void mem(); }; template "
2243 "<typename T> void x() { S<T> s; s.mem(); }";
2244
2245 EXPECT_TRUE(matches(
2246 Code,
2247 cxxDependentScopeMemberExpr(
2248 hasObjectExpression(declRefExpr(hasType(elaboratedType(namesType(
2249 templateSpecializationType(hasDeclaration(classTemplateDecl(
2250 has(cxxRecordDecl(has(cxxMethodDecl(hasName("mem"))
2251 .bind("templMem")))))))))))),
2252 memberHasSameNameAsBoundNode("templMem"))));
2253
2254 EXPECT_TRUE(
2255 matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2256 }
2257
2258 // Member variables:
2259 {
2260 auto Code = "template <typename T> struct S{ int mem; }; template "
2261 "<typename T> void x() { S<T> s; s.mem; }";
2262
2263 EXPECT_TRUE(
2264 matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2265
2266 EXPECT_TRUE(matches(
2267 Code,
2268 cxxDependentScopeMemberExpr(
2269 hasObjectExpression(declRefExpr(
2270 hasType(elaboratedType(namesType(templateSpecializationType(
2271 hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
2272 fieldDecl(hasName("mem")).bind("templMem")))))))))))),
2273 memberHasSameNameAsBoundNode("templMem"))));
2274 }
2275
2276 // static member variables:
2277 {
2278 auto Code = "template <typename T> struct S{ static int mem; }; template "
2279 "<typename T> void x() { S<T> s; s.mem; }";
2280
2281 EXPECT_TRUE(
2282 matches(Code, cxxDependentScopeMemberExpr(hasMemberName("mem"))));
2283
2284 EXPECT_TRUE(matches(
2285 Code,
2286 cxxDependentScopeMemberExpr(
2287 hasObjectExpression(declRefExpr(
2288 hasType(elaboratedType(namesType(templateSpecializationType(
2289 hasDeclaration(classTemplateDecl(has(cxxRecordDecl(
2290 has(varDecl(hasName("mem")).bind("templMem")))))))))))),
2291 memberHasSameNameAsBoundNode("templMem"))));
2292 }
2293 {
2294 auto Code = R"cpp(
2295 template <typename T>
2296 struct S {
2297 bool operator==(int) const { return true; }
2298 };
2299
2300 template <typename T>
2301 void func(T t) {
2302 S<T> s;
2303 s.operator==(1);
2304 }
2305 )cpp";
2306
2307 EXPECT_TRUE(matches(
2308 Code, cxxDependentScopeMemberExpr(hasMemberName("operator=="))));
2309 }
2310
2311 // other named decl:
2312 {
2313 auto Code = "template <typename T> struct S{ static int mem; }; struct "
2314 "mem{}; template "
2315 "<typename T> void x() { S<T> s; s.mem; }";
2316
2317 EXPECT_TRUE(matches(
2318 Code,
2319 translationUnitDecl(has(cxxRecordDecl(hasName("mem"))),
2320 hasDescendant(cxxDependentScopeMemberExpr()))));
2321
2322 EXPECT_FALSE(matches(
2323 Code,
2324 translationUnitDecl(has(cxxRecordDecl(hasName("mem")).bind("templMem")),
2325 hasDescendant(cxxDependentScopeMemberExpr(
2326 memberHasSameNameAsBoundNode("templMem"))))));
2327 }
2328 }
2329
2330 TEST(ASTMatchersTest, ArgumentCountIs_CXXUnresolvedConstructExpr) {
2331 const auto *Code =
2332 "template <typename T> struct S{}; template <typename T> void "
2333 "x() { auto s = S<T>(); }";
2334
2335 EXPECT_TRUE(matches(Code, cxxUnresolvedConstructExpr(argumentCountIs(0))));
2336 EXPECT_TRUE(notMatches(Code, cxxUnresolvedConstructExpr(argumentCountIs(1))));
2337 }
2338
2339 TEST(ASTMatchersTest, HasArgument_CXXUnresolvedConstructExpr) {
2340 const auto *Code =
2341 "template <typename T> struct S{ S(int){} }; template <typename "
2342 "T> void x() { int y; auto s = S<T>(y); }";
2343 EXPECT_TRUE(matches(Code, cxxUnresolvedConstructExpr(hasArgument(
2344 0, declRefExpr(to(varDecl(hasName("y"))))))));
2345 EXPECT_TRUE(
2346 notMatches(Code, cxxUnresolvedConstructExpr(hasArgument(
2347 0, declRefExpr(to(varDecl(hasName("x"))))))));
2348 }
2349
2350 TEST_P(ASTMatchersTest, IsListInitialization) {
2351 if (!GetParam().isCXX11OrLater()) {
2352 return;
2353 }
2354
2355 auto ConstructorListInit =
2356 traverse(TK_AsIs, varDecl(has(cxxConstructExpr(isListInitialization()))));
2357
2358 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x{0}; }",
2359 ConstructorListInit));
2360 EXPECT_FALSE(matches("class X { public: X(int); }; void x() { X x(0); }",
2361 ConstructorListInit));
2362 }
2363
2364 TEST_P(ASTMatchersTest, IsImplicit_CXXConstructorDecl) {
2365 if (!GetParam().isCXX()) {
2366 return;
2367 }
2368
2369 // This one doesn't match because the constructor is not added by the
2370 // compiler (it is not needed).
2371 EXPECT_TRUE(notMatches("class Foo { };", cxxConstructorDecl(isImplicit())));
2372 // The compiler added the implicit default constructor.
2373 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
2374 cxxConstructorDecl(isImplicit())));
2375 EXPECT_TRUE(matches("class Foo { Foo(){} };",
2376 cxxConstructorDecl(unless(isImplicit()))));
2377 // The compiler added an implicit assignment operator.
2378 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
2379 cxxMethodDecl(isImplicit(), hasName("operator="))));
2380 }
2381
2382 TEST_P(ASTMatchersTest, IsExplicit_CXXConstructorDecl) {
2383 if (!GetParam().isCXX()) {
2384 return;
2385 }
2386
2387 EXPECT_TRUE(matches("struct S { explicit S(int); };",
2388 cxxConstructorDecl(isExplicit())));
2389 EXPECT_TRUE(
2390 notMatches("struct S { S(int); };", cxxConstructorDecl(isExplicit())));
2391 }
2392
2393 TEST_P(ASTMatchersTest, IsExplicit_CXXConstructorDecl_CXX20) {
2394 if (!GetParam().isCXX20OrLater()) {
2395 return;
2396 }
2397
2398 EXPECT_TRUE(notMatches("template<bool b> struct S { explicit(b) S(int);};",
2399 cxxConstructorDecl(isExplicit())));
2400 EXPECT_TRUE(matches("struct S { explicit(true) S(int);};",
2401 cxxConstructorDecl(isExplicit())));
2402 EXPECT_TRUE(notMatches("struct S { explicit(false) S(int);};",
2403 cxxConstructorDecl(isExplicit())));
2404 }
2405
2406 TEST_P(ASTMatchersTest, IsExplicit_CXXDeductionGuideDecl) {
2407 if (!GetParam().isCXX17OrLater()) {
2408 return;
2409 }
2410
2411 EXPECT_TRUE(notMatches("template<typename T> struct S { S(int);};"
2412 "S(int) -> S<int>;",
2413 cxxDeductionGuideDecl(isExplicit())));
2414 EXPECT_TRUE(matches("template<typename T> struct S { S(int);};"
2415 "explicit S(int) -> S<int>;",
2416 cxxDeductionGuideDecl(isExplicit())));
2417 }
2418
2419 TEST_P(ASTMatchersTest, IsExplicit_CXXDeductionGuideDecl_CXX20) {
2420 if (!GetParam().isCXX20OrLater()) {
2421 return;
2422 }
2423
2424 EXPECT_TRUE(matches("template<typename T> struct S { S(int);};"
2425 "explicit(true) S(int) -> S<int>;",
2426 cxxDeductionGuideDecl(isExplicit())));
2427 EXPECT_TRUE(notMatches("template<typename T> struct S { S(int);};"
2428 "explicit(false) S(int) -> S<int>;",
2429 cxxDeductionGuideDecl(isExplicit())));
2430 EXPECT_TRUE(
2431 notMatches("template<typename T> struct S { S(int);};"
2432 "template<bool b = true> explicit(b) S(int) -> S<int>;",
2433 cxxDeductionGuideDecl(isExplicit())));
2434 }
2435
2436 TEST_P(ASTMatchersTest, CXXConstructorDecl_Kinds) {
2437 if (!GetParam().isCXX()) {
2438 return;
2439 }
2440
2441 EXPECT_TRUE(
2442 matches("struct S { S(); };", cxxConstructorDecl(isDefaultConstructor(),
2443 unless(isImplicit()))));
2444 EXPECT_TRUE(notMatches(
2445 "struct S { S(); };",
2446 cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2447 EXPECT_TRUE(notMatches(
2448 "struct S { S(); };",
2449 cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2450
2451 EXPECT_TRUE(notMatches(
2452 "struct S { S(const S&); };",
2453 cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
2454 EXPECT_TRUE(
2455 matches("struct S { S(const S&); };",
2456 cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2457 EXPECT_TRUE(notMatches(
2458 "struct S { S(const S&); };",
2459 cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2460
2461 EXPECT_TRUE(notMatches(
2462 "struct S { S(S&&); };",
2463 cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
2464 EXPECT_TRUE(notMatches(
2465 "struct S { S(S&&); };",
2466 cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
2467 EXPECT_TRUE(
2468 matches("struct S { S(S&&); };",
2469 cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
2470 }
2471
2472 TEST_P(ASTMatchersTest, IsUserProvided) {
2473 if (!GetParam().isCXX11OrLater()) {
2474 return;
2475 }
2476
2477 EXPECT_TRUE(notMatches("struct S { int X = 0; };",
2478 cxxConstructorDecl(isUserProvided())));
2479 EXPECT_TRUE(notMatches("struct S { S() = default; };",
2480 cxxConstructorDecl(isUserProvided())));
2481 EXPECT_TRUE(notMatches("struct S { S() = delete; };",
2482 cxxConstructorDecl(isUserProvided())));
2483 EXPECT_TRUE(
2484 matches("struct S { S(); };", cxxConstructorDecl(isUserProvided())));
2485 EXPECT_TRUE(matches("struct S { S(); }; S::S(){}",
2486 cxxConstructorDecl(isUserProvided())));
2487 }
2488
2489 TEST_P(ASTMatchersTest, IsDelegatingConstructor) {
2490 if (!GetParam().isCXX11OrLater()) {
2491 return;
2492 }
2493
2494 EXPECT_TRUE(notMatches("struct S { S(); S(int); int X; };",
2495 cxxConstructorDecl(isDelegatingConstructor())));
2496 EXPECT_TRUE(notMatches("struct S { S(){} S(int X) : X(X) {} int X; };",
2497 cxxConstructorDecl(isDelegatingConstructor())));
2498 EXPECT_TRUE(matches(
2499 "struct S { S() : S(0) {} S(int X) : X(X) {} int X; };",
2500 cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(0))));
2501 EXPECT_TRUE(matches(
2502 "struct S { S(); S(int X); int X; }; S::S(int X) : S() {}",
2503 cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1))));
2504 }
2505
2506 TEST_P(ASTMatchersTest, HasSize) {
2507 StatementMatcher Literal = stringLiteral(hasSize(4));
2508 EXPECT_TRUE(matches("const char *s = \"abcd\";", Literal));
2509 // with escaped characters
2510 EXPECT_TRUE(matches("const char *s = \"\x05\x06\x07\x08\";", Literal));
2511 // no matching, too small
2512 EXPECT_TRUE(notMatches("const char *s = \"ab\";", Literal));
2513 }
2514
2515 TEST_P(ASTMatchersTest, HasSize_CXX) {
2516 if (!GetParam().isCXX()) {
2517 // FIXME: Fix this test to also work in non-C++ language modes.
2518 return;
2519 }
2520
2521 StatementMatcher Literal = stringLiteral(hasSize(4));
2522 // wide string
2523 EXPECT_TRUE(matches("const wchar_t *s = L\"abcd\";", Literal));
2524 }
2525
2526 TEST_P(ASTMatchersTest, HasName_MatchesNamespaces) {
2527 if (!GetParam().isCXX()) {
2528 return;
2529 }
2530
2531 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2532 recordDecl(hasName("a::b::C"))));
2533 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2534 recordDecl(hasName("::a::b::C"))));
2535 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2536 recordDecl(hasName("b::C"))));
2537 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
2538 recordDecl(hasName("C"))));
2539 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2540 recordDecl(hasName("c::b::C"))));
2541 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2542 recordDecl(hasName("a::c::C"))));
2543 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2544 recordDecl(hasName("a::b::A"))));
2545 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2546 recordDecl(hasName("::C"))));
2547 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2548 recordDecl(hasName("::b::C"))));
2549 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2550 recordDecl(hasName("z::a::b::C"))));
2551 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
2552 recordDecl(hasName("a+b::C"))));
2553 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
2554 recordDecl(hasName("C"))));
2555 }
2556
2557 TEST_P(ASTMatchersTest, HasName_MatchesOuterClasses) {
2558 if (!GetParam().isCXX()) {
2559 return;
2560 }
2561
2562 EXPECT_TRUE(matches("class A { class B { class C; }; };",
2563 recordDecl(hasName("A::B::C"))));
2564 EXPECT_TRUE(matches("class A { class B { class C; }; };",
2565 recordDecl(hasName("::A::B::C"))));
2566 EXPECT_TRUE(matches("class A { class B { class C; }; };",
2567 recordDecl(hasName("B::C"))));
2568 EXPECT_TRUE(
2569 matches("class A { class B { class C; }; };", recordDecl(hasName("C"))));
2570 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2571 recordDecl(hasName("c::B::C"))));
2572 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2573 recordDecl(hasName("A::c::C"))));
2574 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2575 recordDecl(hasName("A::B::A"))));
2576 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2577 recordDecl(hasName("::C"))));
2578 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2579 recordDecl(hasName("::B::C"))));
2580 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2581 recordDecl(hasName("z::A::B::C"))));
2582 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
2583 recordDecl(hasName("A+B::C"))));
2584 }
2585
2586 TEST_P(ASTMatchersTest, HasName_MatchesInlinedNamespaces) {
2587 if (!GetParam().isCXX()) {
2588 return;
2589 }
2590
2591 StringRef code = "namespace a { inline namespace b { class C; } }";
2592 EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
2593 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2594 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
2595 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2596 }
2597
2598 TEST_P(ASTMatchersTest, HasName_MatchesAnonymousNamespaces) {
2599 if (!GetParam().isCXX()) {
2600 return;
2601 }
2602
2603 StringRef code = "namespace a { namespace { class C; } }";
2604 EXPECT_TRUE(
2605 matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
2606 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
2607 EXPECT_TRUE(
2608 matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
2609 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
2610 }
2611
2612 TEST_P(ASTMatchersTest, HasName_MatchesAnonymousOuterClasses) {
2613 if (!GetParam().isCXX()) {
2614 return;
2615 }
2616
2617 EXPECT_TRUE(matches("class A { class { class C; } x; };",
2618 recordDecl(hasName("A::(anonymous class)::C"))));
2619 EXPECT_TRUE(matches("class A { class { class C; } x; };",
2620 recordDecl(hasName("::A::(anonymous class)::C"))));
2621 EXPECT_FALSE(matches("class A { class { class C; } x; };",
2622 recordDecl(hasName("::A::C"))));
2623 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2624 recordDecl(hasName("A::(anonymous struct)::C"))));
2625 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
2626 recordDecl(hasName("::A::(anonymous struct)::C"))));
2627 EXPECT_FALSE(matches("class A { struct { class C; } x; };",
2628 recordDecl(hasName("::A::C"))));
2629 }
2630
2631 TEST_P(ASTMatchersTest, HasName_MatchesFunctionScope) {
2632 if (!GetParam().isCXX()) {
2633 return;
2634 }
2635
2636 StringRef code =
2637 "namespace a { void F(int a) { struct S { int m; }; int i; } }";
2638 EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
2639 EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
2640
2641 EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
2642 EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
2643 EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
2644 EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
2645 EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
2646 }
2647
2648 TEST_P(ASTMatchersTest, HasName_QualifiedStringMatchesThroughLinkage) {
2649 if (!GetParam().isCXX()) {
2650 return;
2651 }
2652
2653 // https://bugs.llvm.org/show_bug.cgi?id=42193
2654 StringRef code = R"cpp(namespace foo { extern "C" void test(); })cpp";
2655 EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
2656 EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
2657 EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
2658 EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
2659
2660 code = R"cpp(namespace foo { extern "C" { void test(); } })cpp";
2661 EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
2662 EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
2663 EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
2664 EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
2665 }
2666
2667 TEST_P(ASTMatchersTest, HasAnyName) {
2668 if (!GetParam().isCXX()) {
2669 // FIXME: Add a test for `hasAnyName()` that does not depend on C++.
2670 return;
2671 }
2672
2673 StringRef Code = "namespace a { namespace b { class C; } }";
2674
2675 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
2676 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
2677 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
2678 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
2679
2680 EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
2681 EXPECT_TRUE(
2682 matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
2683
2684 std::vector<StringRef> Names = {"::C", "::b::C", "::a::b::C"};
2685 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName(Names))));
2686 }
2687
2688 TEST_P(ASTMatchersTest, IsDefinition) {
2689 DeclarationMatcher DefinitionOfClassA =
2690 recordDecl(hasName("A"), isDefinition());
2691 EXPECT_TRUE(matches("struct A {};", DefinitionOfClassA));
2692 EXPECT_TRUE(notMatches("struct A;", DefinitionOfClassA));
2693
2694 DeclarationMatcher DefinitionOfVariableA =
2695 varDecl(hasName("a"), isDefinition());
2696 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2697 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2698 }
2699
2700 TEST_P(ASTMatchersTest, IsDefinition_CXX) {
2701 if (!GetParam().isCXX()) {
2702 return;
2703 }
2704
2705 DeclarationMatcher DefinitionOfMethodA =
2706 cxxMethodDecl(hasName("a"), isDefinition());
2707 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2708 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2709
2710 DeclarationMatcher DefinitionOfObjCMethodA =
2711 objcMethodDecl(hasName("a"), isDefinition());
2712 EXPECT_TRUE(matchesObjC("@interface A @end "
2713 "@implementation A; -(void)a {} @end",
2714 DefinitionOfObjCMethodA));
2715 EXPECT_TRUE(
2716 notMatchesObjC("@interface A; - (void)a; @end", DefinitionOfObjCMethodA));
2717 }
2718
2719 TEST_P(ASTMatchersTest, HandlesNullQualTypes) {
2720 if (!GetParam().isCXX()) {
2721 // FIXME: Add an equivalent test that does not depend on C++.
2722 return;
2723 }
2724
2725 // FIXME: Add a Type matcher so we can replace uses of this
2726 // variable with Type(True())
2727 const TypeMatcher AnyType = anything();
2728
2729 // We don't really care whether this matcher succeeds; we're testing that
2730 // it completes without crashing.
2731 EXPECT_TRUE(matches(
2732 "struct A { };"
2733 "template <typename T>"
2734 "void f(T t) {"
2735 " T local_t(t /* this becomes a null QualType in the AST */);"
2736 "}"
2737 "void g() {"
2738 " f(0);"
2739 "}",
2740 expr(hasType(TypeMatcher(anyOf(TypeMatcher(hasDeclaration(anything())),
2741 pointsTo(AnyType), references(AnyType)
2742 // Other QualType matchers should go here.
2743 ))))));
2744 }
2745
2746 TEST_P(ASTMatchersTest, ObjCIvarRefExpr) {
2747 StringRef ObjCString =
2748 "@interface A @end "
2749 "@implementation A { A *x; } - (void) func { x = 0; } @end";
2750 EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr()));
2751 EXPECT_TRUE(matchesObjC(
2752 ObjCString, objcIvarRefExpr(hasDeclaration(namedDecl(hasName("x"))))));
2753 EXPECT_FALSE(matchesObjC(
2754 ObjCString, objcIvarRefExpr(hasDeclaration(namedDecl(hasName("y"))))));
2755 }
2756
2757 TEST_P(ASTMatchersTest, BlockExpr) {
2758 EXPECT_TRUE(matchesObjC("void f() { ^{}(); }", blockExpr()));
2759 }
2760
2761 TEST_P(ASTMatchersTest,
2762 StatementCountIs_FindsNoStatementsInAnEmptyCompoundStatement) {
2763 EXPECT_TRUE(matches("void f() { }", compoundStmt(statementCountIs(0))));
2764 EXPECT_TRUE(notMatches("void f() {}", compoundStmt(statementCountIs(1))));
2765 }
2766
2767 TEST_P(ASTMatchersTest, StatementCountIs_AppearsToMatchOnlyOneCount) {
2768 EXPECT_TRUE(matches("void f() { 1; }", compoundStmt(statementCountIs(1))));
2769 EXPECT_TRUE(notMatches("void f() { 1; }", compoundStmt(statementCountIs(0))));
2770 EXPECT_TRUE(notMatches("void f() { 1; }", compoundStmt(statementCountIs(2))));
2771 }
2772
2773 TEST_P(ASTMatchersTest, StatementCountIs_WorksWithMultipleStatements) {
2774 EXPECT_TRUE(
2775 matches("void f() { 1; 2; 3; }", compoundStmt(statementCountIs(3))));
2776 }
2777
2778 TEST_P(ASTMatchersTest, StatementCountIs_WorksWithNestedCompoundStatements) {
2779 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2780 compoundStmt(statementCountIs(1))));
2781 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2782 compoundStmt(statementCountIs(2))));
2783 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
2784 compoundStmt(statementCountIs(3))));
2785 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
2786 compoundStmt(statementCountIs(4))));
2787 }
2788
2789 TEST_P(ASTMatchersTest, Member_WorksInSimplestCase) {
2790 if (!GetParam().isCXX()) {
2791 // FIXME: Add a test for `member()` that does not depend on C++.
2792 return;
2793 }
2794 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
2795 memberExpr(member(hasName("first")))));
2796 }
2797
2798 TEST_P(ASTMatchersTest, Member_DoesNotMatchTheBaseExpression) {
2799 if (!GetParam().isCXX()) {
2800 // FIXME: Add a test for `member()` that does not depend on C++.
2801 return;
2802 }
2803
2804 // Don't pick out the wrong part of the member expression, this should
2805 // be checking the member (name) only.
2806 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
2807 memberExpr(member(hasName("first")))));
2808 }
2809
2810 TEST_P(ASTMatchersTest, Member_MatchesInMemberFunctionCall) {
2811 if (!GetParam().isCXX()) {
2812 return;
2813 }
2814
2815 EXPECT_TRUE(matches("void f() {"
2816 " struct { void first() {}; } s;"
2817 " s.first();"
2818 "};",
2819 memberExpr(member(hasName("first")))));
2820 }
2821
2822 TEST_P(ASTMatchersTest, FieldDecl) {
2823 EXPECT_TRUE(
2824 matches("struct A { int i; }; void f() { struct A a; a.i = 2; }",
2825 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2826 EXPECT_TRUE(
2827 notMatches("struct A { float f; }; void f() { struct A a; a.f = 2.0f; }",
2828 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2829 }
2830
2831 TEST_P(ASTMatchersTest, IsBitField) {
2832 EXPECT_TRUE(matches("struct C { int a : 2; int b; };",
2833 fieldDecl(isBitField(), hasName("a"))));
2834 EXPECT_TRUE(notMatches("struct C { int a : 2; int b; };",
2835 fieldDecl(isBitField(), hasName("b"))));
2836 EXPECT_TRUE(matches("struct C { int a : 2; int b : 4; };",
2837 fieldDecl(isBitField(), hasBitWidth(2), hasName("a"))));
2838 }
2839
2840 TEST_P(ASTMatchersTest, HasInClassInitializer) {
2841 if (!GetParam().isCXX()) {
2842 return;
2843 }
2844
2845 EXPECT_TRUE(
2846 matches("class C { int a = 2; int b; };",
2847 fieldDecl(hasInClassInitializer(integerLiteral(equals(2))),
2848 hasName("a"))));
2849 EXPECT_TRUE(
2850 notMatches("class C { int a = 2; int b; };",
2851 fieldDecl(hasInClassInitializer(anything()), hasName("b"))));
2852 }
2853
2854 TEST_P(ASTMatchersTest, IsPublic_IsProtected_IsPrivate) {
2855 if (!GetParam().isCXX()) {
2856 return;
2857 }
2858
2859 EXPECT_TRUE(
2860 matches("struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2861 EXPECT_TRUE(notMatches("struct A { int i; };",
2862 fieldDecl(isProtected(), hasName("i"))));
2863 EXPECT_TRUE(
2864 notMatches("struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2865
2866 EXPECT_TRUE(
2867 notMatches("class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2868 EXPECT_TRUE(notMatches("class A { int i; };",
2869 fieldDecl(isProtected(), hasName("i"))));
2870 EXPECT_TRUE(
2871 matches("class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2872
2873 EXPECT_TRUE(notMatches("class A { protected: int i; };",
2874 fieldDecl(isPublic(), hasName("i"))));
2875 EXPECT_TRUE(matches("class A { protected: int i; };",
2876 fieldDecl(isProtected(), hasName("i"))));
2877 EXPECT_TRUE(notMatches("class A { protected: int i; };",
2878 fieldDecl(isPrivate(), hasName("i"))));
2879
2880 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2881 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2882 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2883 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2884 }
2885
2886 TEST_P(ASTMatchersTest,
2887 HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications) {
2888 if (!GetParam().supportsCXXDynamicExceptionSpecification()) {
2889 return;
2890 }
2891
2892 EXPECT_TRUE(notMatches("void f();", functionDecl(hasDynamicExceptionSpec())));
2893 EXPECT_TRUE(
2894 matches("void j() throw();", functionDecl(hasDynamicExceptionSpec())));
2895 EXPECT_TRUE(
2896 matches("void k() throw(int);", functionDecl(hasDynamicExceptionSpec())));
2897 EXPECT_TRUE(
2898 matches("void l() throw(...);", functionDecl(hasDynamicExceptionSpec())));
2899
2900 EXPECT_TRUE(
2901 notMatches("void f();", functionProtoType(hasDynamicExceptionSpec())));
2902 EXPECT_TRUE(matches("void j() throw();",
2903 functionProtoType(hasDynamicExceptionSpec())));
2904 EXPECT_TRUE(matches("void k() throw(int);",
2905 functionProtoType(hasDynamicExceptionSpec())));
2906 EXPECT_TRUE(matches("void l() throw(...);",
2907 functionProtoType(hasDynamicExceptionSpec())));
2908 }
2909
2910 TEST_P(ASTMatchersTest,
2911 HasDynamicExceptionSpec_MatchesDynamicExceptionSpecifications_CXX11) {
2912 if (!GetParam().isCXX11OrLater()) {
2913 return;
2914 }
2915
2916 EXPECT_TRUE(notMatches("void g() noexcept;",
2917 functionDecl(hasDynamicExceptionSpec())));
2918 EXPECT_TRUE(notMatches("void h() noexcept(true);",
2919 functionDecl(hasDynamicExceptionSpec())));
2920 EXPECT_TRUE(notMatches("void i() noexcept(false);",
2921 functionDecl(hasDynamicExceptionSpec())));
2922
2923 EXPECT_TRUE(notMatches("void g() noexcept;",
2924 functionProtoType(hasDynamicExceptionSpec())));
2925 EXPECT_TRUE(notMatches("void h() noexcept(true);",
2926 functionProtoType(hasDynamicExceptionSpec())));
2927 EXPECT_TRUE(notMatches("void i() noexcept(false);",
2928 functionProtoType(hasDynamicExceptionSpec())));
2929 }
2930
2931 TEST_P(ASTMatchersTest, HasObjectExpression_DoesNotMatchMember) {
2932 if (!GetParam().isCXX()) {
2933 return;
2934 }
2935
2936 EXPECT_TRUE(notMatches(
2937 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
2938 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2939 }
2940
2941 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfVariable) {
2942 EXPECT_TRUE(matches(
2943 "struct X { int m; }; void f(struct X x) { x.m; }",
2944 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2945 EXPECT_TRUE(matches("struct X { int m; }; void f(struct X* x) { x->m; }",
2946 memberExpr(hasObjectExpression(
2947 hasType(pointsTo(recordDecl(hasName("X"))))))));
2948 }
2949
2950 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfVariable_CXX) {
2951 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
2952 // FIXME: Fix this test to work with delayed template parsing.
2953 return;
2954 }
2955
2956 EXPECT_TRUE(matches("template <class T> struct X { void f() { T t; t.m; } };",
2957 cxxDependentScopeMemberExpr(hasObjectExpression(
2958 declRefExpr(to(namedDecl(hasName("t"))))))));
2959 EXPECT_TRUE(
2960 matches("template <class T> struct X { void f() { T t; t->m; } };",
2961 cxxDependentScopeMemberExpr(hasObjectExpression(
2962 declRefExpr(to(namedDecl(hasName("t"))))))));
2963 }
2964
2965 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfMemberFunc) {
2966 if (!GetParam().isCXX()) {
2967 return;
2968 }
2969
2970 EXPECT_TRUE(matches(
2971 "struct X { void f(); }; void g(X x) { x.f(); }",
2972 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
2973 }
2974
2975 TEST_P(ASTMatchersTest, HasObjectExpression_MatchesBaseOfMemberFunc_Template) {
2976 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
2977 // FIXME: Fix this test to work with delayed template parsing.
2978 return;
2979 }
2980
2981 EXPECT_TRUE(matches("struct X { template <class T> void f(); };"
2982 "template <class T> void g(X x) { x.f<T>(); }",
2983 unresolvedMemberExpr(hasObjectExpression(
2984 hasType(recordDecl(hasName("X")))))));
2985 EXPECT_TRUE(matches("template <class T> void f(T t) { t.g(); }",
2986 cxxDependentScopeMemberExpr(hasObjectExpression(
2987 declRefExpr(to(namedDecl(hasName("t"))))))));
2988 }
2989
2990 TEST_P(ASTMatchersTest, HasObjectExpression_ImplicitlyFormedMemberExpression) {
2991 if (!GetParam().isCXX()) {
2992 return;
2993 }
2994
2995 EXPECT_TRUE(matches("class X {}; struct S { X m; void f() { this->m; } };",
2996 memberExpr(hasObjectExpression(
2997 hasType(pointsTo(recordDecl(hasName("S"))))))));
2998 EXPECT_TRUE(matches("class X {}; struct S { X m; void f() { m; } };",
2999 memberExpr(hasObjectExpression(
3000 hasType(pointsTo(recordDecl(hasName("S"))))))));
3001 }
3002
3003 TEST_P(ASTMatchersTest, FieldDecl_DoesNotMatchNonFieldMembers) {
3004 if (!GetParam().isCXX()) {
3005 return;
3006 }
3007
3008 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
3009 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
3010 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
3011 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
3012 }
3013
3014 TEST_P(ASTMatchersTest, FieldDecl_MatchesField) {
3015 EXPECT_TRUE(matches("struct X { int m; };", fieldDecl(hasName("m"))));
3016 }
3017
3018 TEST_P(ASTMatchersTest, IsVolatileQualified) {
3019 EXPECT_TRUE(
3020 matches("volatile int i = 42;", varDecl(hasType(isVolatileQualified()))));
3021 EXPECT_TRUE(
3022 notMatches("volatile int *i;", varDecl(hasType(isVolatileQualified()))));
3023 EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
3024 varDecl(hasType(isVolatileQualified()))));
3025 }
3026
3027 TEST_P(ASTMatchersTest, IsConstQualified_MatchesConstInt) {
3028 EXPECT_TRUE(
3029 matches("const int i = 42;", varDecl(hasType(isConstQualified()))));
3030 }
3031
3032 TEST_P(ASTMatchersTest, IsConstQualified_MatchesConstPointer) {
3033 EXPECT_TRUE(matches("int i = 42; int* const p = &i;",
3034 varDecl(hasType(isConstQualified()))));
3035 }
3036
3037 TEST_P(ASTMatchersTest, IsConstQualified_MatchesThroughTypedef) {
3038 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
3039 varDecl(hasType(isConstQualified()))));
3040 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p = ((int*)0);",
3041 varDecl(hasType(isConstQualified()))));
3042 }
3043
3044 TEST_P(ASTMatchersTest, IsConstQualified_DoesNotMatchInappropriately) {
3045 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
3046 varDecl(hasType(isConstQualified()))));
3047 EXPECT_TRUE(
3048 notMatches("int const* p;", varDecl(hasType(isConstQualified()))));
3049 }
3050
3051 TEST_P(ASTMatchersTest, DeclCountIs_DeclCountIsCorrect) {
3052 EXPECT_TRUE(matches("void f() {int i,j;}", declStmt(declCountIs(2))));
3053 EXPECT_TRUE(
3054 notMatches("void f() {int i,j; int k;}", declStmt(declCountIs(3))));
3055 EXPECT_TRUE(
3056 notMatches("void f() {int i,j, k, l;}", declStmt(declCountIs(3))));
3057 }
3058
3059 TEST_P(ASTMatchersTest, EachOf_TriggersForEachMatch) {
3060 EXPECT_TRUE(matchAndVerifyResultTrue(
3061 "class A { int a; int b; };",
3062 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3063 has(fieldDecl(hasName("b")).bind("v")))),
3064 std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
3065 }
3066
3067 TEST_P(ASTMatchersTest, EachOf_BehavesLikeAnyOfUnlessBothMatch) {
3068 EXPECT_TRUE(matchAndVerifyResultTrue(
3069 "struct A { int a; int c; };",
3070 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3071 has(fieldDecl(hasName("b")).bind("v")))),
3072 std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
3073 EXPECT_TRUE(matchAndVerifyResultTrue(
3074 "struct A { int c; int b; };",
3075 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3076 has(fieldDecl(hasName("b")).bind("v")))),
3077 std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
3078 EXPECT_TRUE(
3079 notMatches("struct A { int c; int d; };",
3080 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3081 has(fieldDecl(hasName("b")).bind("v"))))));
3082 }
3083
3084 TEST_P(ASTMatchersTest, Optionally_SubmatchersDoNotMatch) {
3085 EXPECT_TRUE(matchAndVerifyResultFalse(
3086 "class A { int a; int b; };",
3087 recordDecl(optionally(has(fieldDecl(hasName("c")).bind("c")))),
3088 std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("c")));
3089 }
3090
3091 // Regression test.
3092 TEST_P(ASTMatchersTest, Optionally_SubmatchersDoNotMatchButPreserveBindings) {
3093 StringRef Code = "class A { int a; int b; };";
3094 auto Matcher = recordDecl(decl().bind("decl"),
3095 optionally(has(fieldDecl(hasName("c")).bind("v"))));
3096 // "decl" is still bound.
3097 EXPECT_TRUE(matchAndVerifyResultTrue(
3098 Code, Matcher, std::make_unique<VerifyIdIsBoundTo<RecordDecl>>("decl")));
3099 // "v" is not bound, but the match still suceeded.
3100 EXPECT_TRUE(matchAndVerifyResultFalse(
3101 Code, Matcher, std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v")));
3102 }
3103
3104 TEST_P(ASTMatchersTest, Optionally_SubmatchersMatch) {
3105 EXPECT_TRUE(matchAndVerifyResultTrue(
3106 "class A { int a; int c; };",
3107 recordDecl(optionally(has(fieldDecl(hasName("a")).bind("v")))),
3108 std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v")));
3109 }
3110
3111 TEST_P(ASTMatchersTest,
3112 IsTemplateInstantiation_MatchesImplicitClassTemplateInstantiation) {
3113 if (!GetParam().isCXX()) {
3114 return;
3115 }
3116
3117 // Make sure that we can both match the class by name (::X) and by the type
3118 // the template was instantiated with (via a field).
3119
3120 EXPECT_TRUE(
3121 matches("template <typename T> class X {}; class A {}; X<A> x;",
3122 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3123
3124 EXPECT_TRUE(matches(
3125 "template <typename T> class X { T t; }; class A {}; X<A> x;",
3126 cxxRecordDecl(
3127 isTemplateInstantiation(),
3128 hasDescendant(fieldDecl(hasType(recordDecl(hasName("A"))))))));
3129 }
3130
3131 TEST_P(ASTMatchersTest,
3132 IsTemplateInstantiation_MatchesImplicitFunctionTemplateInstantiation) {
3133 if (!GetParam().isCXX()) {
3134 return;
3135 }
3136
3137 EXPECT_TRUE(matches(
3138 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
3139 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
3140 isTemplateInstantiation())));
3141 }
3142
3143 TEST_P(ASTMatchersTest,
3144 IsTemplateInstantiation_MatchesExplicitClassTemplateInstantiation) {
3145 if (!GetParam().isCXX()) {
3146 return;
3147 }
3148
3149 EXPECT_TRUE(matches("template <typename T> class X { T t; }; class A {};"
3150 "template class X<A>;",
3151 cxxRecordDecl(isTemplateInstantiation(),
3152 hasDescendant(fieldDecl(
3153 hasType(recordDecl(hasName("A"))))))));
3154
3155 // Make sure that we match the instantiation instead of the template
3156 // definition by checking whether the member function is present.
3157 EXPECT_TRUE(
3158 matches("template <typename T> class X { void f() { T t; } };"
3159 "extern template class X<int>;",
3160 cxxRecordDecl(isTemplateInstantiation(),
3161 unless(hasDescendant(varDecl(hasName("t")))))));
3162 }
3163
3164 TEST_P(
3165 ASTMatchersTest,
3166 IsTemplateInstantiation_MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3167 if (!GetParam().isCXX()) {
3168 return;
3169 }
3170
3171 EXPECT_TRUE(
3172 matches("template <typename T> class X {};"
3173 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
3174 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3175 }
3176
3177 TEST_P(
3178 ASTMatchersTest,
3179 IsTemplateInstantiation_MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3180 if (!GetParam().isCXX()) {
3181 return;
3182 }
3183
3184 EXPECT_TRUE(
3185 matches("class A {};"
3186 "class X {"
3187 " template <typename U> class Y { U u; };"
3188 " Y<A> y;"
3189 "};",
3190 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
3191 }
3192
3193 TEST_P(
3194 ASTMatchersTest,
3195 IsTemplateInstantiation_DoesNotMatchInstantiationsInsideOfInstantiation) {
3196 if (!GetParam().isCXX()) {
3197 return;
3198 }
3199
3200 // FIXME: Figure out whether this makes sense. It doesn't affect the
3201 // normal use case as long as the uppermost instantiation always is marked
3202 // as template instantiation, but it might be confusing as a predicate.
3203 EXPECT_TRUE(matches(
3204 "class A {};"
3205 "template <typename T> class X {"
3206 " template <typename U> class Y { U u; };"
3207 " Y<T> y;"
3208 "}; X<A> x;",
3209 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
3210 }
3211
3212 TEST_P(
3213 ASTMatchersTest,
3214 IsTemplateInstantiation_DoesNotMatchExplicitClassTemplateSpecialization) {
3215 if (!GetParam().isCXX()) {
3216 return;
3217 }
3218
3219 EXPECT_TRUE(
3220 notMatches("template <typename T> class X {}; class A {};"
3221 "template <> class X<A> {}; X<A> x;",
3222 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
3223 }
3224
3225 TEST_P(ASTMatchersTest, IsTemplateInstantiation_DoesNotMatchNonTemplate) {
3226 if (!GetParam().isCXX()) {
3227 return;
3228 }
3229
3230 EXPECT_TRUE(notMatches("class A {}; class Y { A a; };",
3231 cxxRecordDecl(isTemplateInstantiation())));
3232 }
3233
3234 TEST_P(ASTMatchersTest, IsInstantiated_MatchesInstantiation) {
3235 if (!GetParam().isCXX()) {
3236 return;
3237 }
3238
3239 EXPECT_TRUE(
3240 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3241 cxxRecordDecl(isInstantiated())));
3242 }
3243
3244 TEST_P(ASTMatchersTest, IsInstantiated_NotMatchesDefinition) {
3245 if (!GetParam().isCXX()) {
3246 return;
3247 }
3248
3249 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3250 cxxRecordDecl(isInstantiated())));
3251 }
3252
3253 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_MatchesInstantiationStmt) {
3254 if (!GetParam().isCXX()) {
3255 return;
3256 }
3257
3258 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3259 "class Y { A<int> a; }; Y y;",
3260 declStmt(isInTemplateInstantiation())));
3261 }
3262
3263 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_NotMatchesDefinitionStmt) {
3264 if (!GetParam().isCXX()) {
3265 return;
3266 }
3267
3268 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3269 declStmt(isInTemplateInstantiation())));
3270 }
3271
3272 TEST_P(ASTMatchersTest, IsInstantiated_MatchesFunctionInstantiation) {
3273 if (!GetParam().isCXX()) {
3274 return;
3275 }
3276
3277 EXPECT_TRUE(
3278 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3279 functionDecl(isInstantiated())));
3280 }
3281
3282 TEST_P(ASTMatchersTest, IsInstantiated_NotMatchesFunctionDefinition) {
3283 if (!GetParam().isCXX()) {
3284 return;
3285 }
3286
3287 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3288 varDecl(isInstantiated())));
3289 }
3290
3291 TEST_P(ASTMatchersTest,
3292 IsInTemplateInstantiation_MatchesFunctionInstantiationStmt) {
3293 if (!GetParam().isCXX()) {
3294 return;
3295 }
3296
3297 EXPECT_TRUE(
3298 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3299 declStmt(isInTemplateInstantiation())));
3300 }
3301
3302 TEST_P(ASTMatchersTest,
3303 IsInTemplateInstantiation_NotMatchesFunctionDefinitionStmt) {
3304 if (!GetParam().isCXX()) {
3305 return;
3306 }
3307
3308 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3309 declStmt(isInTemplateInstantiation())));
3310 }
3311
3312 TEST_P(ASTMatchersTest, IsInTemplateInstantiation_Sharing) {
3313 if (!GetParam().isCXX()) {
3314 return;
3315 }
3316
3317 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3318 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3319 // and makes the matcher behave in non-obvious ways.
3320 EXPECT_TRUE(notMatches(
3321 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3322 Matcher));
3323 EXPECT_TRUE(matches(
3324 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3325 Matcher));
3326 }
3327
3328 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesNonValueTypeDependent) {
3329 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3330 // FIXME: Fix this test to work with delayed template parsing.
3331 return;
3332 }
3333
3334 EXPECT_TRUE(matches(
3335 "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
3336 expr(isInstantiationDependent())));
3337 }
3338
3339 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesValueDependent) {
3340 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3341 // FIXME: Fix this test to work with delayed template parsing.
3342 return;
3343 }
3344
3345 EXPECT_TRUE(matches("template<int T> int f() { return T; }",
3346 expr(isInstantiationDependent())));
3347 }
3348
3349 TEST_P(ASTMatchersTest, IsInstantiationDependent_MatchesTypeDependent) {
3350 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3351 // FIXME: Fix this test to work with delayed template parsing.
3352 return;
3353 }
3354
3355 EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3356 expr(isInstantiationDependent())));
3357 }
3358
3359 TEST_P(ASTMatchersTest, IsTypeDependent_MatchesTypeDependent) {
3360 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3361 // FIXME: Fix this test to work with delayed template parsing.
3362 return;
3363 }
3364
3365 EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3366 expr(isTypeDependent())));
3367 }
3368
3369 TEST_P(ASTMatchersTest, IsTypeDependent_NotMatchesValueDependent) {
3370 if (!GetParam().isCXX()) {
3371 return;
3372 }
3373
3374 EXPECT_TRUE(notMatches("template<int T> int f() { return T; }",
3375 expr(isTypeDependent())));
3376 }
3377
3378 TEST_P(ASTMatchersTest, IsValueDependent_MatchesValueDependent) {
3379 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3380 // FIXME: Fix this test to work with delayed template parsing.
3381 return;
3382 }
3383
3384 EXPECT_TRUE(matches("template<int T> int f() { return T; }",
3385 expr(isValueDependent())));
3386 }
3387
3388 TEST_P(ASTMatchersTest, IsValueDependent_MatchesTypeDependent) {
3389 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3390 // FIXME: Fix this test to work with delayed template parsing.
3391 return;
3392 }
3393
3394 EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
3395 expr(isValueDependent())));
3396 }
3397
3398 TEST_P(ASTMatchersTest, IsValueDependent_MatchesInstantiationDependent) {
3399 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3400 // FIXME: Fix this test to work with delayed template parsing.
3401 return;
3402 }
3403
3404 EXPECT_TRUE(matches(
3405 "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
3406 expr(isValueDependent())));
3407 }
3408
3409 TEST_P(ASTMatchersTest,
3410 IsExplicitTemplateSpecialization_DoesNotMatchPrimaryTemplate) {
3411 if (!GetParam().isCXX()) {
3412 return;
3413 }
3414
3415 EXPECT_TRUE(notMatches("template <typename T> class X {};",
3416 cxxRecordDecl(isExplicitTemplateSpecialization())));
3417 EXPECT_TRUE(notMatches("template <typename T> void f(T t);",
3418 functionDecl(isExplicitTemplateSpecialization())));
3419 }
3420
3421 TEST_P(
3422 ASTMatchersTest,
3423 IsExplicitTemplateSpecialization_DoesNotMatchExplicitTemplateInstantiations) {
3424 if (!GetParam().isCXX()) {
3425 return;
3426 }
3427
3428 EXPECT_TRUE(
3429 notMatches("template <typename T> class X {};"
3430 "template class X<int>; extern template class X<long>;",
3431 cxxRecordDecl(isExplicitTemplateSpecialization())));
3432 EXPECT_TRUE(
3433 notMatches("template <typename T> void f(T t) {}"
3434 "template void f(int t); extern template void f(long t);",
3435 functionDecl(isExplicitTemplateSpecialization())));
3436 }
3437
3438 TEST_P(
3439 ASTMatchersTest,
3440 IsExplicitTemplateSpecialization_DoesNotMatchImplicitTemplateInstantiations) {
3441 if (!GetParam().isCXX()) {
3442 return;
3443 }
3444
3445 EXPECT_TRUE(notMatches("template <typename T> class X {}; X<int> x;",
3446 cxxRecordDecl(isExplicitTemplateSpecialization())));
3447 EXPECT_TRUE(
3448 notMatches("template <typename T> void f(T t); void g() { f(10); }",
3449 functionDecl(isExplicitTemplateSpecialization())));
3450 }
3451
3452 TEST_P(
3453 ASTMatchersTest,
3454 IsExplicitTemplateSpecialization_MatchesExplicitTemplateSpecializations) {
3455 if (!GetParam().isCXX()) {
3456 return;
3457 }
3458
3459 EXPECT_TRUE(matches("template <typename T> class X {};"
3460 "template<> class X<int> {};",
3461 cxxRecordDecl(isExplicitTemplateSpecialization())));
3462 EXPECT_TRUE(matches("template <typename T> void f(T t) {}"
3463 "template<> void f(int t) {}",
3464 functionDecl(isExplicitTemplateSpecialization())));
3465 }
3466
3467 TEST_P(ASTMatchersTest, IsNoReturn) {
3468 EXPECT_TRUE(notMatches("void func();", functionDecl(isNoReturn())));
3469 EXPECT_TRUE(notMatches("void func() {}", functionDecl(isNoReturn())));
3470
3471 EXPECT_TRUE(matches("__attribute__((noreturn)) void func();",
3472 functionDecl(isNoReturn())));
3473 EXPECT_TRUE(matches("__attribute__((noreturn)) void func() {}",
3474 functionDecl(isNoReturn())));
3475
3476 EXPECT_TRUE(matches("_Noreturn void func();", functionDecl(isNoReturn())));
3477 EXPECT_TRUE(matches("_Noreturn void func() {}", functionDecl(isNoReturn())));
3478 }
3479
3480 TEST_P(ASTMatchersTest, IsNoReturn_CXX) {
3481 if (!GetParam().isCXX()) {
3482 return;
3483 }
3484
3485 EXPECT_TRUE(
3486 notMatches("struct S { void func(); };", functionDecl(isNoReturn())));
3487 EXPECT_TRUE(
3488 notMatches("struct S { void func() {} };", functionDecl(isNoReturn())));
3489
3490 EXPECT_TRUE(notMatches("struct S { static void func(); };",
3491 functionDecl(isNoReturn())));
3492 EXPECT_TRUE(notMatches("struct S { static void func() {} };",
3493 functionDecl(isNoReturn())));
3494
3495 EXPECT_TRUE(notMatches("struct S { S(); };", functionDecl(isNoReturn())));
3496 EXPECT_TRUE(notMatches("struct S { S() {} };", functionDecl(isNoReturn())));
3497
3498 // ---
3499
3500 EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func(); };",
3501 functionDecl(isNoReturn())));
3502 EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func() {} };",
3503 functionDecl(isNoReturn())));
3504
3505 EXPECT_TRUE(
3506 matches("struct S { __attribute__((noreturn)) static void func(); };",
3507 functionDecl(isNoReturn())));
3508 EXPECT_TRUE(
3509 matches("struct S { __attribute__((noreturn)) static void func() {} };",
3510 functionDecl(isNoReturn())));
3511
3512 EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S(); };",
3513 functionDecl(isNoReturn())));
3514 EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S() {} };",
3515 functionDecl(isNoReturn())));
3516 }
3517
3518 TEST_P(ASTMatchersTest, IsNoReturn_CXX11Attribute) {
3519 if (!GetParam().isCXX11OrLater()) {
3520 return;
3521 }
3522
3523 EXPECT_TRUE(matches("[[noreturn]] void func();", functionDecl(isNoReturn())));
3524 EXPECT_TRUE(
3525 matches("[[noreturn]] void func() {}", functionDecl(isNoReturn())));
3526
3527 EXPECT_TRUE(matches("struct S { [[noreturn]] void func(); };",
3528 functionDecl(isNoReturn())));
3529 EXPECT_TRUE(matches("struct S { [[noreturn]] void func() {} };",
3530 functionDecl(isNoReturn())));
3531
3532 EXPECT_TRUE(matches("struct S { [[noreturn]] static void func(); };",
3533 functionDecl(isNoReturn())));
3534 EXPECT_TRUE(matches("struct S { [[noreturn]] static void func() {} };",
3535 functionDecl(isNoReturn())));
3536
3537 EXPECT_TRUE(
3538 matches("struct S { [[noreturn]] S(); };", functionDecl(isNoReturn())));
3539 EXPECT_TRUE(
3540 matches("struct S { [[noreturn]] S() {} };", functionDecl(isNoReturn())));
3541 }
3542
3543 TEST_P(ASTMatchersTest, BooleanType) {
3544 if (!GetParam().isCXX()) {
3545 // FIXME: Add a test for `booleanType()` that does not depend on C++.
3546 return;
3547 }
3548
3549 EXPECT_TRUE(matches("struct S { bool func(); };",
3550 cxxMethodDecl(returns(booleanType()))));
3551 EXPECT_TRUE(notMatches("struct S { void func(); };",
3552 cxxMethodDecl(returns(booleanType()))));
3553 }
3554
3555 TEST_P(ASTMatchersTest, VoidType) {
3556 if (!GetParam().isCXX()) {
3557 // FIXME: Add a test for `voidType()` that does not depend on C++.
3558 return;
3559 }
3560
3561 EXPECT_TRUE(matches("struct S { void func(); };",
3562 cxxMethodDecl(returns(voidType()))));
3563 }
3564
3565 TEST_P(ASTMatchersTest, RealFloatingPointType) {
3566 if (!GetParam().isCXX()) {
3567 // FIXME: Add a test for `realFloatingPointType()` that does not depend on
3568 // C++.
3569 return;
3570 }
3571
3572 EXPECT_TRUE(matches("struct S { float func(); };",
3573 cxxMethodDecl(returns(realFloatingPointType()))));
3574 EXPECT_TRUE(notMatches("struct S { int func(); };",
3575 cxxMethodDecl(returns(realFloatingPointType()))));
3576 EXPECT_TRUE(matches("struct S { long double func(); };",
3577 cxxMethodDecl(returns(realFloatingPointType()))));
3578 }
3579
3580 TEST_P(ASTMatchersTest, ArrayType) {
3581 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3582 EXPECT_TRUE(matches("int a[42];", arrayType()));
3583 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3584
3585 EXPECT_TRUE(notMatches("struct A {}; struct A a[7];",
3586 arrayType(hasElementType(builtinType()))));
3587
3588 EXPECT_TRUE(matches("int const a[] = { 2, 3 };",
3589 qualType(arrayType(hasElementType(builtinType())))));
3590 EXPECT_TRUE(matches(
3591 "int const a[] = { 2, 3 };",
3592 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3593 EXPECT_TRUE(matches("typedef const int T; T x[] = { 1, 2 };",
3594 qualType(isConstQualified(), arrayType())));
3595
3596 EXPECT_TRUE(notMatches(
3597 "int a[] = { 2, 3 };",
3598 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3599 EXPECT_TRUE(notMatches(
3600 "int a[] = { 2, 3 };",
3601 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3602 EXPECT_TRUE(notMatches("int const a[] = { 2, 3 };",
3603 qualType(arrayType(hasElementType(builtinType())),
3604 unless(isConstQualified()))));
3605
3606 EXPECT_TRUE(
3607 matches("int a[2];", constantArrayType(hasElementType(builtinType()))));
3608 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3609 }
3610
3611 TEST_P(ASTMatchersTest, DecayedType) {
3612 EXPECT_TRUE(
3613 matches("void f(int i[]);",
3614 valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
3615 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
3616 }
3617
3618 TEST_P(ASTMatchersTest, ComplexType) {
3619 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3620 EXPECT_TRUE(
3621 matches("_Complex float f;", complexType(hasElementType(builtinType()))));
3622 EXPECT_TRUE(notMatches("_Complex float f;",
3623 complexType(hasElementType(isInteger()))));
3624 }
3625
3626 TEST_P(ASTMatchersTest, IsAnonymous) {
3627 if (!GetParam().isCXX()) {
3628 return;
3629 }
3630
3631 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
3632 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
3633 }
3634
3635 TEST_P(ASTMatchersTest, InStdNamespace) {
3636 if (!GetParam().isCXX()) {
3637 return;
3638 }
3639
3640 EXPECT_TRUE(notMatches("class vector {};"
3641 "namespace foo {"
3642 " class vector {};"
3643 "}"
3644 "namespace foo {"
3645 " namespace std {"
3646 " class vector {};"
3647 " }"
3648 "}",
3649 cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3650
3651 EXPECT_TRUE(matches("namespace std {"
3652 " class vector {};"
3653 "}",
3654 cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3655
3656 EXPECT_TRUE(matches("namespace std {"
3657 " extern \"C++\" class vector {};"
3658 "}",
3659 cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3660 }
3661
3662 TEST_P(ASTMatchersTest, InAnonymousNamespace) {
3663 if (!GetParam().isCXX()) {
3664 return;
3665 }
3666
3667 EXPECT_TRUE(
3668 notMatches("class vector {};"
3669 "namespace foo {"
3670 " class vector {};"
3671 "}",
3672 cxxRecordDecl(hasName("vector"), isInAnonymousNamespace())));
3673
3674 EXPECT_TRUE(
3675 matches("namespace {"
3676 " class vector {};"
3677 "}",
3678 cxxRecordDecl(hasName("vector"), isInAnonymousNamespace())));
3679
3680 EXPECT_TRUE(
3681 matches("namespace foo {"
3682 " namespace {"
3683 " class vector {};"
3684 " }"
3685 "}",
3686 cxxRecordDecl(hasName("vector"), isInAnonymousNamespace())));
3687
3688 EXPECT_TRUE(
3689 matches("namespace {"
3690 " namespace foo {"
3691 " class vector {};"
3692 " }"
3693 "}",
3694 cxxRecordDecl(hasName("vector"), isInAnonymousNamespace())));
3695 }
3696
3697 TEST_P(ASTMatchersTest, InStdNamespace_CXX11) {
3698 if (!GetParam().isCXX11OrLater()) {
3699 return;
3700 }
3701
3702 EXPECT_TRUE(matches("namespace std {"
3703 " inline namespace __1 {"
3704 " class vector {};"
3705 " }"
3706 "}",
3707 cxxRecordDecl(hasName("vector"), isInStdNamespace())));
3708 EXPECT_TRUE(notMatches("namespace std {"
3709 " inline namespace __1 {"
3710 " inline namespace __fs {"
3711 " namespace filesystem {"
3712 " inline namespace v1 {"
3713 " class path {};"
3714 " }"
3715 " }"
3716 " }"
3717 " }"
3718 "}",
3719 cxxRecordDecl(hasName("path"), isInStdNamespace())));
3720 EXPECT_TRUE(
3721 matches("namespace std {"
3722 " inline namespace __1 {"
3723 " inline namespace __fs {"
3724 " namespace filesystem {"
3725 " inline namespace v1 {"
3726 " class path {};"
3727 " }"
3728 " }"
3729 " }"
3730 " }"
3731 "}",
3732 cxxRecordDecl(hasName("path"),
3733 hasAncestor(namespaceDecl(hasName("filesystem"),
3734 isInStdNamespace())))));
3735 }
3736
3737 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_QualType) {
3738 EXPECT_TRUE(matches(
3739 "int i = 1;", varDecl(hasType(qualType().bind("type")),
3740 hasInitializer(ignoringParenImpCasts(
3741 hasType(qualType(equalsBoundNode("type"))))))));
3742 EXPECT_TRUE(notMatches("int i = 1.f;",
3743 varDecl(hasType(qualType().bind("type")),
3744 hasInitializer(ignoringParenImpCasts(hasType(
3745 qualType(equalsBoundNode("type"))))))));
3746 }
3747
3748 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_NonMatchingTypes) {
3749 EXPECT_TRUE(notMatches(
3750 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
3751 hasInitializer(ignoringParenImpCasts(
3752 hasType(qualType(equalsBoundNode("type"))))))));
3753 }
3754
3755 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Stmt) {
3756 EXPECT_TRUE(
3757 matches("void f() { if(1) {} }",
3758 stmt(allOf(ifStmt().bind("if"),
3759 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
3760
3761 EXPECT_TRUE(notMatches(
3762 "void f() { if(1) { if (1) {} } }",
3763 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
3764 }
3765
3766 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Decl) {
3767 if (!GetParam().isCXX()) {
3768 // FIXME: Add a test for `equalsBoundNode()` for declarations that does not
3769 // depend on C++.
3770 return;
3771 }
3772
3773 EXPECT_TRUE(matches(
3774 "class X { class Y {}; };",
3775 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
3776 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
3777
3778 EXPECT_TRUE(notMatches("class X { class Y {}; };",
3779 decl(allOf(recordDecl(hasName("::X")).bind("record"),
3780 has(decl(equalsBoundNode("record")))))));
3781 }
3782
3783 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_Type) {
3784 if (!GetParam().isCXX()) {
3785 // FIXME: Add a test for `equalsBoundNode()` for types that does not depend
3786 // on C++.
3787 return;
3788 }
3789 EXPECT_TRUE(matches(
3790 "class X { int a; int b; };",
3791 recordDecl(
3792 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3793 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
3794
3795 EXPECT_TRUE(notMatches(
3796 "class X { int a; double b; };",
3797 recordDecl(
3798 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3799 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
3800 }
3801
3802 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_UsingForEachDescendant) {
3803 EXPECT_TRUE(matchAndVerifyResultTrue(
3804 "int f() {"
3805 " if (1) {"
3806 " int i = 9;"
3807 " }"
3808 " int j = 10;"
3809 " {"
3810 " float k = 9.0;"
3811 " }"
3812 " return 0;"
3813 "}",
3814 // Look for variable declarations within functions whose type is the same
3815 // as the function return type.
3816 functionDecl(
3817 returns(qualType().bind("type")),
3818 forEachDescendant(varDecl(hasType(qualType(equalsBoundNode("type"))))
3819 .bind("decl"))),
3820 // Only i and j should match, not k.
3821 std::make_unique<VerifyIdIsBoundTo<VarDecl>>("decl", 2)));
3822 }
3823
3824 TEST_P(ASTMatchersTest, EqualsBoundNodeMatcher_FiltersMatchedCombinations) {
3825 EXPECT_TRUE(matchAndVerifyResultTrue(
3826 "void f() {"
3827 " int x;"
3828 " double d;"
3829 " x = d + x - d + x;"
3830 "}",
3831 functionDecl(
3832 hasName("f"), forEachDescendant(varDecl().bind("d")),
3833 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
3834 std::make_unique<VerifyIdIsBoundTo<VarDecl>>("d", 5)));
3835 }
3836
3837 TEST_P(ASTMatchersTest,
3838 EqualsBoundNodeMatcher_UnlessDescendantsOfAncestorsMatch) {
3839 EXPECT_TRUE(matchAndVerifyResultTrue(
3840 "struct StringRef { int size() const; const char* data() const; };"
3841 "void f(StringRef v) {"
3842 " v.data();"
3843 "}",
3844 cxxMemberCallExpr(
3845 callee(cxxMethodDecl(hasName("data"))),
3846 on(declRefExpr(to(
3847 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
3848 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
3849 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
3850 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
3851 .bind("data"),
3852 std::make_unique<VerifyIdIsBoundTo<Expr>>("data", 1)));
3853
3854 EXPECT_FALSE(matches(
3855 "struct StringRef { int size() const; const char* data() const; };"
3856 "void f(StringRef v) {"
3857 " v.data();"
3858 " v.size();"
3859 "}",
3860 cxxMemberCallExpr(
3861 callee(cxxMethodDecl(hasName("data"))),
3862 on(declRefExpr(to(
3863 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
3864 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
3865 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
3866 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
3867 .bind("data")));
3868 }
3869
3870 TEST_P(ASTMatchersTest, NullPointerConstant) {
3871 EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
3872 "void *v1 = NULL;",
3873 expr(nullPointerConstant())));
3874 EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
3875 EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
3876 EXPECT_FALSE(matches("int i = 0;", expr(nullPointerConstant())));
3877 }
3878
3879 TEST_P(ASTMatchersTest, NullPointerConstant_GNUNull) {
3880 if (!GetParam().isCXX()) {
3881 return;
3882 }
3883
3884 EXPECT_TRUE(matches("void *p = __null;", expr(nullPointerConstant())));
3885 }
3886
3887 TEST_P(ASTMatchersTest, NullPointerConstant_GNUNullInTemplate) {
3888 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
3889 // FIXME: Fix this test to work with delayed template parsing.
3890 return;
3891 }
3892
3893 const char kTest[] = R"(
3894 template <typename T>
3895 struct MyTemplate {
3896 MyTemplate() : field_(__null) {}
3897 T* field_;
3898 };
3899 )";
3900 EXPECT_TRUE(matches(kTest, expr(nullPointerConstant())));
3901 }
3902
3903 TEST_P(ASTMatchersTest, NullPointerConstant_CXX11Nullptr) {
3904 if (!GetParam().isCXX11OrLater()) {
3905 return;
3906 }
3907
3908 EXPECT_TRUE(matches("void *p = nullptr;", expr(nullPointerConstant())));
3909 }
3910
3911 TEST_P(ASTMatchersTest, HasExternalFormalLinkage) {
3912 EXPECT_TRUE(matches("int a = 0;",
3913 namedDecl(hasName("a"), hasExternalFormalLinkage())));
3914 EXPECT_TRUE(notMatches("static int a = 0;",
3915 namedDecl(hasName("a"), hasExternalFormalLinkage())));
3916 EXPECT_TRUE(notMatches("static void f(void) { int a = 0; }",
3917 namedDecl(hasName("a"), hasExternalFormalLinkage())));
3918 EXPECT_TRUE(notMatches("void f(void) { int a = 0; }",
3919 namedDecl(hasName("a"), hasExternalFormalLinkage())));
3920 }
3921
3922 TEST_P(ASTMatchersTest, HasExternalFormalLinkage_CXX) {
3923 if (!GetParam().isCXX()) {
3924 return;
3925 }
3926
3927 EXPECT_TRUE(notMatches("namespace { int a = 0; }",
3928 namedDecl(hasName("a"), hasExternalFormalLinkage())));
3929 }
3930
3931 TEST_P(ASTMatchersTest, HasDefaultArgument) {
3932 if (!GetParam().isCXX()) {
3933 return;
3934 }
3935
3936 EXPECT_TRUE(
3937 matches("void x(int val = 0) {}", parmVarDecl(hasDefaultArgument())));
3938 EXPECT_TRUE(
3939 notMatches("void x(int val) {}", parmVarDecl(hasDefaultArgument())));
3940 }
3941
3942 TEST_P(ASTMatchersTest, IsAtPosition) {
3943 EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(1))));
3944 EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(0))));
3945 EXPECT_TRUE(matches("void x(int a, int b) {}", parmVarDecl(isAtPosition(1))));
3946 EXPECT_TRUE(notMatches("void x(int val) {}", parmVarDecl(isAtPosition(1))));
3947 }
3948
3949 TEST_P(ASTMatchersTest, IsAtPosition_FunctionDecl) {
3950 EXPECT_TRUE(matches("void x(int a);", parmVarDecl(isAtPosition(0))));
3951 EXPECT_TRUE(matches("void x(int a, int b);", parmVarDecl(isAtPosition(0))));
3952 EXPECT_TRUE(matches("void x(int a, int b);", parmVarDecl(isAtPosition(1))));
3953 EXPECT_TRUE(notMatches("void x(int val);", parmVarDecl(isAtPosition(1))));
3954 }
3955
3956 TEST_P(ASTMatchersTest, IsAtPosition_Lambda) {
3957 if (!GetParam().isCXX11OrLater()) {
3958 return;
3959 }
3960
3961 EXPECT_TRUE(
3962 matches("void x() { [](int a) {}; }", parmVarDecl(isAtPosition(0))));
3963 EXPECT_TRUE(matches("void x() { [](int a, int b) {}; }",
3964 parmVarDecl(isAtPosition(0))));
3965 EXPECT_TRUE(matches("void x() { [](int a, int b) {}; }",
3966 parmVarDecl(isAtPosition(1))));
3967 EXPECT_TRUE(
3968 notMatches("void x() { [](int val) {}; }", parmVarDecl(isAtPosition(1))));
3969 }
3970
3971 TEST_P(ASTMatchersTest, IsAtPosition_BlockDecl) {
3972 EXPECT_TRUE(matchesObjC(
3973 "void func() { void (^my_block)(int arg) = ^void(int arg) {}; } ",
3974 parmVarDecl(isAtPosition(0))));
3975
3976 EXPECT_TRUE(matchesObjC("void func() { void (^my_block)(int x, int y) = "
3977 "^void(int x, int y) {}; } ",
3978 parmVarDecl(isAtPosition(1))));
3979
3980 EXPECT_TRUE(notMatchesObjC(
3981 "void func() { void (^my_block)(int arg) = ^void(int arg) {}; } ",
3982 parmVarDecl(isAtPosition(1))));
3983 }
3984
3985 TEST_P(ASTMatchersTest, IsArray) {
3986 if (!GetParam().isCXX()) {
3987 return;
3988 }
3989
3990 EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
3991 cxxNewExpr(isArray())));
3992 }
3993
3994 TEST_P(ASTMatchersTest, HasArraySize) {
3995 if (!GetParam().isCXX()) {
3996 return;
3997 }
3998
3999 EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
4000 cxxNewExpr(hasArraySize(
4001 ignoringParenImpCasts(integerLiteral(equals(10)))))));
4002 }
4003
4004 TEST_P(ASTMatchersTest, HasDefinition_MatchesStructDefinition) {
4005 if (!GetParam().isCXX()) {
4006 return;
4007 }
4008
4009 EXPECT_TRUE(matches("struct x {};", cxxRecordDecl(hasDefinition())));
4010 EXPECT_TRUE(notMatches("struct x;", cxxRecordDecl(hasDefinition())));
4011 }
4012
4013 TEST_P(ASTMatchersTest, HasDefinition_MatchesClassDefinition) {
4014 if (!GetParam().isCXX()) {
4015 return;
4016 }
4017
4018 EXPECT_TRUE(matches("class x {};", cxxRecordDecl(hasDefinition())));
4019 EXPECT_TRUE(notMatches("class x;", cxxRecordDecl(hasDefinition())));
4020 }
4021
4022 TEST_P(ASTMatchersTest, HasDefinition_MatchesUnionDefinition) {
4023 if (!GetParam().isCXX()) {
4024 return;
4025 }
4026
4027 EXPECT_TRUE(matches("union x {};", cxxRecordDecl(hasDefinition())));
4028 EXPECT_TRUE(notMatches("union x;", cxxRecordDecl(hasDefinition())));
4029 }
4030
4031 TEST_P(ASTMatchersTest, IsScoped_MatchesScopedEnum) {
4032 if (!GetParam().isCXX11OrLater()) {
4033 return;
4034 }
4035 EXPECT_TRUE(matches("enum class X {};", enumDecl(isScoped())));
4036 }
4037
4038 TEST_P(ASTMatchersTest, IsScoped_NotMatchesRegularEnum) {
4039 EXPECT_TRUE(notMatches("enum E { E1 };", enumDecl(isScoped())));
4040 }
4041
4042 TEST_P(ASTMatchersTest, IsStruct) {
4043 EXPECT_TRUE(matches("struct S {};", tagDecl(isStruct())));
4044 }
4045
4046 TEST_P(ASTMatchersTest, IsUnion) {
4047 EXPECT_TRUE(matches("union U {};", tagDecl(isUnion())));
4048 }
4049
4050 TEST_P(ASTMatchersTest, IsEnum) {
4051 EXPECT_TRUE(matches("enum E { E1 };", tagDecl(isEnum())));
4052 }
4053
4054 TEST_P(ASTMatchersTest, IsClass) {
4055 if (!GetParam().isCXX()) {
4056 return;
4057 }
4058
4059 EXPECT_TRUE(matches("class C {};", tagDecl(isClass())));
4060 }
4061
4062 TEST_P(ASTMatchersTest, HasTrailingReturn_MatchesTrailingReturn) {
4063 if (!GetParam().isCXX11OrLater()) {
4064 return;
4065 }
4066
4067 EXPECT_TRUE(matches("auto Y() -> int { return 0; }",
4068 functionDecl(hasTrailingReturn())));
4069 EXPECT_TRUE(matches("auto X() -> int;", functionDecl(hasTrailingReturn())));
4070 EXPECT_TRUE(
4071 notMatches("int X() { return 0; }", functionDecl(hasTrailingReturn())));
4072 EXPECT_TRUE(notMatches("int X();", functionDecl(hasTrailingReturn())));
4073 EXPECT_TRUE(notMatches("void X();", functionDecl(hasTrailingReturn())));
4074 }
4075
4076 TEST_P(ASTMatchersTest, HasTrailingReturn_MatchesLambdaTrailingReturn) {
4077 if (!GetParam().isCXX11OrLater()) {
4078 return;
4079 }
4080
4081 EXPECT_TRUE(matches(
4082 "auto lambda2 = [](double x, double y) -> double {return x + y;};",
4083 functionDecl(hasTrailingReturn())));
4084 EXPECT_TRUE(
4085 notMatches("auto lambda2 = [](double x, double y) {return x + y;};",
4086 functionDecl(hasTrailingReturn())));
4087 }
4088
4089 TEST_P(ASTMatchersTest, IsAssignmentOperator) {
4090 if (!GetParam().isCXX()) {
4091 return;
4092 }
4093
4094 StatementMatcher BinAsgmtOperator = binaryOperator(isAssignmentOperator());
4095 StatementMatcher CXXAsgmtOperator =
4096 cxxOperatorCallExpr(isAssignmentOperator());
4097
4098 EXPECT_TRUE(matches("void x() { int a; a += 1; }", BinAsgmtOperator));
4099 EXPECT_TRUE(matches("void x() { int a; a = 2; }", BinAsgmtOperator));
4100 EXPECT_TRUE(matches("void x() { int a; a &= 3; }", BinAsgmtOperator));
4101 EXPECT_TRUE(matches("struct S { S& operator=(const S&); };"
4102 "void x() { S s1, s2; s1 = s2; }",
4103 CXXAsgmtOperator));
4104 EXPECT_TRUE(
4105 notMatches("void x() { int a; if(a == 0) return; }", BinAsgmtOperator));
4106 }
4107
4108 TEST_P(ASTMatchersTest, IsComparisonOperator) {
4109 if (!GetParam().isCXX()) {
4110 return;
4111 }
4112
4113 StatementMatcher BinCompOperator = binaryOperator(isComparisonOperator());
4114 StatementMatcher CXXCompOperator =
4115 cxxOperatorCallExpr(isComparisonOperator());
4116
4117 EXPECT_TRUE(matches("void x() { int a; a == 1; }", BinCompOperator));
4118 EXPECT_TRUE(matches("void x() { int a; a > 2; }", BinCompOperator));
4119 EXPECT_TRUE(matches("struct S { bool operator==(const S&); };"
4120 "void x() { S s1, s2; bool b1 = s1 == s2; }",
4121 CXXCompOperator));
4122 EXPECT_TRUE(
4123 notMatches("void x() { int a; if(a = 0) return; }", BinCompOperator));
4124 }
4125
4126 TEST_P(ASTMatchersTest, isRightFold) {
4127 if (!GetParam().isCXX17OrLater()) {
4128 return;
4129 }
4130
4131 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4132 "return (0 + ... + args); }",
4133 cxxFoldExpr(isRightFold())));
4134 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4135 "return (args + ... + 0); }",
4136 cxxFoldExpr(isRightFold())));
4137 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4138 "return (... + args); };",
4139 cxxFoldExpr(isRightFold())));
4140 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4141 "return (args + ...); };",
4142 cxxFoldExpr(isRightFold())));
4143 }
4144
4145 TEST_P(ASTMatchersTest, isLeftFold) {
4146 if (!GetParam().isCXX17OrLater()) {
4147 return;
4148 }
4149
4150 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4151 "return (0 + ... + args); }",
4152 cxxFoldExpr(isLeftFold())));
4153 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4154 "return (args + ... + 0); }",
4155 cxxFoldExpr(isLeftFold())));
4156 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4157 "return (... + args); };",
4158 cxxFoldExpr(isLeftFold())));
4159 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4160 "return (args + ...); };",
4161 cxxFoldExpr(isLeftFold())));
4162 }
4163
4164 TEST_P(ASTMatchersTest, isUnaryFold) {
4165 if (!GetParam().isCXX17OrLater()) {
4166 return;
4167 }
4168
4169 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4170 "return (0 + ... + args); }",
4171 cxxFoldExpr(isUnaryFold())));
4172 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4173 "return (args + ... + 0); }",
4174 cxxFoldExpr(isUnaryFold())));
4175 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4176 "return (... + args); };",
4177 cxxFoldExpr(isUnaryFold())));
4178 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4179 "return (args + ...); };",
4180 cxxFoldExpr(isUnaryFold())));
4181 }
4182
4183 TEST_P(ASTMatchersTest, isBinaryFold) {
4184 if (!GetParam().isCXX17OrLater()) {
4185 return;
4186 }
4187
4188 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4189 "return (0 + ... + args); }",
4190 cxxFoldExpr(isBinaryFold())));
4191 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4192 "return (args + ... + 0); }",
4193 cxxFoldExpr(isBinaryFold())));
4194 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4195 "return (... + args); };",
4196 cxxFoldExpr(isBinaryFold())));
4197 EXPECT_FALSE(matches("template <typename... Args> auto sum(Args... args) { "
4198 "return (args + ...); };",
4199 cxxFoldExpr(isBinaryFold())));
4200 }
4201
4202 TEST_P(ASTMatchersTest, hasOperator) {
4203 if (!GetParam().isCXX17OrLater()) {
4204 return;
4205 }
4206
4207 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4208 "return (0 + ... + args); }",
4209 cxxFoldExpr(hasOperatorName("+"))));
4210 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
4211 "return (... + args); };",
4212 cxxFoldExpr(hasOperatorName("+"))));
4213
4214 EXPECT_FALSE(
4215 matches("template <typename... Args> auto multiply(Args... args) { "
4216 "return (0 * ... * args); }",
4217 cxxFoldExpr(hasOperatorName("+"))));
4218 EXPECT_FALSE(
4219 matches("template <typename... Args> auto multiply(Args... args) { "
4220 "return (... * args); };",
4221 cxxFoldExpr(hasOperatorName("+"))));
4222 }
4223
4224 TEST_P(ASTMatchersTest, IsMain) {
4225 EXPECT_TRUE(matches("int main() {}", functionDecl(isMain())));
4226
4227 EXPECT_TRUE(notMatches("int main2() {}", functionDecl(isMain())));
4228 }
4229
4230 TEST_P(ASTMatchersTest, OMPExecutableDirective_IsStandaloneDirective) {
4231 auto Matcher = ompExecutableDirective(isStandaloneDirective());
4232
4233 StringRef Source0 = R"(
4234 void x() {
4235 #pragma omp parallel
4236 ;
4237 })";
4238 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4239
4240 StringRef Source1 = R"(
4241 void x() {
4242 #pragma omp taskyield
4243 })";
4244 EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
4245 }
4246
4247 TEST_P(ASTMatchersTest, OMPExecutableDirective_HasStructuredBlock) {
4248 StringRef Source0 = R"(
4249 void x() {
4250 #pragma omp parallel
4251 ;
4252 })";
4253 EXPECT_TRUE(matchesWithOpenMP(
4254 Source0, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
4255
4256 StringRef Source1 = R"(
4257 void x() {
4258 #pragma omp parallel
4259 {;}
4260 })";
4261 EXPECT_TRUE(notMatchesWithOpenMP(
4262 Source1, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
4263 EXPECT_TRUE(matchesWithOpenMP(
4264 Source1, ompExecutableDirective(hasStructuredBlock(compoundStmt()))));
4265
4266 StringRef Source2 = R"(
4267 void x() {
4268 #pragma omp taskyield
4269 {;}
4270 })";
4271 EXPECT_TRUE(notMatchesWithOpenMP(
4272 Source2, ompExecutableDirective(hasStructuredBlock(anything()))));
4273 }
4274
4275 TEST_P(ASTMatchersTest, OMPExecutableDirective_HasClause) {
4276 auto Matcher = ompExecutableDirective(hasAnyClause(anything()));
4277
4278 StringRef Source0 = R"(
4279 void x() {
4280 ;
4281 })";
4282 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4283
4284 StringRef Source1 = R"(
4285 void x() {
4286 #pragma omp parallel
4287 ;
4288 })";
4289 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4290
4291 StringRef Source2 = R"(
4292 void x() {
4293 #pragma omp parallel default(none)
4294 ;
4295 })";
4296 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4297
4298 StringRef Source3 = R"(
4299 void x() {
4300 #pragma omp parallel default(shared)
4301 ;
4302 })";
4303 EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
4304
4305 StringRef Source4 = R"(
4306 void x() {
4307 #pragma omp parallel default(firstprivate)
4308 ;
4309 })";
4310 EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4311
4312 StringRef Source5 = R"(
4313 void x(int x) {
4314 #pragma omp parallel num_threads(x)
4315 ;
4316 })";
4317 EXPECT_TRUE(matchesWithOpenMP(Source5, Matcher));
4318 }
4319
4320 TEST_P(ASTMatchersTest, OMPDefaultClause_IsNoneKind) {
4321 auto Matcher =
4322 ompExecutableDirective(hasAnyClause(ompDefaultClause(isNoneKind())));
4323
4324 StringRef Source0 = R"(
4325 void x() {
4326 ;
4327 })";
4328 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4329
4330 StringRef Source1 = R"(
4331 void x() {
4332 #pragma omp parallel
4333 ;
4334 })";
4335 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4336
4337 StringRef Source2 = R"(
4338 void x() {
4339 #pragma omp parallel default(none)
4340 ;
4341 })";
4342 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4343
4344 StringRef Source3 = R"(
4345 void x() {
4346 #pragma omp parallel default(shared)
4347 ;
4348 })";
4349 EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4350
4351 StringRef Source4 = R"(
4352 void x(int x) {
4353 #pragma omp parallel default(firstprivate)
4354 ;
4355 })";
4356 EXPECT_TRUE(notMatchesWithOpenMP51(Source4, Matcher));
4357
4358 StringRef Source5 = R"(
4359 void x(int x) {
4360 #pragma omp parallel default(private)
4361 ;
4362 })";
4363 EXPECT_TRUE(notMatchesWithOpenMP51(Source5, Matcher));
4364
4365 const std::string Source6 = R"(
4366 void x(int x) {
4367 #pragma omp parallel num_threads(x)
4368 ;
4369 })";
4370 EXPECT_TRUE(notMatchesWithOpenMP(Source6, Matcher));
4371 }
4372
4373 TEST_P(ASTMatchersTest, OMPDefaultClause_IsSharedKind) {
4374 auto Matcher =
4375 ompExecutableDirective(hasAnyClause(ompDefaultClause(isSharedKind())));
4376
4377 StringRef Source0 = R"(
4378 void x() {
4379 ;
4380 })";
4381 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4382
4383 StringRef Source1 = R"(
4384 void x() {
4385 #pragma omp parallel
4386 ;
4387 })";
4388 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4389
4390 StringRef Source2 = R"(
4391 void x() {
4392 #pragma omp parallel default(shared)
4393 ;
4394 })";
4395 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4396
4397 StringRef Source3 = R"(
4398 void x() {
4399 #pragma omp parallel default(none)
4400 ;
4401 })";
4402 EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4403
4404 StringRef Source4 = R"(
4405 void x(int x) {
4406 #pragma omp parallel default(firstprivate)
4407 ;
4408 })";
4409 EXPECT_TRUE(notMatchesWithOpenMP51(Source4, Matcher));
4410
4411 StringRef Source5 = R"(
4412 void x(int x) {
4413 #pragma omp parallel default(private)
4414 ;
4415 })";
4416 EXPECT_TRUE(notMatchesWithOpenMP51(Source5, Matcher));
4417
4418 const std::string Source6 = R"(
4419 void x(int x) {
4420 #pragma omp parallel num_threads(x)
4421 ;
4422 })";
4423 EXPECT_TRUE(notMatchesWithOpenMP(Source6, Matcher));
4424 }
4425
4426 TEST(OMPDefaultClause, isFirstPrivateKind) {
4427 auto Matcher = ompExecutableDirective(
4428 hasAnyClause(ompDefaultClause(isFirstPrivateKind())));
4429
4430 const std::string Source0 = R"(
4431 void x() {
4432 ;
4433 })";
4434 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4435
4436 const std::string Source1 = R"(
4437 void x() {
4438 #pragma omp parallel
4439 ;
4440 })";
4441 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4442
4443 const std::string Source2 = R"(
4444 void x() {
4445 #pragma omp parallel default(shared)
4446 ;
4447 })";
4448 EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
4449
4450 const std::string Source3 = R"(
4451 void x() {
4452 #pragma omp parallel default(none)
4453 ;
4454 })";
4455 EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4456
4457 const std::string Source4 = R"(
4458 void x(int x) {
4459 #pragma omp parallel default(firstprivate)
4460 ;
4461 })";
4462 EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4463
4464 const std::string Source5 = R"(
4465 void x(int x) {
4466 #pragma omp parallel default(private)
4467 ;
4468 })";
4469 EXPECT_TRUE(notMatchesWithOpenMP51(Source5, Matcher));
4470
4471 const std::string Source6 = R"(
4472 void x(int x) {
4473 #pragma omp parallel num_threads(x)
4474 ;
4475 })";
4476 EXPECT_TRUE(notMatchesWithOpenMP(Source6, Matcher));
4477 }
4478
4479 TEST(OMPDefaultClause, istPrivateKind) {
4480 auto Matcher =
4481 ompExecutableDirective(hasAnyClause(ompDefaultClause(isPrivateKind())));
4482
4483 const std::string Source0 = R"(
4484 void x() {
4485 ;
4486 })";
4487 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4488
4489 const std::string Source1 = R"(
4490 void x() {
4491 #pragma omp parallel
4492 ;
4493 })";
4494 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
4495
4496 const std::string Source2 = R"(
4497 void x() {
4498 #pragma omp parallel default(shared)
4499 ;
4500 })";
4501 EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
4502
4503 const std::string Source3 = R"(
4504 void x() {
4505 #pragma omp parallel default(none)
4506 ;
4507 })";
4508 EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
4509
4510 const std::string Source4 = R"(
4511 void x(int x) {
4512 #pragma omp parallel default(firstprivate)
4513 ;
4514 })";
4515 EXPECT_TRUE(notMatchesWithOpenMP51(Source4, Matcher));
4516
4517 const std::string Source5 = R"(
4518 void x(int x) {
4519 #pragma omp parallel default(private)
4520 ;
4521 })";
4522 EXPECT_TRUE(matchesWithOpenMP51(Source5, Matcher));
4523
4524 const std::string Source6 = R"(
4525 void x(int x) {
4526 #pragma omp parallel num_threads(x)
4527 ;
4528 })";
4529 EXPECT_TRUE(notMatchesWithOpenMP(Source6, Matcher));
4530 }
4531
4532 TEST_P(ASTMatchersTest, OMPExecutableDirective_IsAllowedToContainClauseKind) {
4533 auto Matcher = ompExecutableDirective(
4534 isAllowedToContainClauseKind(llvm::omp::OMPC_default));
4535
4536 StringRef Source0 = R"(
4537 void x() {
4538 ;
4539 })";
4540 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
4541
4542 StringRef Source1 = R"(
4543 void x() {
4544 #pragma omp parallel
4545 ;
4546 })";
4547 EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
4548
4549 StringRef Source2 = R"(
4550 void x() {
4551 #pragma omp parallel default(none)
4552 ;
4553 })";
4554 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
4555
4556 StringRef Source3 = R"(
4557 void x() {
4558 #pragma omp parallel default(shared)
4559 ;
4560 })";
4561 EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
4562
4563 StringRef Source4 = R"(
4564 void x() {
4565 #pragma omp parallel default(firstprivate)
4566 ;
4567 })";
4568 EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
4569
4570 StringRef Source5 = R"(
4571 void x() {
4572 #pragma omp parallel default(private)
4573 ;
4574 })";
4575 EXPECT_TRUE(matchesWithOpenMP51(Source5, Matcher));
4576
4577 StringRef Source6 = R"(
4578 void x(int x) {
4579 #pragma omp parallel num_threads(x)
4580 ;
4581 })";
4582 EXPECT_TRUE(matchesWithOpenMP(Source6, Matcher));
4583
4584 StringRef Source7 = R"(
4585 void x() {
4586 #pragma omp taskyield
4587 })";
4588 EXPECT_TRUE(notMatchesWithOpenMP(Source7, Matcher));
4589
4590 StringRef Source8 = R"(
4591 void x() {
4592 #pragma omp task
4593 ;
4594 })";
4595 EXPECT_TRUE(matchesWithOpenMP(Source8, Matcher));
4596 }
4597
4598 TEST_P(ASTMatchersTest, HasAnyBase_DirectBase) {
4599 if (!GetParam().isCXX()) {
4600 return;
4601 }
4602 EXPECT_TRUE(matches(
4603 "struct Base {};"
4604 "struct ExpectedMatch : Base {};",
4605 cxxRecordDecl(hasName("ExpectedMatch"),
4606 hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))));
4607 }
4608
4609 TEST_P(ASTMatchersTest, HasAnyBase_IndirectBase) {
4610 if (!GetParam().isCXX()) {
4611 return;
4612 }
4613 EXPECT_TRUE(matches(
4614 "struct Base {};"
4615 "struct Intermediate : Base {};"
4616 "struct ExpectedMatch : Intermediate {};",
4617 cxxRecordDecl(hasName("ExpectedMatch"),
4618 hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))));
4619 }
4620
4621 TEST_P(ASTMatchersTest, HasAnyBase_NoBase) {
4622 if (!GetParam().isCXX()) {
4623 return;
4624 }
4625 EXPECT_TRUE(notMatches("struct Foo {};"
4626 "struct Bar {};",
4627 cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl())))));
4628 }
4629
4630 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Public) {
4631 if (!GetParam().isCXX()) {
4632 return;
4633 }
4634 EXPECT_TRUE(matches("class Base {};"
4635 "class Derived : public Base {};",
4636 cxxRecordDecl(hasAnyBase(isPublic()))));
4637 }
4638
4639 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_DefaultAccessSpecifierPublic) {
4640 if (!GetParam().isCXX()) {
4641 return;
4642 }
4643 EXPECT_TRUE(matches("class Base {};"
4644 "struct Derived : Base {};",
4645 cxxRecordDecl(hasAnyBase(isPublic()))));
4646 }
4647
4648 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Private) {
4649 if (!GetParam().isCXX()) {
4650 return;
4651 }
4652 EXPECT_TRUE(notMatches("class Base {};"
4653 "class Derived : private Base {};",
4654 cxxRecordDecl(hasAnyBase(isPublic()))));
4655 }
4656
4657 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_DefaultAccessSpecifierPrivate) {
4658 if (!GetParam().isCXX()) {
4659 return;
4660 }
4661 EXPECT_TRUE(notMatches("class Base {};"
4662 "class Derived : Base {};",
4663 cxxRecordDecl(hasAnyBase(isPublic()))));
4664 }
4665
4666 TEST_P(ASTMatchersTest, HasAnyBase_IsPublic_Protected) {
4667 if (!GetParam().isCXX()) {
4668 return;
4669 }
4670 EXPECT_TRUE(notMatches("class Base {};"
4671 "class Derived : protected Base {};",
4672 cxxRecordDecl(hasAnyBase(isPublic()))));
4673 }
4674
4675 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Private) {
4676 if (!GetParam().isCXX()) {
4677 return;
4678 }
4679 EXPECT_TRUE(matches("class Base {};"
4680 "class Derived : private Base {};",
4681 cxxRecordDecl(hasAnyBase(isPrivate()))));
4682 }
4683
4684 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_DefaultAccessSpecifierPrivate) {
4685 if (!GetParam().isCXX()) {
4686 return;
4687 }
4688 EXPECT_TRUE(matches("struct Base {};"
4689 "class Derived : Base {};",
4690 cxxRecordDecl(hasAnyBase(isPrivate()))));
4691 }
4692
4693 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Public) {
4694 if (!GetParam().isCXX()) {
4695 return;
4696 }
4697 EXPECT_TRUE(notMatches("class Base {};"
4698 "class Derived : public Base {};",
4699 cxxRecordDecl(hasAnyBase(isPrivate()))));
4700 }
4701
4702 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_DefaultAccessSpecifierPublic) {
4703 if (!GetParam().isCXX()) {
4704 return;
4705 }
4706 EXPECT_TRUE(notMatches("class Base {};"
4707 "struct Derived : Base {};",
4708 cxxRecordDecl(hasAnyBase(isPrivate()))));
4709 }
4710
4711 TEST_P(ASTMatchersTest, HasAnyBase_IsPrivate_Protected) {
4712 if (!GetParam().isCXX()) {
4713 return;
4714 }
4715 EXPECT_TRUE(notMatches("class Base {};"
4716 "class Derived : protected Base {};",
4717 cxxRecordDecl(hasAnyBase(isPrivate()))));
4718 }
4719
4720 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Protected) {
4721 if (!GetParam().isCXX()) {
4722 return;
4723 }
4724 EXPECT_TRUE(matches("class Base {};"
4725 "class Derived : protected Base {};",
4726 cxxRecordDecl(hasAnyBase(isProtected()))));
4727 }
4728
4729 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Public) {
4730 if (!GetParam().isCXX()) {
4731 return;
4732 }
4733 EXPECT_TRUE(notMatches("class Base {};"
4734 "class Derived : public Base {};",
4735 cxxRecordDecl(hasAnyBase(isProtected()))));
4736 }
4737
4738 TEST_P(ASTMatchersTest, HasAnyBase_IsProtected_Private) {
4739 if (!GetParam().isCXX()) {
4740 return;
4741 }
4742 EXPECT_TRUE(notMatches("class Base {};"
4743 "class Derived : private Base {};",
4744 cxxRecordDecl(hasAnyBase(isProtected()))));
4745 }
4746
4747 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_Directly) {
4748 if (!GetParam().isCXX()) {
4749 return;
4750 }
4751 EXPECT_TRUE(matches("class Base {};"
4752 "class Derived : virtual Base {};",
4753 cxxRecordDecl(hasAnyBase(isVirtual()))));
4754 }
4755
4756 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_Indirectly) {
4757 if (!GetParam().isCXX()) {
4758 return;
4759 }
4760 EXPECT_TRUE(
4761 matches("class Base {};"
4762 "class Intermediate : virtual Base {};"
4763 "class Derived : Intermediate {};",
4764 cxxRecordDecl(hasName("Derived"), hasAnyBase(isVirtual()))));
4765 }
4766
4767 TEST_P(ASTMatchersTest, HasAnyBase_IsVirtual_NoVirtualBase) {
4768 if (!GetParam().isCXX()) {
4769 return;
4770 }
4771 EXPECT_TRUE(notMatches("class Base {};"
4772 "class Derived : Base {};",
4773 cxxRecordDecl(hasAnyBase(isVirtual()))));
4774 }
4775
4776 TEST_P(ASTMatchersTest, HasDirectBase) {
4777 if (!GetParam().isCXX()) {
4778 return;
4779 }
4780
4781 DeclarationMatcher ClassHasAnyDirectBase =
4782 cxxRecordDecl(hasDirectBase(cxxBaseSpecifier()));
4783 EXPECT_TRUE(notMatches("class X {};", ClassHasAnyDirectBase));
4784 EXPECT_TRUE(matches("class X {}; class Y : X {};", ClassHasAnyDirectBase));
4785 EXPECT_TRUE(matches("class X {}; class Y : public virtual X {};",
4786 ClassHasAnyDirectBase));
4787
4788 EXPECT_TRUE(matches(
4789 R"cc(
4790 class Base {};
4791 class Derived : Base{};
4792 )cc",
4793 cxxRecordDecl(hasName("Derived"),
4794 hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4795
4796 StringRef MultiDerived = R"cc(
4797 class Base {};
4798 class Base2 {};
4799 class Derived : Base, Base2{};
4800 )cc";
4801
4802 EXPECT_TRUE(matches(
4803 MultiDerived,
4804 cxxRecordDecl(hasName("Derived"),
4805 hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4806 EXPECT_TRUE(matches(
4807 MultiDerived,
4808 cxxRecordDecl(hasName("Derived"),
4809 hasDirectBase(hasType(cxxRecordDecl(hasName("Base2")))))));
4810
4811 StringRef Indirect = R"cc(
4812 class Base {};
4813 class Intermediate : Base {};
4814 class Derived : Intermediate{};
4815 )cc";
4816
4817 EXPECT_TRUE(
4818 matches(Indirect, cxxRecordDecl(hasName("Derived"),
4819 hasDirectBase(hasType(cxxRecordDecl(
4820 hasName("Intermediate")))))));
4821 EXPECT_TRUE(notMatches(
4822 Indirect,
4823 cxxRecordDecl(hasName("Derived"),
4824 hasDirectBase(hasType(cxxRecordDecl(hasName("Base")))))));
4825 }
4826
4827 TEST_P(ASTMatchersTest, CapturesThis) {
4828 if (!GetParam().isCXX11OrLater()) {
4829 return;
4830 }
4831 auto matcher = lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())));
4832 EXPECT_TRUE(matches("class C { int cc; int f() { auto l = [this](){ return "
4833 "cc; }; return l(); } };",
4834 matcher));
4835 EXPECT_TRUE(matches("class C { int cc; int f() { auto l = [=](){ return cc; "
4836 "}; return l(); } };",
4837 matcher));
4838 EXPECT_TRUE(matches("class C { int cc; int f() { auto l = [&](){ return cc; "
4839 "}; return l(); } };",
4840 matcher));
4841 EXPECT_FALSE(matches("class C { int cc; int f() { auto l = [cc](){ return "
4842 "cc; }; return l(); } };",
4843 matcher));
4844 EXPECT_FALSE(matches("class C { int this; int f() { auto l = [this](){ "
4845 "return this; }; return l(); } };",
4846 matcher));
4847 }
4848
4849 TEST_P(ASTMatchersTest, IsImplicit_LambdaCapture) {
4850 if (!GetParam().isCXX11OrLater()) {
4851 return;
4852 }
4853 auto matcher = lambdaExpr(hasAnyCapture(
4854 lambdaCapture(isImplicit(), capturesVar(varDecl(hasName("cc"))))));
4855 EXPECT_TRUE(
4856 matches("int main() { int cc; auto f = [&](){ return cc; }; }", matcher));
4857 EXPECT_TRUE(
4858 matches("int main() { int cc; auto f = [=](){ return cc; }; }", matcher));
4859 EXPECT_FALSE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
4860 matcher));
4861 }
4862
4863 } // namespace ast_matchers
4864 } // namespace clang