blob: e304d0629cb3abffc79fd2e2a519a72a0ff804e7 [file] [log] [blame]
Piotr Padlewskic6e05022016-05-17 19:22:57 +00001// unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp - AST matcher unit tests//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ASTMatchersTest.h"
11#include "clang/AST/PrettyPrinter.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Tooling/Tooling.h"
15#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
17#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
22
23TEST(AllOf, AllOverloadsWork) {
24 const char Program[] =
25 "struct T { };"
26 "int f(int, T*, int, int);"
27 "void g(int x) { T t; f(x, &t, 3, 4); }";
28 EXPECT_TRUE(matches(Program,
29 callExpr(allOf(callee(functionDecl(hasName("f"))),
30 hasArgument(0, declRefExpr(to(varDecl())))))));
31 EXPECT_TRUE(matches(Program,
32 callExpr(allOf(callee(functionDecl(hasName("f"))),
33 hasArgument(0, declRefExpr(to(varDecl()))),
34 hasArgument(1, hasType(pointsTo(
35 recordDecl(hasName("T")))))))));
36 EXPECT_TRUE(matches(Program,
37 callExpr(allOf(callee(functionDecl(hasName("f"))),
38 hasArgument(0, declRefExpr(to(varDecl()))),
39 hasArgument(1, hasType(pointsTo(
40 recordDecl(hasName("T"))))),
41 hasArgument(2, integerLiteral(equals(3)))))));
42 EXPECT_TRUE(matches(Program,
43 callExpr(allOf(callee(functionDecl(hasName("f"))),
44 hasArgument(0, declRefExpr(to(varDecl()))),
45 hasArgument(1, hasType(pointsTo(
46 recordDecl(hasName("T"))))),
47 hasArgument(2, integerLiteral(equals(3))),
48 hasArgument(3, integerLiteral(equals(4)))))));
49}
50
51TEST(DeclarationMatcher, MatchHas) {
52 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
53 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
54 EXPECT_TRUE(matches("class X {};", HasClassX));
55
56 DeclarationMatcher YHasClassX =
57 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
58 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
59 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
60 EXPECT_TRUE(
61 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
62}
63
64TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
65 DeclarationMatcher Recursive =
66 recordDecl(
67 has(recordDecl(
68 has(recordDecl(hasName("X"))),
69 has(recordDecl(hasName("Y"))),
70 hasName("Z"))),
71 has(recordDecl(
72 has(recordDecl(hasName("A"))),
73 has(recordDecl(hasName("B"))),
74 hasName("C"))),
75 hasName("F"));
76
77 EXPECT_TRUE(matches(
78 "class F {"
79 " class Z {"
80 " class X {};"
81 " class Y {};"
82 " };"
83 " class C {"
84 " class A {};"
85 " class B {};"
86 " };"
87 "};", Recursive));
88
89 EXPECT_TRUE(matches(
90 "class F {"
91 " class Z {"
92 " class A {};"
93 " class X {};"
94 " class Y {};"
95 " };"
96 " class C {"
97 " class X {};"
98 " class A {};"
99 " class B {};"
100 " };"
101 "};", Recursive));
102
103 EXPECT_TRUE(matches(
104 "class O1 {"
105 " class O2 {"
106 " class F {"
107 " class Z {"
108 " class A {};"
109 " class X {};"
110 " class Y {};"
111 " };"
112 " class C {"
113 " class X {};"
114 " class A {};"
115 " class B {};"
116 " };"
117 " };"
118 " };"
119 "};", Recursive));
120}
121
122TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
123 DeclarationMatcher Recursive =
124 recordDecl(
125 anyOf(
126 has(recordDecl(
127 anyOf(
128 has(recordDecl(
129 hasName("X"))),
130 has(recordDecl(
131 hasName("Y"))),
132 hasName("Z")))),
133 has(recordDecl(
134 anyOf(
135 hasName("C"),
136 has(recordDecl(
137 hasName("A"))),
138 has(recordDecl(
139 hasName("B")))))),
140 hasName("F")));
141
142 EXPECT_TRUE(matches("class F {};", Recursive));
143 EXPECT_TRUE(matches("class Z {};", Recursive));
144 EXPECT_TRUE(matches("class C {};", Recursive));
145 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
146 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
147 EXPECT_TRUE(
148 matches("class O1 { class O2 {"
149 " class M { class N { class B {}; }; }; "
150 "}; };", Recursive));
151}
152
153TEST(DeclarationMatcher, MatchNot) {
154 DeclarationMatcher NotClassX =
155 cxxRecordDecl(
156 isDerivedFrom("Y"),
157 unless(hasName("X")));
158 EXPECT_TRUE(notMatches("", NotClassX));
159 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
160 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
161 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
162 EXPECT_TRUE(
163 notMatches("class Y {}; class Z {}; class X : public Y {};",
164 NotClassX));
165
166 DeclarationMatcher ClassXHasNotClassY =
167 recordDecl(
168 hasName("X"),
169 has(recordDecl(hasName("Z"))),
170 unless(
171 has(recordDecl(hasName("Y")))));
172 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
173 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
174 ClassXHasNotClassY));
175
176 DeclarationMatcher NamedNotRecord =
177 namedDecl(hasName("Foo"), unless(recordDecl()));
178 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
179 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
180}
181
182TEST(CastExpression, HasCastKind) {
183 EXPECT_TRUE(matches("char *p = 0;",
184 castExpr(hasCastKind(CK_NullToPointer))));
185 EXPECT_TRUE(notMatches("char *p = 0;",
186 castExpr(hasCastKind(CK_DerivedToBase))));
187 EXPECT_TRUE(matches("char *p = 0;",
188 implicitCastExpr(hasCastKind(CK_NullToPointer))));
189}
190
191TEST(DeclarationMatcher, HasDescendant) {
192 DeclarationMatcher ZDescendantClassX =
193 recordDecl(
194 hasDescendant(recordDecl(hasName("X"))),
195 hasName("Z"));
196 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
197 EXPECT_TRUE(
198 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
199 EXPECT_TRUE(
200 matches("class Z { class A { class Y { class X {}; }; }; };",
201 ZDescendantClassX));
202 EXPECT_TRUE(
203 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
204 ZDescendantClassX));
205 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
206
207 DeclarationMatcher ZDescendantClassXHasClassY =
208 recordDecl(
209 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
210 hasName("X"))),
211 hasName("Z"));
212 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
213 ZDescendantClassXHasClassY));
214 EXPECT_TRUE(
215 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
216 ZDescendantClassXHasClassY));
217 EXPECT_TRUE(notMatches(
218 "class Z {"
219 " class A {"
220 " class B {"
221 " class X {"
222 " class C {"
223 " class Y {};"
224 " };"
225 " };"
226 " }; "
227 " };"
228 "};", ZDescendantClassXHasClassY));
229
230 DeclarationMatcher ZDescendantClassXDescendantClassY =
231 recordDecl(
232 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
233 hasName("X"))),
234 hasName("Z"));
235 EXPECT_TRUE(
236 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
237 ZDescendantClassXDescendantClassY));
238 EXPECT_TRUE(matches(
239 "class Z {"
240 " class A {"
241 " class X {"
242 " class B {"
243 " class Y {};"
244 " };"
245 " class Y {};"
246 " };"
247 " };"
248 "};", ZDescendantClassXDescendantClassY));
249}
250
251TEST(DeclarationMatcher, HasDescendantMemoization) {
252 DeclarationMatcher CannotMemoize =
253 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
254 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
255}
256
257TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
258 auto Name = hasName("i");
259 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
260 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
261 // Matching VD first should not make a cache hit for RD.
262 EXPECT_TRUE(notMatches("void f() { int i; }",
263 decl(hasDescendant(VD), hasDescendant(RD))));
264 EXPECT_TRUE(notMatches("void f() { int i; }",
265 decl(hasDescendant(RD), hasDescendant(VD))));
266 // Not matching RD first should not make a cache hit for VD either.
267 EXPECT_TRUE(matches("void f() { int i; }",
268 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
269}
270
271TEST(DeclarationMatcher, HasAncestorMemoization) {
272 // This triggers an hasAncestor with a TemplateArgument in the bound nodes.
273 // That node can't be memoized so we have to check for it before trying to put
274 // it on the cache.
275 DeclarationMatcher CannotMemoize = classTemplateSpecializationDecl(
276 hasAnyTemplateArgument(templateArgument().bind("targ")),
277 forEach(fieldDecl(hasAncestor(forStmt()))));
278
279 EXPECT_TRUE(notMatches("template <typename T> struct S;"
280 "template <> struct S<int>{ int i; int j; };",
281 CannotMemoize));
282}
283
284TEST(DeclarationMatcher, HasAttr) {
285 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
286 decl(hasAttr(clang::attr::WarnUnused))));
287 EXPECT_FALSE(matches("struct X {};",
288 decl(hasAttr(clang::attr::WarnUnused))));
289}
290
291
292TEST(DeclarationMatcher, MatchAnyOf) {
293 DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
294 anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
295 EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
296 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
297 EXPECT_TRUE(
298 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
299 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
300
301 DeclarationMatcher XOrYOrZOrU =
302 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
303 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
304 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
305
306 DeclarationMatcher XOrYOrZOrUOrV =
307 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
308 hasName("V")));
309 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
310 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
311 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
312 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
313 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
314 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
315
316 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
317 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
318 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
319 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
320
321 EXPECT_TRUE(
322 matches("void f() try { } catch (int) { } catch (...) { }",
323 cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
324}
325
326TEST(DeclarationMatcher, ClassIsDerived) {
327 DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
328
329 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
330 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
331 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
332 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
333 EXPECT_TRUE(notMatches("", IsDerivedFromX));
334
335 DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
336
337 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
338 EXPECT_TRUE(matches("class X {};", IsAX));
339 EXPECT_TRUE(matches("class X;", IsAX));
340 EXPECT_TRUE(notMatches("class Y;", IsAX));
341 EXPECT_TRUE(notMatches("", IsAX));
342
343 DeclarationMatcher ZIsDerivedFromX =
344 cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
345 EXPECT_TRUE(
346 matches("class X {}; class Y : public X {}; class Z : public Y {};",
347 ZIsDerivedFromX));
348 EXPECT_TRUE(
349 matches("class X {};"
350 "template<class T> class Y : public X {};"
351 "class Z : public Y<int> {};", ZIsDerivedFromX));
352 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
353 ZIsDerivedFromX));
354 EXPECT_TRUE(
355 matches("template<class T> class X {}; "
356 "template<class T> class Z : public X<T> {};",
357 ZIsDerivedFromX));
358 EXPECT_TRUE(
359 matches("template<class T, class U=T> class X {}; "
360 "template<class T> class Z : public X<T> {};",
361 ZIsDerivedFromX));
362 EXPECT_TRUE(
363 notMatches("template<class X> class A { class Z : public X {}; };",
364 ZIsDerivedFromX));
365 EXPECT_TRUE(
366 matches("template<class X> class A { public: class Z : public X {}; }; "
367 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
368 EXPECT_TRUE(
369 matches("template <class T> class X {}; "
370 "template<class Y> class A { class Z : public X<Y> {}; };",
371 ZIsDerivedFromX));
372 EXPECT_TRUE(
373 notMatches("template<template<class T> class X> class A { "
374 " class Z : public X<int> {}; };", ZIsDerivedFromX));
375 EXPECT_TRUE(
376 matches("template<template<class T> class X> class A { "
377 " public: class Z : public X<int> {}; }; "
378 "template<class T> class X {}; void y() { A<X>::Z z; }",
379 ZIsDerivedFromX));
380 EXPECT_TRUE(
381 notMatches("template<class X> class A { class Z : public X::D {}; };",
382 ZIsDerivedFromX));
383 EXPECT_TRUE(
384 matches("template<class X> class A { public: "
385 " class Z : public X::D {}; }; "
386 "class Y { public: class X {}; typedef X D; }; "
387 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
388 EXPECT_TRUE(
389 matches("class X {}; typedef X Y; class Z : public Y {};",
390 ZIsDerivedFromX));
391 EXPECT_TRUE(
392 matches("template<class T> class Y { typedef typename T::U X; "
393 " class Z : public X {}; };", ZIsDerivedFromX));
394 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
395 ZIsDerivedFromX));
396 EXPECT_TRUE(
397 notMatches("template<class T> class X {}; "
398 "template<class T> class A { class Z : public X<T>::D {}; };",
399 ZIsDerivedFromX));
400 EXPECT_TRUE(
401 matches("template<class T> class X { public: typedef X<T> D; }; "
402 "template<class T> class A { public: "
403 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
404 ZIsDerivedFromX));
405 EXPECT_TRUE(
406 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
407 ZIsDerivedFromX));
408 EXPECT_TRUE(
409 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
410 ZIsDerivedFromX));
411 EXPECT_TRUE(
412 matches("class X {}; class Y : public X {}; "
413 "typedef Y V; typedef V W; class Z : public W {};",
414 ZIsDerivedFromX));
415 EXPECT_TRUE(
416 matches("template<class T, class U> class X {}; "
417 "template<class T> class A { class Z : public X<T, int> {}; };",
418 ZIsDerivedFromX));
419 EXPECT_TRUE(
420 notMatches("template<class X> class D { typedef X A; typedef A B; "
421 " typedef B C; class Z : public C {}; };",
422 ZIsDerivedFromX));
423 EXPECT_TRUE(
424 matches("class X {}; typedef X A; typedef A B; "
425 "class Z : public B {};", ZIsDerivedFromX));
426 EXPECT_TRUE(
427 matches("class X {}; typedef X A; typedef A B; typedef B C; "
428 "class Z : public C {};", ZIsDerivedFromX));
429 EXPECT_TRUE(
430 matches("class U {}; typedef U X; typedef X V; "
431 "class Z : public V {};", ZIsDerivedFromX));
432 EXPECT_TRUE(
433 matches("class Base {}; typedef Base X; "
434 "class Z : public Base {};", ZIsDerivedFromX));
435 EXPECT_TRUE(
436 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
437 "class Z : public Base {};", ZIsDerivedFromX));
438 EXPECT_TRUE(
439 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
440 "class Z : public Base {};", ZIsDerivedFromX));
441 EXPECT_TRUE(
442 matches("class A {}; typedef A X; typedef A Y; "
443 "class Z : public Y {};", ZIsDerivedFromX));
444 EXPECT_TRUE(
445 notMatches("template <typename T> class Z;"
446 "template <> class Z<void> {};"
447 "template <typename T> class Z : public Z<void> {};",
448 IsDerivedFromX));
449 EXPECT_TRUE(
450 matches("template <typename T> class X;"
451 "template <> class X<void> {};"
452 "template <typename T> class X : public X<void> {};",
453 IsDerivedFromX));
454 EXPECT_TRUE(matches(
455 "class X {};"
456 "template <typename T> class Z;"
457 "template <> class Z<void> {};"
458 "template <typename T> class Z : public Z<void>, public X {};",
459 ZIsDerivedFromX));
460 EXPECT_TRUE(
461 notMatches("template<int> struct X;"
462 "template<int i> struct X : public X<i-1> {};",
463 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
464 EXPECT_TRUE(matches(
465 "struct A {};"
466 "template<int> struct X;"
467 "template<int i> struct X : public X<i-1> {};"
468 "template<> struct X<0> : public A {};"
469 "struct B : public X<42> {};",
470 cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
471
472 // FIXME: Once we have better matchers for template type matching,
473 // get rid of the Variable(...) matching and match the right template
474 // declarations directly.
475 const char *RecursiveTemplateOneParameter =
476 "class Base1 {}; class Base2 {};"
477 "template <typename T> class Z;"
478 "template <> class Z<void> : public Base1 {};"
479 "template <> class Z<int> : public Base2 {};"
480 "template <> class Z<float> : public Z<void> {};"
481 "template <> class Z<double> : public Z<int> {};"
482 "template <typename T> class Z : public Z<float>, public Z<double> {};"
483 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
484 EXPECT_TRUE(matches(
485 RecursiveTemplateOneParameter,
486 varDecl(hasName("z_float"),
487 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
488 EXPECT_TRUE(notMatches(
489 RecursiveTemplateOneParameter,
490 varDecl(hasName("z_float"),
491 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
492 EXPECT_TRUE(matches(
493 RecursiveTemplateOneParameter,
494 varDecl(hasName("z_char"),
495 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
496 isDerivedFrom("Base2")))))));
497
498 const char *RecursiveTemplateTwoParameters =
499 "class Base1 {}; class Base2 {};"
500 "template <typename T1, typename T2> class Z;"
501 "template <typename T> class Z<void, T> : public Base1 {};"
502 "template <typename T> class Z<int, T> : public Base2 {};"
503 "template <typename T> class Z<float, T> : public Z<void, T> {};"
504 "template <typename T> class Z<double, T> : public Z<int, T> {};"
505 "template <typename T1, typename T2> class Z : "
506 " public Z<float, T2>, public Z<double, T2> {};"
507 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
508 " Z<char, void> z_char; }";
509 EXPECT_TRUE(matches(
510 RecursiveTemplateTwoParameters,
511 varDecl(hasName("z_float"),
512 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
513 EXPECT_TRUE(notMatches(
514 RecursiveTemplateTwoParameters,
515 varDecl(hasName("z_float"),
516 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
517 EXPECT_TRUE(matches(
518 RecursiveTemplateTwoParameters,
519 varDecl(hasName("z_char"),
520 hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
521 isDerivedFrom("Base2")))))));
522 EXPECT_TRUE(matches(
523 "namespace ns { class X {}; class Y : public X {}; }",
524 cxxRecordDecl(isDerivedFrom("::ns::X"))));
525 EXPECT_TRUE(notMatches(
526 "class X {}; class Y : public X {};",
527 cxxRecordDecl(isDerivedFrom("::ns::X"))));
528
529 EXPECT_TRUE(matches(
530 "class X {}; class Y : public X {};",
531 cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
532
533 EXPECT_TRUE(matches(
534 "template<typename T> class X {};"
535 "template<typename T> using Z = X<T>;"
536 "template <typename T> class Y : Z<T> {};",
537 cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
538}
539
540TEST(Matcher, BindMatchedNodes) {
541 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
542
543 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
544 ClassX, llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x")));
545
546 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
547 ClassX, llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("other-id")));
548
549 TypeMatcher TypeAHasClassB = hasDeclaration(
550 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
551
552 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
553 TypeAHasClassB,
554 llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
555
556 StatementMatcher MethodX =
557 callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
558
559 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
560 MethodX,
561 llvm::make_unique<VerifyIdIsBoundTo<CXXMemberCallExpr>>("x")));
562}
563
564TEST(Matcher, BindTheSameNameInAlternatives) {
565 StatementMatcher matcher = anyOf(
566 binaryOperator(hasOperatorName("+"),
567 hasLHS(expr().bind("x")),
568 hasRHS(integerLiteral(equals(0)))),
569 binaryOperator(hasOperatorName("+"),
570 hasLHS(integerLiteral(equals(0))),
571 hasRHS(expr().bind("x"))));
572
573 EXPECT_TRUE(matchAndVerifyResultTrue(
574 // The first branch of the matcher binds x to 0 but then fails.
575 // The second branch binds x to f() and succeeds.
576 "int f() { return 0 + f(); }",
577 matcher,
578 llvm::make_unique<VerifyIdIsBoundTo<CallExpr>>("x")));
579}
580
581TEST(Matcher, BindsIDForMemoizedResults) {
582 // Using the same matcher in two match expressions will make memoization
583 // kick in.
584 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
585 EXPECT_TRUE(matchAndVerifyResultTrue(
586 "class A { class B { class X {}; }; };",
587 DeclarationMatcher(anyOf(
588 recordDecl(hasName("A"), hasDescendant(ClassX)),
589 recordDecl(hasName("B"), hasDescendant(ClassX)))),
590 llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 2)));
591}
592
593TEST(HasType, MatchesAsString) {
594 EXPECT_TRUE(
595 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
596 cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
597 EXPECT_TRUE(
598 matches("class X { void x(int x) {} };",
599 cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
600 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
601 fieldDecl(hasType(asString("ns::A")))));
602 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
603 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
604}
605
606TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
607 StatementMatcher OpCallAndAnd =
608 cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
609 EXPECT_TRUE(matches("class Y { }; "
610 "bool operator&&(Y x, Y y) { return true; }; "
611 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
612 StatementMatcher OpCallLessLess =
613 cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
614 EXPECT_TRUE(notMatches("class Y { }; "
615 "bool operator&&(Y x, Y y) { return true; }; "
616 "Y a; Y b; bool c = a && b;",
617 OpCallLessLess));
618 StatementMatcher OpStarCall =
619 cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
620 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
621 OpStarCall));
622 DeclarationMatcher ClassWithOpStar =
623 cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
624 EXPECT_TRUE(matches("class Y { int operator*(); };",
625 ClassWithOpStar));
626 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
627 ClassWithOpStar)) ;
628 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
629 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
630 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
631}
632
633
634TEST(Matcher, NestedOverloadedOperatorCalls) {
635 EXPECT_TRUE(matchAndVerifyResultTrue(
636 "class Y { }; "
637 "Y& operator&&(Y& x, Y& y) { return x; }; "
638 "Y a; Y b; Y c; Y d = a && b && c;",
639 cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
640 llvm::make_unique<VerifyIdIsBoundTo<CXXOperatorCallExpr>>("x", 2)));
641 EXPECT_TRUE(matches("class Y { }; "
642 "Y& operator&&(Y& x, Y& y) { return x; }; "
643 "Y a; Y b; Y c; Y d = a && b && c;",
644 cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
645 EXPECT_TRUE(
646 matches("class Y { }; "
647 "Y& operator&&(Y& x, Y& y) { return x; }; "
648 "Y a; Y b; Y c; Y d = a && b && c;",
649 cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
650}
651
652TEST(Matcher, VarDecl_Storage) {
653 auto M = varDecl(hasName("X"), hasLocalStorage());
654 EXPECT_TRUE(matches("void f() { int X; }", M));
655 EXPECT_TRUE(notMatches("int X;", M));
656 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
657
658 M = varDecl(hasName("X"), hasGlobalStorage());
659 EXPECT_TRUE(notMatches("void f() { int X; }", M));
660 EXPECT_TRUE(matches("int X;", M));
661 EXPECT_TRUE(matches("void f() { static int X; }", M));
662}
663
664TEST(Matcher, VarDecl_StorageDuration) {
665 std::string T =
666 "void f() { int x; static int y; } int a;";
667
668 EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
669 EXPECT_TRUE(
670 notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
671 EXPECT_TRUE(
672 notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
673
674 EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
675 EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
676 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
677
678 // FIXME: It is really hard to test with thread_local itself because not all
679 // targets support TLS, which causes this to be an error depending on what
680 // platform the test is being run on. We do not have access to the TargetInfo
681 // object to be able to test whether the platform supports TLS or not.
682 EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
683 EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
684 EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
685}
686
687TEST(Matcher, FindsVarDeclInFunctionParameter) {
688 EXPECT_TRUE(matches(
689 "void f(int i) {}",
690 varDecl(hasName("i"))));
691}
692
693TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
694 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
695 hasArgumentOfType(asString("int")))));
696 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
697 hasArgumentOfType(asString("float")))));
698 EXPECT_TRUE(matches(
699 "struct A {}; void x() { A a; int b = sizeof(a); }",
700 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
701 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
702 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
703}
704
705TEST(IsInteger, MatchesIntegers) {
706 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
707 EXPECT_TRUE(matches(
708 "long long i = 0; void f(long long) { }; void g() {f(i);}",
709 callExpr(hasArgument(0, declRefExpr(
710 to(varDecl(hasType(isInteger()))))))));
711}
712
713TEST(IsInteger, ReportsNoFalsePositives) {
714 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
715 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
716 callExpr(hasArgument(0, declRefExpr(
717 to(varDecl(hasType(isInteger()))))))));
718}
719
720TEST(IsAnyPointer, MatchesPointers) {
721 EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
722}
723
724TEST(IsAnyPointer, MatchesObjcPointer) {
725 EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
726 varDecl(hasType(isAnyPointer()))));
727}
728
729TEST(IsAnyPointer, ReportsNoFalsePositives) {
730 EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
731}
732
733TEST(IsAnyCharacter, MatchesCharacters) {
734 EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
735}
736
737TEST(IsAnyCharacter, ReportsNoFalsePositives) {
738 EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
739}
740
741TEST(IsArrow, MatchesMemberVariablesViaArrow) {
742 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
743 memberExpr(isArrow())));
744 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
745 memberExpr(isArrow())));
746 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
747 memberExpr(isArrow())));
748}
749
750TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
751 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
752 memberExpr(isArrow())));
753 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
754 memberExpr(isArrow())));
755 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
756 memberExpr(isArrow())));
757}
758
759TEST(IsArrow, MatchesMemberCallsViaArrow) {
760 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
761 memberExpr(isArrow())));
762 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
763 memberExpr(isArrow())));
764 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
765 memberExpr(isArrow())));
766}
767
768TEST(ConversionDeclaration, IsExplicit) {
769 EXPECT_TRUE(matches("struct S { explicit operator int(); };",
770 cxxConversionDecl(isExplicit())));
771 EXPECT_TRUE(notMatches("struct S { operator int(); };",
772 cxxConversionDecl(isExplicit())));
773}
774
775TEST(Matcher, ArgumentCount) {
776 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
777
778 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
779 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
780 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
781}
782
783TEST(Matcher, ParameterCount) {
784 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
785 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
786 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
787 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
788 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
789 EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
790}
791
792TEST(Matcher, References) {
793 DeclarationMatcher ReferenceClassX = varDecl(
794 hasType(references(recordDecl(hasName("X")))));
795 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
796 ReferenceClassX));
797 EXPECT_TRUE(
798 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
799 // The match here is on the implicit copy constructor code for
800 // class X, not on code 'X x = y'.
801 EXPECT_TRUE(
802 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
803 EXPECT_TRUE(
804 notMatches("class X {}; extern X x;", ReferenceClassX));
805 EXPECT_TRUE(
806 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
807}
808
809TEST(QualType, hasLocalQualifiers) {
810 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
811 varDecl(hasType(hasLocalQualifiers()))));
812 EXPECT_TRUE(matches("int *const j = nullptr;",
813 varDecl(hasType(hasLocalQualifiers()))));
814 EXPECT_TRUE(matches("int *volatile k;",
815 varDecl(hasType(hasLocalQualifiers()))));
816 EXPECT_TRUE(notMatches("int m;",
817 varDecl(hasType(hasLocalQualifiers()))));
818}
819
820TEST(IsExternC, MatchesExternCFunctionDeclarations) {
821 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
822 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
823 functionDecl(isExternC())));
824 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
825}
826
827TEST(IsDefaulted, MatchesDefaultedFunctionDeclarations) {
828 EXPECT_TRUE(notMatches("class A { ~A(); };",
829 functionDecl(hasName("~A"), isDefaulted())));
830 EXPECT_TRUE(matches("class B { ~B() = default; };",
831 functionDecl(hasName("~B"), isDefaulted())));
832}
833
834TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
835 EXPECT_TRUE(
836 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
837 EXPECT_TRUE(matches("void Func() = delete;",
838 functionDecl(hasName("Func"), isDeleted())));
839}
840
841TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
842 EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
843 EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
844 EXPECT_TRUE(
845 notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
846 EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
847 EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
Aaron Ballman230ad972016-06-07 17:34:45 +0000848
849 EXPECT_TRUE(notMatches("void f();", functionProtoType(isNoThrow())));
850 EXPECT_TRUE(notMatches("void f() throw(int);", functionProtoType(isNoThrow())));
851 EXPECT_TRUE(
852 notMatches("void f() noexcept(false);", functionProtoType(isNoThrow())));
853 EXPECT_TRUE(matches("void f() throw();", functionProtoType(isNoThrow())));
854 EXPECT_TRUE(matches("void f() noexcept;", functionProtoType(isNoThrow())));
Piotr Padlewskic6e05022016-05-17 19:22:57 +0000855}
856
857TEST(isConstexpr, MatchesConstexprDeclarations) {
858 EXPECT_TRUE(matches("constexpr int foo = 42;",
859 varDecl(hasName("foo"), isConstexpr())));
860 EXPECT_TRUE(matches("constexpr int bar();",
861 functionDecl(hasName("bar"), isConstexpr())));
862}
863
864TEST(TemplateArgumentCountIs, Matches) {
865 EXPECT_TRUE(
866 matches("template<typename T> struct C {}; C<int> c;",
867 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
868 EXPECT_TRUE(
869 notMatches("template<typename T> struct C {}; C<int> c;",
870 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
871
872 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
873 templateSpecializationType(templateArgumentCountIs(1))));
874 EXPECT_TRUE(
875 notMatches("template<typename T> struct C {}; C<int> c;",
876 templateSpecializationType(templateArgumentCountIs(2))));
877}
878
879TEST(IsIntegral, Matches) {
880 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
881 classTemplateSpecializationDecl(
882 hasAnyTemplateArgument(isIntegral()))));
883 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
884 classTemplateSpecializationDecl(hasAnyTemplateArgument(
885 templateArgument(isIntegral())))));
886}
887
888TEST(EqualsIntegralValue, Matches) {
889 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
890 classTemplateSpecializationDecl(
891 hasAnyTemplateArgument(equalsIntegralValue("42")))));
892 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
893 classTemplateSpecializationDecl(
894 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
895 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
896 classTemplateSpecializationDecl(
897 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
898 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
899 classTemplateSpecializationDecl(hasAnyTemplateArgument(
900 equalsIntegralValue("0042")))));
901}
902
903TEST(Matcher, MatchesAccessSpecDecls) {
904 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
905 EXPECT_TRUE(
906 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
907 EXPECT_TRUE(
908 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
909 EXPECT_TRUE(
910 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
911
912 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
913}
914
915TEST(Matcher, MatchesFinal) {
916 EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
917 EXPECT_TRUE(matches("class X { virtual void f() final; };",
918 cxxMethodDecl(isFinal())));
919 EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
920 EXPECT_TRUE(
921 notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
922}
923
924TEST(Matcher, MatchesVirtualMethod) {
925 EXPECT_TRUE(matches("class X { virtual int f(); };",
926 cxxMethodDecl(isVirtual(), hasName("::X::f"))));
927 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
928}
929
930TEST(Matcher, MatchesVirtualAsWrittenMethod) {
931 EXPECT_TRUE(matches("class A { virtual int f(); };"
932 "class B : public A { int f(); };",
933 cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
934 EXPECT_TRUE(
935 notMatches("class A { virtual int f(); };"
936 "class B : public A { int f(); };",
937 cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
938}
939
940TEST(Matcher, MatchesPureMethod) {
941 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
942 cxxMethodDecl(isPure(), hasName("::X::f"))));
943 EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
944}
945
946TEST(Matcher, MatchesCopyAssignmentOperator) {
947 EXPECT_TRUE(matches("class X { X &operator=(X); };",
948 cxxMethodDecl(isCopyAssignmentOperator())));
949 EXPECT_TRUE(matches("class X { X &operator=(X &); };",
950 cxxMethodDecl(isCopyAssignmentOperator())));
951 EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
952 cxxMethodDecl(isCopyAssignmentOperator())));
953 EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
954 cxxMethodDecl(isCopyAssignmentOperator())));
955 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
956 cxxMethodDecl(isCopyAssignmentOperator())));
957 EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
958 cxxMethodDecl(isCopyAssignmentOperator())));
959}
960
961TEST(Matcher, MatchesMoveAssignmentOperator) {
962 EXPECT_TRUE(notMatches("class X { X &operator=(X); };",
963 cxxMethodDecl(isMoveAssignmentOperator())));
964 EXPECT_TRUE(matches("class X { X &operator=(X &&); };",
965 cxxMethodDecl(isMoveAssignmentOperator())));
966 EXPECT_TRUE(matches("class X { X &operator=(const X &&); };",
967 cxxMethodDecl(isMoveAssignmentOperator())));
968 EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };",
969 cxxMethodDecl(isMoveAssignmentOperator())));
970 EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
971 cxxMethodDecl(isMoveAssignmentOperator())));
972 EXPECT_TRUE(notMatches("class X { X &operator=(X &); };",
973 cxxMethodDecl(isMoveAssignmentOperator())));
974}
975
976TEST(Matcher, MatchesConstMethod) {
977 EXPECT_TRUE(
978 matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
979 EXPECT_TRUE(
980 notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
981}
982
983TEST(Matcher, MatchesOverridingMethod) {
984 EXPECT_TRUE(matches("class X { virtual int f(); }; "
985 "class Y : public X { int f(); };",
986 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
987 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
988 "class Y : public X { int f(); };",
989 cxxMethodDecl(isOverride(), hasName("::X::f"))));
990 EXPECT_TRUE(notMatches("class X { int f(); }; "
991 "class Y : public X { int f(); };",
992 cxxMethodDecl(isOverride())));
993 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
994 cxxMethodDecl(isOverride())));
995 EXPECT_TRUE(
996 matches("template <typename Base> struct Y : Base { void f() override;};",
997 cxxMethodDecl(isOverride(), hasName("::Y::f"))));
998}
999
1000TEST(Matcher, ConstructorArgument) {
1001 StatementMatcher Constructor = cxxConstructExpr(
1002 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
1003
1004 EXPECT_TRUE(
1005 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1006 Constructor));
1007 EXPECT_TRUE(
1008 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1009 Constructor));
1010 EXPECT_TRUE(
1011 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1012 Constructor));
1013 EXPECT_TRUE(
1014 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1015 Constructor));
1016
1017 StatementMatcher WrongIndex = cxxConstructExpr(
1018 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
1019 EXPECT_TRUE(
1020 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1021 WrongIndex));
1022}
1023
1024TEST(Matcher, ConstructorArgumentCount) {
1025 StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
1026
1027 EXPECT_TRUE(
1028 matches("class X { public: X(int); }; void x() { X x(0); }",
1029 Constructor1Arg));
1030 EXPECT_TRUE(
1031 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1032 Constructor1Arg));
1033 EXPECT_TRUE(
1034 matches("class X { public: X(int); }; void x() { X x = 0; }",
1035 Constructor1Arg));
1036 EXPECT_TRUE(
1037 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1038 Constructor1Arg));
1039}
1040
1041TEST(Matcher, ConstructorListInitialization) {
1042 StatementMatcher ConstructorListInit =
1043 cxxConstructExpr(isListInitialization());
1044
1045 EXPECT_TRUE(
1046 matches("class X { public: X(int); }; void x() { X x{0}; }",
1047 ConstructorListInit));
1048 EXPECT_FALSE(
1049 matches("class X { public: X(int); }; void x() { X x(0); }",
1050 ConstructorListInit));
1051}
1052
1053TEST(ConstructorDeclaration, IsImplicit) {
1054 // This one doesn't match because the constructor is not added by the
1055 // compiler (it is not needed).
1056 EXPECT_TRUE(notMatches("class Foo { };",
1057 cxxConstructorDecl(isImplicit())));
1058 // The compiler added the implicit default constructor.
1059 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
1060 cxxConstructorDecl(isImplicit())));
1061 EXPECT_TRUE(matches("class Foo { Foo(){} };",
1062 cxxConstructorDecl(unless(isImplicit()))));
1063 // The compiler added an implicit assignment operator.
1064 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1065 cxxMethodDecl(isImplicit(), hasName("operator="))));
1066}
1067
1068TEST(ConstructorDeclaration, IsExplicit) {
1069 EXPECT_TRUE(matches("struct S { explicit S(int); };",
1070 cxxConstructorDecl(isExplicit())));
1071 EXPECT_TRUE(notMatches("struct S { S(int); };",
1072 cxxConstructorDecl(isExplicit())));
1073}
1074
1075TEST(ConstructorDeclaration, Kinds) {
1076 EXPECT_TRUE(matches("struct S { S(); };",
1077 cxxConstructorDecl(isDefaultConstructor())));
1078 EXPECT_TRUE(notMatches("struct S { S(); };",
1079 cxxConstructorDecl(isCopyConstructor())));
1080 EXPECT_TRUE(notMatches("struct S { S(); };",
1081 cxxConstructorDecl(isMoveConstructor())));
1082
1083 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
1084 cxxConstructorDecl(isDefaultConstructor())));
1085 EXPECT_TRUE(matches("struct S { S(const S&); };",
1086 cxxConstructorDecl(isCopyConstructor())));
1087 EXPECT_TRUE(notMatches("struct S { S(const S&); };",
1088 cxxConstructorDecl(isMoveConstructor())));
1089
1090 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
1091 cxxConstructorDecl(isDefaultConstructor())));
1092 EXPECT_TRUE(notMatches("struct S { S(S&&); };",
1093 cxxConstructorDecl(isCopyConstructor())));
1094 EXPECT_TRUE(matches("struct S { S(S&&); };",
1095 cxxConstructorDecl(isMoveConstructor())));
1096}
1097
1098TEST(ConstructorDeclaration, IsUserProvided) {
1099 EXPECT_TRUE(notMatches("struct S { int X = 0; };",
1100 cxxConstructorDecl(isUserProvided())));
1101 EXPECT_TRUE(notMatches("struct S { S() = default; };",
1102 cxxConstructorDecl(isUserProvided())));
1103 EXPECT_TRUE(notMatches("struct S { S() = delete; };",
1104 cxxConstructorDecl(isUserProvided())));
1105 EXPECT_TRUE(
1106 matches("struct S { S(); };", cxxConstructorDecl(isUserProvided())));
1107 EXPECT_TRUE(matches("struct S { S(); }; S::S(){}",
1108 cxxConstructorDecl(isUserProvided())));
1109}
1110
1111TEST(ConstructorDeclaration, IsDelegatingConstructor) {
1112 EXPECT_TRUE(notMatches("struct S { S(); S(int); int X; };",
1113 cxxConstructorDecl(isDelegatingConstructor())));
1114 EXPECT_TRUE(notMatches("struct S { S(){} S(int X) : X(X) {} int X; };",
1115 cxxConstructorDecl(isDelegatingConstructor())));
1116 EXPECT_TRUE(matches(
1117 "struct S { S() : S(0) {} S(int X) : X(X) {} int X; };",
1118 cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(0))));
1119 EXPECT_TRUE(matches(
1120 "struct S { S(); S(int X); int X; }; S::S(int X) : S() {}",
1121 cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1))));
1122}
1123
1124TEST(StringLiteral, HasSize) {
1125 StatementMatcher Literal = stringLiteral(hasSize(4));
1126 EXPECT_TRUE(matches("const char *s = \"abcd\";", Literal));
1127 // wide string
1128 EXPECT_TRUE(matches("const wchar_t *s = L\"abcd\";", Literal));
1129 // with escaped characters
1130 EXPECT_TRUE(matches("const char *s = \"\x05\x06\x07\x08\";", Literal));
1131 // no matching, too small
1132 EXPECT_TRUE(notMatches("const char *s = \"ab\";", Literal));
1133}
1134
1135TEST(Matcher, HasNameSupportsNamespaces) {
1136 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1137 recordDecl(hasName("a::b::C"))));
1138 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1139 recordDecl(hasName("::a::b::C"))));
1140 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1141 recordDecl(hasName("b::C"))));
1142 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1143 recordDecl(hasName("C"))));
1144 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1145 recordDecl(hasName("c::b::C"))));
1146 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1147 recordDecl(hasName("a::c::C"))));
1148 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1149 recordDecl(hasName("a::b::A"))));
1150 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1151 recordDecl(hasName("::C"))));
1152 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1153 recordDecl(hasName("::b::C"))));
1154 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1155 recordDecl(hasName("z::a::b::C"))));
1156 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1157 recordDecl(hasName("a+b::C"))));
1158 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
1159 recordDecl(hasName("C"))));
1160}
1161
1162TEST(Matcher, HasNameSupportsOuterClasses) {
1163 EXPECT_TRUE(
1164 matches("class A { class B { class C; }; };",
1165 recordDecl(hasName("A::B::C"))));
1166 EXPECT_TRUE(
1167 matches("class A { class B { class C; }; };",
1168 recordDecl(hasName("::A::B::C"))));
1169 EXPECT_TRUE(
1170 matches("class A { class B { class C; }; };",
1171 recordDecl(hasName("B::C"))));
1172 EXPECT_TRUE(
1173 matches("class A { class B { class C; }; };",
1174 recordDecl(hasName("C"))));
1175 EXPECT_TRUE(
1176 notMatches("class A { class B { class C; }; };",
1177 recordDecl(hasName("c::B::C"))));
1178 EXPECT_TRUE(
1179 notMatches("class A { class B { class C; }; };",
1180 recordDecl(hasName("A::c::C"))));
1181 EXPECT_TRUE(
1182 notMatches("class A { class B { class C; }; };",
1183 recordDecl(hasName("A::B::A"))));
1184 EXPECT_TRUE(
1185 notMatches("class A { class B { class C; }; };",
1186 recordDecl(hasName("::C"))));
1187 EXPECT_TRUE(
1188 notMatches("class A { class B { class C; }; };",
1189 recordDecl(hasName("::B::C"))));
1190 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
1191 recordDecl(hasName("z::A::B::C"))));
1192 EXPECT_TRUE(
1193 notMatches("class A { class B { class C; }; };",
1194 recordDecl(hasName("A+B::C"))));
1195}
1196
1197TEST(Matcher, HasNameSupportsInlinedNamespaces) {
1198 std::string code = "namespace a { inline namespace b { class C; } }";
1199 EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
1200 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
1201 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
1202 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
1203}
1204
1205TEST(Matcher, HasNameSupportsAnonymousNamespaces) {
1206 std::string code = "namespace a { namespace { class C; } }";
1207 EXPECT_TRUE(
1208 matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
1209 EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
1210 EXPECT_TRUE(
1211 matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
1212 EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
1213}
1214
1215TEST(Matcher, HasNameSupportsAnonymousOuterClasses) {
1216 EXPECT_TRUE(matches("class A { class { class C; } x; };",
1217 recordDecl(hasName("A::(anonymous class)::C"))));
1218 EXPECT_TRUE(matches("class A { class { class C; } x; };",
1219 recordDecl(hasName("::A::(anonymous class)::C"))));
1220 EXPECT_FALSE(matches("class A { class { class C; } x; };",
1221 recordDecl(hasName("::A::C"))));
1222 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
1223 recordDecl(hasName("A::(anonymous struct)::C"))));
1224 EXPECT_TRUE(matches("class A { struct { class C; } x; };",
1225 recordDecl(hasName("::A::(anonymous struct)::C"))));
1226 EXPECT_FALSE(matches("class A { struct { class C; } x; };",
1227 recordDecl(hasName("::A::C"))));
1228}
1229
1230TEST(Matcher, HasNameSupportsFunctionScope) {
1231 std::string code =
1232 "namespace a { void F(int a) { struct S { int m; }; int i; } }";
1233 EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
1234 EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
1235
1236 EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
1237 EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
1238 EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
1239 EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
1240 EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
1241}
1242
1243TEST(Matcher, HasAnyName) {
1244 const std::string Code = "namespace a { namespace b { class C; } }";
1245
1246 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
1247 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
1248 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
1249 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
1250
1251 EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
1252 EXPECT_TRUE(
1253 matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
1254
1255 std::vector<StringRef> Names = {"::C", "::b::C", "::a::b::C"};
1256 EXPECT_TRUE(matches(Code, recordDecl(hasAnyName(Names))));
1257}
1258
1259TEST(Matcher, IsDefinition) {
1260 DeclarationMatcher DefinitionOfClassA =
1261 recordDecl(hasName("A"), isDefinition());
1262 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
1263 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
1264
1265 DeclarationMatcher DefinitionOfVariableA =
1266 varDecl(hasName("a"), isDefinition());
1267 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
1268 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
1269
1270 DeclarationMatcher DefinitionOfMethodA =
1271 cxxMethodDecl(hasName("a"), isDefinition());
1272 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
1273 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
1274}
1275
1276TEST(Matcher, HandlesNullQualTypes) {
1277 // FIXME: Add a Type matcher so we can replace uses of this
1278 // variable with Type(True())
1279 const TypeMatcher AnyType = anything();
1280
1281 // We don't really care whether this matcher succeeds; we're testing that
1282 // it completes without crashing.
1283 EXPECT_TRUE(matches(
1284 "struct A { };"
1285 "template <typename T>"
1286 "void f(T t) {"
1287 " T local_t(t /* this becomes a null QualType in the AST */);"
1288 "}"
1289 "void g() {"
1290 " f(0);"
1291 "}",
1292 expr(hasType(TypeMatcher(
1293 anyOf(
1294 TypeMatcher(hasDeclaration(anything())),
1295 pointsTo(AnyType),
1296 references(AnyType)
1297 // Other QualType matchers should go here.
1298 ))))));
1299}
1300
1301
1302TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
1303 EXPECT_TRUE(matches("void f() { }",
1304 compoundStmt(statementCountIs(0))));
1305 EXPECT_TRUE(notMatches("void f() {}",
1306 compoundStmt(statementCountIs(1))));
1307}
1308
1309TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
1310 EXPECT_TRUE(matches("void f() { 1; }",
1311 compoundStmt(statementCountIs(1))));
1312 EXPECT_TRUE(notMatches("void f() { 1; }",
1313 compoundStmt(statementCountIs(0))));
1314 EXPECT_TRUE(notMatches("void f() { 1; }",
1315 compoundStmt(statementCountIs(2))));
1316}
1317
1318TEST(StatementCountIs, WorksWithMultipleStatements) {
1319 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
1320 compoundStmt(statementCountIs(3))));
1321}
1322
1323TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
1324 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1325 compoundStmt(statementCountIs(1))));
1326 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1327 compoundStmt(statementCountIs(2))));
1328 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
1329 compoundStmt(statementCountIs(3))));
1330 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1331 compoundStmt(statementCountIs(4))));
1332}
1333
1334TEST(Member, WorksInSimplestCase) {
1335 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
1336 memberExpr(member(hasName("first")))));
1337}
1338
1339TEST(Member, DoesNotMatchTheBaseExpression) {
1340 // Don't pick out the wrong part of the member expression, this should
1341 // be checking the member (name) only.
1342 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
1343 memberExpr(member(hasName("first")))));
1344}
1345
1346TEST(Member, MatchesInMemberFunctionCall) {
1347 EXPECT_TRUE(matches("void f() {"
1348 " struct { void first() {}; } s;"
1349 " s.first();"
1350 "};",
1351 memberExpr(member(hasName("first")))));
1352}
1353
1354TEST(Member, MatchesMember) {
1355 EXPECT_TRUE(matches(
1356 "struct A { int i; }; void f() { A a; a.i = 2; }",
1357 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
1358 EXPECT_TRUE(notMatches(
1359 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
1360 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
1361}
1362
1363
1364TEST(Member, UnderstandsAccess) {
1365 EXPECT_TRUE(matches(
1366 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
1367 EXPECT_TRUE(notMatches(
1368 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
1369 EXPECT_TRUE(notMatches(
1370 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
1371
1372 EXPECT_TRUE(notMatches(
1373 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
1374 EXPECT_TRUE(notMatches(
1375 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
1376 EXPECT_TRUE(matches(
1377 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
1378
1379 EXPECT_TRUE(notMatches(
1380 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
1381 EXPECT_TRUE(matches("class A { protected: int i; };",
1382 fieldDecl(isProtected(), hasName("i"))));
1383 EXPECT_TRUE(notMatches(
1384 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
1385
1386 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
1387 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
1388 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
1389 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
1390}
1391
1392TEST(hasDynamicExceptionSpec, MatchesDynamicExceptionSpecifications) {
1393 EXPECT_TRUE(notMatches("void f();", functionDecl(hasDynamicExceptionSpec())));
1394 EXPECT_TRUE(notMatches("void g() noexcept;",
1395 functionDecl(hasDynamicExceptionSpec())));
1396 EXPECT_TRUE(notMatches("void h() noexcept(true);",
1397 functionDecl(hasDynamicExceptionSpec())));
1398 EXPECT_TRUE(notMatches("void i() noexcept(false);",
1399 functionDecl(hasDynamicExceptionSpec())));
1400 EXPECT_TRUE(
1401 matches("void j() throw();", functionDecl(hasDynamicExceptionSpec())));
1402 EXPECT_TRUE(
1403 matches("void k() throw(int);", functionDecl(hasDynamicExceptionSpec())));
1404 EXPECT_TRUE(
1405 matches("void l() throw(...);", functionDecl(hasDynamicExceptionSpec())));
Aaron Ballman230ad972016-06-07 17:34:45 +00001406
1407 EXPECT_TRUE(notMatches("void f();", functionProtoType(hasDynamicExceptionSpec())));
1408 EXPECT_TRUE(notMatches("void g() noexcept;",
1409 functionProtoType(hasDynamicExceptionSpec())));
1410 EXPECT_TRUE(notMatches("void h() noexcept(true);",
1411 functionProtoType(hasDynamicExceptionSpec())));
1412 EXPECT_TRUE(notMatches("void i() noexcept(false);",
1413 functionProtoType(hasDynamicExceptionSpec())));
1414 EXPECT_TRUE(
1415 matches("void j() throw();", functionProtoType(hasDynamicExceptionSpec())));
1416 EXPECT_TRUE(
1417 matches("void k() throw(int);", functionProtoType(hasDynamicExceptionSpec())));
1418 EXPECT_TRUE(
1419 matches("void l() throw(...);", functionProtoType(hasDynamicExceptionSpec())));
Piotr Padlewskic6e05022016-05-17 19:22:57 +00001420}
1421
1422TEST(HasObjectExpression, DoesNotMatchMember) {
1423 EXPECT_TRUE(notMatches(
1424 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
1425 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
1426}
1427
1428TEST(HasObjectExpression, MatchesBaseOfVariable) {
1429 EXPECT_TRUE(matches(
1430 "struct X { int m; }; void f(X x) { x.m; }",
1431 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
1432 EXPECT_TRUE(matches(
1433 "struct X { int m; }; void f(X* x) { x->m; }",
1434 memberExpr(hasObjectExpression(
1435 hasType(pointsTo(recordDecl(hasName("X"))))))));
1436}
1437
1438TEST(HasObjectExpression,
1439 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
1440 EXPECT_TRUE(matches(
1441 "class X {}; struct S { X m; void f() { this->m; } };",
1442 memberExpr(hasObjectExpression(
1443 hasType(pointsTo(recordDecl(hasName("S"))))))));
1444 EXPECT_TRUE(matches(
1445 "class X {}; struct S { X m; void f() { m; } };",
1446 memberExpr(hasObjectExpression(
1447 hasType(pointsTo(recordDecl(hasName("S"))))))));
1448}
1449
1450TEST(Field, DoesNotMatchNonFieldMembers) {
1451 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
1452 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
1453 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
1454 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
1455}
1456
1457TEST(Field, MatchesField) {
1458 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
1459}
1460
1461TEST(IsVolatileQualified, QualifiersMatch) {
1462 EXPECT_TRUE(matches("volatile int i = 42;",
1463 varDecl(hasType(isVolatileQualified()))));
1464 EXPECT_TRUE(notMatches("volatile int *i;",
1465 varDecl(hasType(isVolatileQualified()))));
1466 EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
1467 varDecl(hasType(isVolatileQualified()))));
1468}
1469
1470TEST(IsConstQualified, MatchesConstInt) {
1471 EXPECT_TRUE(matches("const int i = 42;",
1472 varDecl(hasType(isConstQualified()))));
1473}
1474
1475TEST(IsConstQualified, MatchesConstPointer) {
1476 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
1477 varDecl(hasType(isConstQualified()))));
1478}
1479
1480TEST(IsConstQualified, MatchesThroughTypedef) {
1481 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
1482 varDecl(hasType(isConstQualified()))));
1483 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
1484 varDecl(hasType(isConstQualified()))));
1485}
1486
1487TEST(IsConstQualified, DoesNotMatchInappropriately) {
1488 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
1489 varDecl(hasType(isConstQualified()))));
1490 EXPECT_TRUE(notMatches("int const* p;",
1491 varDecl(hasType(isConstQualified()))));
1492}
1493
1494TEST(DeclCount, DeclCountIsCorrect) {
1495 EXPECT_TRUE(matches("void f() {int i,j;}",
1496 declStmt(declCountIs(2))));
1497 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
1498 declStmt(declCountIs(3))));
1499 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
1500 declStmt(declCountIs(3))));
1501}
1502
1503
1504TEST(EachOf, TriggersForEachMatch) {
1505 EXPECT_TRUE(matchAndVerifyResultTrue(
1506 "class A { int a; int b; };",
1507 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1508 has(fieldDecl(hasName("b")).bind("v")))),
1509 llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
1510}
1511
1512TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
1513 EXPECT_TRUE(matchAndVerifyResultTrue(
1514 "class A { int a; int c; };",
1515 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1516 has(fieldDecl(hasName("b")).bind("v")))),
1517 llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
1518 EXPECT_TRUE(matchAndVerifyResultTrue(
1519 "class A { int c; int b; };",
1520 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1521 has(fieldDecl(hasName("b")).bind("v")))),
1522 llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
1523 EXPECT_TRUE(notMatches(
1524 "class A { int c; int d; };",
1525 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1526 has(fieldDecl(hasName("b")).bind("v"))))));
1527}
1528
1529TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
1530 // Make sure that we can both match the class by name (::X) and by the type
1531 // the template was instantiated with (via a field).
1532
1533 EXPECT_TRUE(matches(
1534 "template <typename T> class X {}; class A {}; X<A> x;",
1535 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1536
1537 EXPECT_TRUE(matches(
1538 "template <typename T> class X { T t; }; class A {}; X<A> x;",
1539 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
1540 fieldDecl(hasType(recordDecl(hasName("A"))))))));
1541}
1542
1543TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
1544 EXPECT_TRUE(matches(
1545 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
1546 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
1547 isTemplateInstantiation())));
1548}
1549
1550TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
1551 EXPECT_TRUE(matches(
1552 "template <typename T> class X { T t; }; class A {};"
1553 "template class X<A>;",
1554 cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
1555 fieldDecl(hasType(recordDecl(hasName("A"))))))));
1556}
1557
1558TEST(IsTemplateInstantiation,
1559 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
1560 EXPECT_TRUE(matches(
1561 "template <typename T> class X {};"
1562 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
1563 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1564}
1565
1566TEST(IsTemplateInstantiation,
1567 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
1568 EXPECT_TRUE(matches(
1569 "class A {};"
1570 "class X {"
1571 " template <typename U> class Y { U u; };"
1572 " Y<A> y;"
1573 "};",
1574 cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
1575}
1576
1577TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
1578 // FIXME: Figure out whether this makes sense. It doesn't affect the
1579 // normal use case as long as the uppermost instantiation always is marked
1580 // as template instantiation, but it might be confusing as a predicate.
1581 EXPECT_TRUE(matches(
1582 "class A {};"
1583 "template <typename T> class X {"
1584 " template <typename U> class Y { U u; };"
1585 " Y<T> y;"
1586 "}; X<A> x;",
1587 cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
1588}
1589
1590TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
1591 EXPECT_TRUE(notMatches(
1592 "template <typename T> class X {}; class A {};"
1593 "template <> class X<A> {}; X<A> x;",
1594 cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1595}
1596
1597TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
1598 EXPECT_TRUE(notMatches(
1599 "class A {}; class Y { A a; };",
1600 cxxRecordDecl(isTemplateInstantiation())));
1601}
1602
1603TEST(IsInstantiated, MatchesInstantiation) {
1604 EXPECT_TRUE(
1605 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
1606 cxxRecordDecl(isInstantiated())));
1607}
1608
1609TEST(IsInstantiated, NotMatchesDefinition) {
1610 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
1611 cxxRecordDecl(isInstantiated())));
1612}
1613
1614TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
1615 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
1616 "class Y { A<int> a; }; Y y;",
1617 declStmt(isInTemplateInstantiation())));
1618}
1619
1620TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
1621 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
1622 declStmt(isInTemplateInstantiation())));
1623}
1624
1625TEST(IsInstantiated, MatchesFunctionInstantiation) {
1626 EXPECT_TRUE(
1627 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
1628 functionDecl(isInstantiated())));
1629}
1630
1631TEST(IsInstantiated, NotMatchesFunctionDefinition) {
1632 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
1633 varDecl(isInstantiated())));
1634}
1635
1636TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
1637 EXPECT_TRUE(
1638 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
1639 declStmt(isInTemplateInstantiation())));
1640}
1641
1642TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
1643 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
1644 declStmt(isInTemplateInstantiation())));
1645}
1646
1647TEST(IsInTemplateInstantiation, Sharing) {
1648 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
1649 // FIXME: Node sharing is an implementation detail, exposing it is ugly
1650 // and makes the matcher behave in non-obvious ways.
1651 EXPECT_TRUE(notMatches(
1652 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
1653 Matcher));
1654 EXPECT_TRUE(matches(
1655 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
1656 Matcher));
1657}
1658
1659TEST(IsExplicitTemplateSpecialization,
1660 DoesNotMatchPrimaryTemplate) {
1661 EXPECT_TRUE(notMatches(
1662 "template <typename T> class X {};",
1663 cxxRecordDecl(isExplicitTemplateSpecialization())));
1664 EXPECT_TRUE(notMatches(
1665 "template <typename T> void f(T t);",
1666 functionDecl(isExplicitTemplateSpecialization())));
1667}
1668
1669TEST(IsExplicitTemplateSpecialization,
1670 DoesNotMatchExplicitTemplateInstantiations) {
1671 EXPECT_TRUE(notMatches(
1672 "template <typename T> class X {};"
1673 "template class X<int>; extern template class X<long>;",
1674 cxxRecordDecl(isExplicitTemplateSpecialization())));
1675 EXPECT_TRUE(notMatches(
1676 "template <typename T> void f(T t) {}"
1677 "template void f(int t); extern template void f(long t);",
1678 functionDecl(isExplicitTemplateSpecialization())));
1679}
1680
1681TEST(IsExplicitTemplateSpecialization,
1682 DoesNotMatchImplicitTemplateInstantiations) {
1683 EXPECT_TRUE(notMatches(
1684 "template <typename T> class X {}; X<int> x;",
1685 cxxRecordDecl(isExplicitTemplateSpecialization())));
1686 EXPECT_TRUE(notMatches(
1687 "template <typename T> void f(T t); void g() { f(10); }",
1688 functionDecl(isExplicitTemplateSpecialization())));
1689}
1690
1691TEST(IsExplicitTemplateSpecialization,
1692 MatchesExplicitTemplateSpecializations) {
1693 EXPECT_TRUE(matches(
1694 "template <typename T> class X {};"
1695 "template<> class X<int> {};",
1696 cxxRecordDecl(isExplicitTemplateSpecialization())));
1697 EXPECT_TRUE(matches(
1698 "template <typename T> void f(T t) {}"
1699 "template<> void f(int t) {}",
1700 functionDecl(isExplicitTemplateSpecialization())));
1701}
1702
1703TEST(TypeMatching, MatchesBool) {
1704 EXPECT_TRUE(matches("struct S { bool func(); };",
1705 cxxMethodDecl(returns(booleanType()))));
1706 EXPECT_TRUE(notMatches("struct S { void func(); };",
1707 cxxMethodDecl(returns(booleanType()))));
1708}
1709
1710TEST(TypeMatching, MatchesVoid) {
1711 EXPECT_TRUE(matches("struct S { void func(); };",
1712 cxxMethodDecl(returns(voidType()))));
1713}
1714
1715TEST(TypeMatching, MatchesRealFloats) {
1716 EXPECT_TRUE(matches("struct S { float func(); };",
1717 cxxMethodDecl(returns(realFloatingPointType()))));
1718 EXPECT_TRUE(notMatches("struct S { int func(); };",
1719 cxxMethodDecl(returns(realFloatingPointType()))));
1720 EXPECT_TRUE(matches("struct S { long double func(); };",
1721 cxxMethodDecl(returns(realFloatingPointType()))));
1722}
1723
1724TEST(TypeMatching, MatchesArrayTypes) {
1725 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
1726 EXPECT_TRUE(matches("int a[42];", arrayType()));
1727 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
1728
1729 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
1730 arrayType(hasElementType(builtinType()))));
1731
1732 EXPECT_TRUE(matches(
1733 "int const a[] = { 2, 3 };",
1734 qualType(arrayType(hasElementType(builtinType())))));
1735 EXPECT_TRUE(matches(
1736 "int const a[] = { 2, 3 };",
1737 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
1738 EXPECT_TRUE(matches(
1739 "typedef const int T; T x[] = { 1, 2 };",
1740 qualType(isConstQualified(), arrayType())));
1741
1742 EXPECT_TRUE(notMatches(
1743 "int a[] = { 2, 3 };",
1744 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
1745 EXPECT_TRUE(notMatches(
1746 "int a[] = { 2, 3 };",
1747 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
1748 EXPECT_TRUE(notMatches(
1749 "int const a[] = { 2, 3 };",
1750 qualType(arrayType(hasElementType(builtinType())),
1751 unless(isConstQualified()))));
1752
1753 EXPECT_TRUE(matches("int a[2];",
1754 constantArrayType(hasElementType(builtinType()))));
1755 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
1756}
1757
1758TEST(TypeMatching, DecayedType) {
1759 EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
1760 EXPECT_TRUE(notMatches("int i[7];", decayedType()));
1761}
1762
1763TEST(TypeMatching, MatchesComplexTypes) {
1764 EXPECT_TRUE(matches("_Complex float f;", complexType()));
1765 EXPECT_TRUE(matches(
1766 "_Complex float f;",
1767 complexType(hasElementType(builtinType()))));
1768 EXPECT_TRUE(notMatches(
1769 "_Complex float f;",
1770 complexType(hasElementType(isInteger()))));
1771}
1772
1773TEST(NS, Anonymous) {
1774 EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
1775 EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
1776}
1777
1778TEST(EqualsBoundNodeMatcher, QualType) {
1779 EXPECT_TRUE(matches(
1780 "int i = 1;", varDecl(hasType(qualType().bind("type")),
1781 hasInitializer(ignoringParenImpCasts(
1782 hasType(qualType(equalsBoundNode("type"))))))));
1783 EXPECT_TRUE(notMatches("int i = 1.f;",
1784 varDecl(hasType(qualType().bind("type")),
1785 hasInitializer(ignoringParenImpCasts(hasType(
1786 qualType(equalsBoundNode("type"))))))));
1787}
1788
1789TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
1790 EXPECT_TRUE(notMatches(
1791 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
1792 hasInitializer(ignoringParenImpCasts(
1793 hasType(qualType(equalsBoundNode("type"))))))));
1794}
1795
1796TEST(EqualsBoundNodeMatcher, Stmt) {
1797 EXPECT_TRUE(
1798 matches("void f() { if(true) {} }",
1799 stmt(allOf(ifStmt().bind("if"),
1800 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
1801
1802 EXPECT_TRUE(notMatches(
1803 "void f() { if(true) { if (true) {} } }",
1804 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
1805}
1806
1807TEST(EqualsBoundNodeMatcher, Decl) {
1808 EXPECT_TRUE(matches(
1809 "class X { class Y {}; };",
1810 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
1811 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
1812
1813 EXPECT_TRUE(notMatches("class X { class Y {}; };",
1814 decl(allOf(recordDecl(hasName("::X")).bind("record"),
1815 has(decl(equalsBoundNode("record")))))));
1816}
1817
1818TEST(EqualsBoundNodeMatcher, Type) {
1819 EXPECT_TRUE(matches(
1820 "class X { int a; int b; };",
1821 recordDecl(
1822 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
1823 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
1824
1825 EXPECT_TRUE(notMatches(
1826 "class X { int a; double b; };",
1827 recordDecl(
1828 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
1829 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
1830}
1831
1832TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
1833 EXPECT_TRUE(matchAndVerifyResultTrue(
1834 "int f() {"
1835 " if (1) {"
1836 " int i = 9;"
1837 " }"
1838 " int j = 10;"
1839 " {"
1840 " float k = 9.0;"
1841 " }"
1842 " return 0;"
1843 "}",
1844 // Look for variable declarations within functions whose type is the same
1845 // as the function return type.
1846 functionDecl(returns(qualType().bind("type")),
1847 forEachDescendant(varDecl(hasType(
1848 qualType(equalsBoundNode("type")))).bind("decl"))),
1849 // Only i and j should match, not k.
1850 llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("decl", 2)));
1851}
1852
1853TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
1854 EXPECT_TRUE(matchAndVerifyResultTrue(
1855 "void f() {"
1856 " int x;"
1857 " double d;"
1858 " x = d + x - d + x;"
1859 "}",
1860 functionDecl(
1861 hasName("f"), forEachDescendant(varDecl().bind("d")),
1862 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
1863 llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("d", 5)));
1864}
1865
1866TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
1867 EXPECT_TRUE(matchAndVerifyResultTrue(
1868 "struct StringRef { int size() const; const char* data() const; };"
1869 "void f(StringRef v) {"
1870 " v.data();"
1871 "}",
1872 cxxMemberCallExpr(
1873 callee(cxxMethodDecl(hasName("data"))),
1874 on(declRefExpr(to(
1875 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
1876 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
1877 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
1878 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
1879 .bind("data"),
1880 llvm::make_unique<VerifyIdIsBoundTo<Expr>>("data", 1)));
1881
1882 EXPECT_FALSE(matches(
1883 "struct StringRef { int size() const; const char* data() const; };"
1884 "void f(StringRef v) {"
1885 " v.data();"
1886 " v.size();"
1887 "}",
1888 cxxMemberCallExpr(
1889 callee(cxxMethodDecl(hasName("data"))),
1890 on(declRefExpr(to(
1891 varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
1892 unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
1893 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
1894 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
1895 .bind("data")));
1896}
1897
1898TEST(NullPointerConstants, Basic) {
1899 EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
1900 "void *v1 = NULL;", expr(nullPointerConstant())));
1901 EXPECT_TRUE(matches("void *v2 = nullptr;", expr(nullPointerConstant())));
1902 EXPECT_TRUE(matches("void *v3 = __null;", expr(nullPointerConstant())));
1903 EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
1904 EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
1905 EXPECT_TRUE(notMatches("int i = 0;", expr(nullPointerConstant())));
1906}
1907
1908} // namespace ast_matchers
1909} // namespace clang