blob: 290da9005d660fe35e46fb4773845112df3c2e8f [file] [log] [blame]
Manuel Klimek4da21662012-07-06 05:48:52 +00001//===- unittest/Tooling/ASTMatchersTest.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/ASTMatchers/ASTMatchers.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Tooling/Tooling.h"
14#include "gtest/gtest.h"
15
16namespace clang {
17namespace ast_matchers {
18
19TEST(HasNameDeathTest, DiesOnEmptyName) {
20 ASSERT_DEBUG_DEATH({
21 DeclarationMatcher HasEmptyName = record(hasName(""));
22 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
23 }, "");
24}
25
26TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
27 ASSERT_DEBUG_DEATH({
28 DeclarationMatcher IsDerivedFromEmpty = record(isDerivedFrom(""));
29 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
30 }, "");
31}
32
33TEST(NameableDeclaration, MatchesVariousDecls) {
34 DeclarationMatcher NamedX = nameableDeclaration(hasName("X"));
35 EXPECT_TRUE(matches("typedef int X;", NamedX));
36 EXPECT_TRUE(matches("int X;", NamedX));
37 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
38 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
39 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
40 EXPECT_TRUE(matches("namespace X { }", NamedX));
41
42 EXPECT_TRUE(notMatches("#define X 1", NamedX));
43}
44
45TEST(DeclarationMatcher, MatchClass) {
46 DeclarationMatcher ClassMatcher(record());
47 EXPECT_FALSE(matches("", ClassMatcher));
48
49 DeclarationMatcher ClassX = record(record(hasName("X")));
50 EXPECT_TRUE(matches("class X;", ClassX));
51 EXPECT_TRUE(matches("class X {};", ClassX));
52 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
53 EXPECT_TRUE(notMatches("", ClassX));
54}
55
56TEST(DeclarationMatcher, ClassIsDerived) {
57 DeclarationMatcher IsDerivedFromX = record(isDerivedFrom("X"));
58
59 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
60 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
61 EXPECT_TRUE(matches("class X {};", IsDerivedFromX));
62 EXPECT_TRUE(matches("class X;", IsDerivedFromX));
63 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
64 EXPECT_TRUE(notMatches("", IsDerivedFromX));
65
66 DeclarationMatcher ZIsDerivedFromX =
67 record(hasName("Z"), isDerivedFrom("X"));
68 EXPECT_TRUE(
69 matches("class X {}; class Y : public X {}; class Z : public Y {};",
70 ZIsDerivedFromX));
71 EXPECT_TRUE(
72 matches("class X {};"
73 "template<class T> class Y : public X {};"
74 "class Z : public Y<int> {};", ZIsDerivedFromX));
75 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
76 ZIsDerivedFromX));
77 EXPECT_TRUE(
78 matches("template<class T> class X {}; "
79 "template<class T> class Z : public X<T> {};",
80 ZIsDerivedFromX));
81 EXPECT_TRUE(
82 matches("template<class T, class U=T> class X {}; "
83 "template<class T> class Z : public X<T> {};",
84 ZIsDerivedFromX));
85 EXPECT_TRUE(
86 notMatches("template<class X> class A { class Z : public X {}; };",
87 ZIsDerivedFromX));
88 EXPECT_TRUE(
89 matches("template<class X> class A { public: class Z : public X {}; }; "
90 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
91 EXPECT_TRUE(
92 matches("template <class T> class X {}; "
93 "template<class Y> class A { class Z : public X<Y> {}; };",
94 ZIsDerivedFromX));
95 EXPECT_TRUE(
96 notMatches("template<template<class T> class X> class A { "
97 " class Z : public X<int> {}; };", ZIsDerivedFromX));
98 EXPECT_TRUE(
99 matches("template<template<class T> class X> class A { "
100 " public: class Z : public X<int> {}; }; "
101 "template<class T> class X {}; void y() { A<X>::Z z; }",
102 ZIsDerivedFromX));
103 EXPECT_TRUE(
104 notMatches("template<class X> class A { class Z : public X::D {}; };",
105 ZIsDerivedFromX));
106 EXPECT_TRUE(
107 matches("template<class X> class A { public: "
108 " class Z : public X::D {}; }; "
109 "class Y { public: class X {}; typedef X D; }; "
110 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
111 EXPECT_TRUE(
112 matches("class X {}; typedef X Y; class Z : public Y {};",
113 ZIsDerivedFromX));
114 EXPECT_TRUE(
115 matches("template<class T> class Y { typedef typename T::U X; "
116 " class Z : public X {}; };", ZIsDerivedFromX));
117 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
118 ZIsDerivedFromX));
119 EXPECT_TRUE(
120 notMatches("template<class T> class X {}; "
121 "template<class T> class A { class Z : public X<T>::D {}; };",
122 ZIsDerivedFromX));
123 EXPECT_TRUE(
124 matches("template<class T> class X { public: typedef X<T> D; }; "
125 "template<class T> class A { public: "
126 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
127 ZIsDerivedFromX));
128 EXPECT_TRUE(
129 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
130 ZIsDerivedFromX));
131 EXPECT_TRUE(
132 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
133 ZIsDerivedFromX));
134 EXPECT_TRUE(
135 matches("class X {}; class Y : public X {}; "
136 "typedef Y V; typedef V W; class Z : public W {};",
137 ZIsDerivedFromX));
138 EXPECT_TRUE(
139 matches("template<class T, class U> class X {}; "
140 "template<class T> class A { class Z : public X<T, int> {}; };",
141 ZIsDerivedFromX));
142 EXPECT_TRUE(
143 notMatches("template<class X> class D { typedef X A; typedef A B; "
144 " typedef B C; class Z : public C {}; };",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {}; typedef X A; typedef A B; "
148 "class Z : public B {};", ZIsDerivedFromX));
149 EXPECT_TRUE(
150 matches("class X {}; typedef X A; typedef A B; typedef B C; "
151 "class Z : public C {};", ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("class U {}; typedef U X; typedef X V; "
154 "class Z : public V {};", ZIsDerivedFromX));
155 EXPECT_TRUE(
156 matches("class Base {}; typedef Base X; "
157 "class Z : public Base {};", ZIsDerivedFromX));
158 EXPECT_TRUE(
159 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
160 "class Z : public Base {};", ZIsDerivedFromX));
161 EXPECT_TRUE(
162 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
163 "class Z : public Base {};", ZIsDerivedFromX));
164 EXPECT_TRUE(
165 matches("class A {}; typedef A X; typedef A Y; "
166 "class Z : public Y {};", ZIsDerivedFromX));
167 EXPECT_TRUE(
168 notMatches("template <typename T> class Z;"
169 "template <> class Z<void> {};"
170 "template <typename T> class Z : public Z<void> {};",
171 IsDerivedFromX));
172 EXPECT_TRUE(
173 matches("template <typename T> class X;"
174 "template <> class X<void> {};"
175 "template <typename T> class X : public X<void> {};",
176 IsDerivedFromX));
177 EXPECT_TRUE(matches(
178 "class X {};"
179 "template <typename T> class Z;"
180 "template <> class Z<void> {};"
181 "template <typename T> class Z : public Z<void>, public X {};",
182 ZIsDerivedFromX));
183
184 // FIXME: Once we have better matchers for template type matching,
185 // get rid of the Variable(...) matching and match the right template
186 // declarations directly.
187 const char *RecursiveTemplateOneParameter =
188 "class Base1 {}; class Base2 {};"
189 "template <typename T> class Z;"
190 "template <> class Z<void> : public Base1 {};"
191 "template <> class Z<int> : public Base2 {};"
192 "template <> class Z<float> : public Z<void> {};"
193 "template <> class Z<double> : public Z<int> {};"
194 "template <typename T> class Z : public Z<float>, public Z<double> {};"
195 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
196 EXPECT_TRUE(matches(
197 RecursiveTemplateOneParameter,
198 variable(hasName("z_float"),
199 hasInitializer(hasType(record(isDerivedFrom("Base1")))))));
200 EXPECT_TRUE(notMatches(
201 RecursiveTemplateOneParameter,
202 variable(
203 hasName("z_float"),
204 hasInitializer(hasType(record(isDerivedFrom("Base2")))))));
205 EXPECT_TRUE(matches(
206 RecursiveTemplateOneParameter,
207 variable(
208 hasName("z_char"),
209 hasInitializer(hasType(record(isDerivedFrom("Base1"),
210 isDerivedFrom("Base2")))))));
211
212 const char *RecursiveTemplateTwoParameters =
213 "class Base1 {}; class Base2 {};"
214 "template <typename T1, typename T2> class Z;"
215 "template <typename T> class Z<void, T> : public Base1 {};"
216 "template <typename T> class Z<int, T> : public Base2 {};"
217 "template <typename T> class Z<float, T> : public Z<void, T> {};"
218 "template <typename T> class Z<double, T> : public Z<int, T> {};"
219 "template <typename T1, typename T2> class Z : "
220 " public Z<float, T2>, public Z<double, T2> {};"
221 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
222 " Z<char, void> z_char; }";
223 EXPECT_TRUE(matches(
224 RecursiveTemplateTwoParameters,
225 variable(
226 hasName("z_float"),
227 hasInitializer(hasType(record(isDerivedFrom("Base1")))))));
228 EXPECT_TRUE(notMatches(
229 RecursiveTemplateTwoParameters,
230 variable(
231 hasName("z_float"),
232 hasInitializer(hasType(record(isDerivedFrom("Base2")))))));
233 EXPECT_TRUE(matches(
234 RecursiveTemplateTwoParameters,
235 variable(
236 hasName("z_char"),
237 hasInitializer(hasType(record(isDerivedFrom("Base1"),
238 isDerivedFrom("Base2")))))));
239}
240
241TEST(DeclarationMatcher, MatchAnyOf) {
242 DeclarationMatcher YOrZDerivedFromX =
243 record(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
244
245 EXPECT_TRUE(
246 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
247 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
248 EXPECT_TRUE(
249 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
250 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
251
252 DeclarationMatcher XOrYOrZOrUOrV =
253 record(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
254 hasName("V")));
255
256 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
257 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
258 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
259 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
260 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
261 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
262}
263
264TEST(DeclarationMatcher, MatchHas) {
265 DeclarationMatcher HasClassX = record(has(record(hasName("X"))));
266
267 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
268 EXPECT_TRUE(matches("class X {};", HasClassX));
269
270 DeclarationMatcher YHasClassX =
271 record(hasName("Y"), has(record(hasName("X"))));
272 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
273 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
274 EXPECT_TRUE(
275 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
276}
277
278TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
279 DeclarationMatcher Recursive =
280 record(
281 has(record(
282 has(record(hasName("X"))),
283 has(record(hasName("Y"))),
284 hasName("Z"))),
285 has(record(
286 has(record(hasName("A"))),
287 has(record(hasName("B"))),
288 hasName("C"))),
289 hasName("F"));
290
291 EXPECT_TRUE(matches(
292 "class F {"
293 " class Z {"
294 " class X {};"
295 " class Y {};"
296 " };"
297 " class C {"
298 " class A {};"
299 " class B {};"
300 " };"
301 "};", Recursive));
302
303 EXPECT_TRUE(matches(
304 "class F {"
305 " class Z {"
306 " class A {};"
307 " class X {};"
308 " class Y {};"
309 " };"
310 " class C {"
311 " class X {};"
312 " class A {};"
313 " class B {};"
314 " };"
315 "};", Recursive));
316
317 EXPECT_TRUE(matches(
318 "class O1 {"
319 " class O2 {"
320 " class F {"
321 " class Z {"
322 " class A {};"
323 " class X {};"
324 " class Y {};"
325 " };"
326 " class C {"
327 " class X {};"
328 " class A {};"
329 " class B {};"
330 " };"
331 " };"
332 " };"
333 "};", Recursive));
334}
335
336TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
337 DeclarationMatcher Recursive =
338 record(
339 anyOf(
340 has(record(
341 anyOf(
342 has(record(
343 hasName("X"))),
344 has(record(
345 hasName("Y"))),
346 hasName("Z")))),
347 has(record(
348 anyOf(
349 hasName("C"),
350 has(record(
351 hasName("A"))),
352 has(record(
353 hasName("B")))))),
354 hasName("F")));
355
356 EXPECT_TRUE(matches("class F {};", Recursive));
357 EXPECT_TRUE(matches("class Z {};", Recursive));
358 EXPECT_TRUE(matches("class C {};", Recursive));
359 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
360 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
361 EXPECT_TRUE(
362 matches("class O1 { class O2 {"
363 " class M { class N { class B {}; }; }; "
364 "}; };", Recursive));
365}
366
367TEST(DeclarationMatcher, MatchNot) {
368 DeclarationMatcher NotClassX =
369 record(
370 isDerivedFrom("Y"),
371 unless(hasName("Y")),
372 unless(hasName("X")));
373 EXPECT_TRUE(notMatches("", NotClassX));
374 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
375 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
376 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
377 EXPECT_TRUE(
378 notMatches("class Y {}; class Z {}; class X : public Y {};",
379 NotClassX));
380
381 DeclarationMatcher ClassXHasNotClassY =
382 record(
383 hasName("X"),
384 has(record(hasName("Z"))),
385 unless(
386 has(record(hasName("Y")))));
387 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
388 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
389 ClassXHasNotClassY));
390}
391
392TEST(DeclarationMatcher, HasDescendant) {
393 DeclarationMatcher ZDescendantClassX =
394 record(
395 hasDescendant(record(hasName("X"))),
396 hasName("Z"));
397 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
398 EXPECT_TRUE(
399 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
400 EXPECT_TRUE(
401 matches("class Z { class A { class Y { class X {}; }; }; };",
402 ZDescendantClassX));
403 EXPECT_TRUE(
404 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
405 ZDescendantClassX));
406 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
407
408 DeclarationMatcher ZDescendantClassXHasClassY =
409 record(
410 hasDescendant(record(has(record(hasName("Y"))),
411 hasName("X"))),
412 hasName("Z"));
413 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
414 ZDescendantClassXHasClassY));
415 EXPECT_TRUE(
416 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
417 ZDescendantClassXHasClassY));
418 EXPECT_TRUE(notMatches(
419 "class Z {"
420 " class A {"
421 " class B {"
422 " class X {"
423 " class C {"
424 " class Y {};"
425 " };"
426 " };"
427 " }; "
428 " };"
429 "};", ZDescendantClassXHasClassY));
430
431 DeclarationMatcher ZDescendantClassXDescendantClassY =
432 record(
433 hasDescendant(record(hasDescendant(record(hasName("Y"))),
434 hasName("X"))),
435 hasName("Z"));
436 EXPECT_TRUE(
437 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
438 ZDescendantClassXDescendantClassY));
439 EXPECT_TRUE(matches(
440 "class Z {"
441 " class A {"
442 " class X {"
443 " class B {"
444 " class Y {};"
445 " };"
446 " class Y {};"
447 " };"
448 " };"
449 "};", ZDescendantClassXDescendantClassY));
450}
451
452TEST(StatementMatcher, Has) {
453 StatementMatcher HasVariableI =
454 expression(
455 hasType(pointsTo(record(hasName("X")))),
456 has(declarationReference(to(variable(hasName("i"))))));
457
458 EXPECT_TRUE(matches(
459 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
460 EXPECT_TRUE(notMatches(
461 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
462}
463
464TEST(StatementMatcher, HasDescendant) {
465 StatementMatcher HasDescendantVariableI =
466 expression(
467 hasType(pointsTo(record(hasName("X")))),
468 hasDescendant(declarationReference(to(variable(hasName("i"))))));
469
470 EXPECT_TRUE(matches(
471 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
472 HasDescendantVariableI));
473 EXPECT_TRUE(notMatches(
474 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
475 HasDescendantVariableI));
476}
477
478TEST(TypeMatcher, MatchesClassType) {
479 TypeMatcher TypeA = hasDeclaration(record(hasName("A")));
480
481 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
482 EXPECT_TRUE(notMatches("class A {};", TypeA));
483
484 TypeMatcher TypeDerivedFromA = hasDeclaration(record(isDerivedFrom("A")));
485
486 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
487 TypeDerivedFromA));
488 EXPECT_TRUE(notMatches("class A {};", TypeA));
489
490 TypeMatcher TypeAHasClassB = hasDeclaration(
491 record(hasName("A"), has(record(hasName("B")))));
492
493 EXPECT_TRUE(
494 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
495}
496
497// Returns from Run whether 'bound_nodes' contain a Decl bound to 'Id', which
498// can be dynamically casted to T.
499// Optionally checks that the check succeeded a specific number of times.
500template <typename T>
501class VerifyIdIsBoundToDecl : public BoundNodesCallback {
502public:
503 // Create an object that checks that a node of type 'T' was bound to 'Id'.
504 // Does not check for a certain number of matches.
505 explicit VerifyIdIsBoundToDecl(const std::string& Id)
506 : Id(Id), ExpectedCount(-1), Count(0) {}
507
508 // Create an object that checks that a node of type 'T' was bound to 'Id'.
509 // Checks that there were exactly 'ExpectedCount' matches.
510 explicit VerifyIdIsBoundToDecl(const std::string& Id, int ExpectedCount)
511 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
512
513 ~VerifyIdIsBoundToDecl() {
514 if (ExpectedCount != -1) {
515 EXPECT_EQ(ExpectedCount, Count);
516 }
517 }
518
519 virtual bool run(const BoundNodes *Nodes) {
520 if (Nodes->getDeclAs<T>(Id) != NULL) {
521 ++Count;
522 return true;
523 }
524 return false;
525 }
526
527private:
528 const std::string Id;
529 const int ExpectedCount;
530 int Count;
531};
532template <typename T>
533class VerifyIdIsBoundToStmt : public BoundNodesCallback {
534public:
535 explicit VerifyIdIsBoundToStmt(const std::string &Id) : Id(Id) {}
536 virtual bool run(const BoundNodes *Nodes) {
537 const T *Node = Nodes->getStmtAs<T>(Id);
538 return Node != NULL;
539 }
540private:
541 const std::string Id;
542};
543
544TEST(Matcher, BindMatchedNodes) {
545 DeclarationMatcher ClassX = has(id("x", record(hasName("X"))));
546
547 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
548 ClassX, new VerifyIdIsBoundToDecl<clang::CXXRecordDecl>("x")));
549
550 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
551 ClassX, new VerifyIdIsBoundToDecl<clang::CXXRecordDecl>("other-id")));
552
553 TypeMatcher TypeAHasClassB = hasDeclaration(
554 record(hasName("A"), has(id("b", record(hasName("B"))))));
555
556 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
557 TypeAHasClassB,
558 new VerifyIdIsBoundToDecl<clang::Decl>("b")));
559
560 StatementMatcher MethodX = id("x", call(callee(method(hasName("x")))));
561
562 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
563 MethodX,
564 new VerifyIdIsBoundToStmt<clang::CXXMemberCallExpr>("x")));
565}
566
567TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
568 TypeMatcher ClassX = hasDeclaration(record(hasName("X")));
569 EXPECT_TRUE(
570 matches("class X {}; void y(X &x) { x; }", expression(hasType(ClassX))));
571 EXPECT_TRUE(
572 notMatches("class X {}; void y(X *x) { x; }",
573 expression(hasType(ClassX))));
574 EXPECT_TRUE(
575 matches("class X {}; void y(X *x) { x; }",
576 expression(hasType(pointsTo(ClassX)))));
577}
578
579TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
580 TypeMatcher ClassX = hasDeclaration(record(hasName("X")));
581 EXPECT_TRUE(
582 matches("class X {}; void y() { X x; }", variable(hasType(ClassX))));
583 EXPECT_TRUE(
584 notMatches("class X {}; void y() { X *x; }", variable(hasType(ClassX))));
585 EXPECT_TRUE(
586 matches("class X {}; void y() { X *x; }",
587 variable(hasType(pointsTo(ClassX)))));
588}
589
590TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
591 DeclarationMatcher ClassX = record(hasName("X"));
592 EXPECT_TRUE(
593 matches("class X {}; void y(X &x) { x; }", expression(hasType(ClassX))));
594 EXPECT_TRUE(
595 notMatches("class X {}; void y(X *x) { x; }",
596 expression(hasType(ClassX))));
597}
598
599TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
600 DeclarationMatcher ClassX = record(hasName("X"));
601 EXPECT_TRUE(
602 matches("class X {}; void y() { X x; }", variable(hasType(ClassX))));
603 EXPECT_TRUE(
604 notMatches("class X {}; void y() { X *x; }", variable(hasType(ClassX))));
605}
606
607TEST(Matcher, Call) {
608 // FIXME: Do we want to overload Call() to directly take
609 // Matcher<clang::Decl>, too?
610 StatementMatcher MethodX = call(hasDeclaration(method(hasName("x"))));
611
612 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
613 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
614
615 StatementMatcher MethodOnY = call(on(hasType(record(hasName("Y")))));
616
617 EXPECT_TRUE(
618 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
619 MethodOnY));
620 EXPECT_TRUE(
621 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
622 MethodOnY));
623 EXPECT_TRUE(
624 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
625 MethodOnY));
626 EXPECT_TRUE(
627 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
628 MethodOnY));
629 EXPECT_TRUE(
630 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
631 MethodOnY));
632
633 StatementMatcher MethodOnYPointer =
634 call(on(hasType(pointsTo(record(hasName("Y"))))));
635
636 EXPECT_TRUE(
637 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
638 MethodOnYPointer));
639 EXPECT_TRUE(
640 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
641 MethodOnYPointer));
642 EXPECT_TRUE(
643 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
644 MethodOnYPointer));
645 EXPECT_TRUE(
646 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
647 MethodOnYPointer));
648 EXPECT_TRUE(
649 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
650 MethodOnYPointer));
651}
652
653TEST(Matcher, OverloadedOperatorCall) {
654 StatementMatcher OpCall = overloadedOperatorCall();
655 // Unary operator
656 EXPECT_TRUE(matches("class Y { }; "
657 "bool operator!(Y x) { return false; }; "
658 "Y y; bool c = !y;", OpCall));
659 // No match -- special operators like "new", "delete"
660 // FIXME: operator new takes size_t, for which we need stddef.h, for which
661 // we need to figure out include paths in the test.
662 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
663 // "class Y { }; "
664 // "void *operator new(size_t size) { return 0; } "
665 // "Y *y = new Y;", OpCall));
666 EXPECT_TRUE(notMatches("class Y { }; "
667 "void operator delete(void *p) { } "
668 "void a() {Y *y = new Y; delete y;}", OpCall));
669 // Binary operator
670 EXPECT_TRUE(matches("class Y { }; "
671 "bool operator&&(Y x, Y y) { return true; }; "
672 "Y a; Y b; bool c = a && b;",
673 OpCall));
674 // No match -- normal operator, not an overloaded one.
675 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
676 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
677}
678
679TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
680 StatementMatcher OpCallAndAnd =
681 overloadedOperatorCall(hasOverloadedOperatorName("&&"));
682 EXPECT_TRUE(matches("class Y { }; "
683 "bool operator&&(Y x, Y y) { return true; }; "
684 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
685 StatementMatcher OpCallLessLess =
686 overloadedOperatorCall(hasOverloadedOperatorName("<<"));
687 EXPECT_TRUE(notMatches("class Y { }; "
688 "bool operator&&(Y x, Y y) { return true; }; "
689 "Y a; Y b; bool c = a && b;",
690 OpCallLessLess));
691}
692
693TEST(Matcher, ThisPointerType) {
694 StatementMatcher MethodOnY = call(thisPointerType(record(hasName("Y"))));
695
696 EXPECT_TRUE(
697 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
698 MethodOnY));
699 EXPECT_TRUE(
700 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
701 MethodOnY));
702 EXPECT_TRUE(
703 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
704 MethodOnY));
705 EXPECT_TRUE(
706 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
707 MethodOnY));
708 EXPECT_TRUE(
709 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
710 MethodOnY));
711
712 EXPECT_TRUE(matches(
713 "class Y {"
714 " public: virtual void x();"
715 "};"
716 "class X : public Y {"
717 " public: virtual void x();"
718 "};"
719 "void z() { X *x; x->Y::x(); }", MethodOnY));
720}
721
722TEST(Matcher, VariableUsage) {
723 StatementMatcher Reference =
724 declarationReference(to(
725 variable(hasInitializer(
726 call(thisPointerType(record(hasName("Y"))))))));
727
728 EXPECT_TRUE(matches(
729 "class Y {"
730 " public:"
731 " bool x() const;"
732 "};"
733 "void z(const Y &y) {"
734 " bool b = y.x();"
735 " if (b) {}"
736 "}", Reference));
737
738 EXPECT_TRUE(notMatches(
739 "class Y {"
740 " public:"
741 " bool x() const;"
742 "};"
743 "void z(const Y &y) {"
744 " bool b = y.x();"
745 "}", Reference));
746}
747
748TEST(Matcher, CalledVariable) {
749 StatementMatcher CallOnVariableY = expression(
750 call(on(declarationReference(to(variable(hasName("y")))))));
751
752 EXPECT_TRUE(matches(
753 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
754 EXPECT_TRUE(matches(
755 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
756 EXPECT_TRUE(matches(
757 "class Y { public: void x(); };"
758 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
759 EXPECT_TRUE(matches(
760 "class Y { public: void x(); };"
761 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
762 EXPECT_TRUE(notMatches(
763 "class Y { public: void x(); };"
764 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
765 CallOnVariableY));
766}
767
768TEST(MemberExpression, DoesNotMatchClasses) {
769 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpression()));
770}
771
772TEST(MemberExpression, MatchesMemberFunctionCall) {
773 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpression()));
774}
775
776TEST(MemberExpression, MatchesVariable) {
777 EXPECT_TRUE(
778 matches("class Y { void x() { this->y; } int y; };", memberExpression()));
779 EXPECT_TRUE(
780 matches("class Y { void x() { y; } int y; };", memberExpression()));
781 EXPECT_TRUE(
782 matches("class Y { void x() { Y y; y.y; } int y; };",
783 memberExpression()));
784}
785
786TEST(MemberExpression, MatchesStaticVariable) {
787 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
788 memberExpression()));
789 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
790 memberExpression()));
791 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
792 memberExpression()));
793}
794
795TEST(IsArrow, MatchesMemberVariablesViaArrow) {
796 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
797 memberExpression(isArrow())));
798 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
799 memberExpression(isArrow())));
800 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
801 memberExpression(isArrow())));
802}
803
804TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
805 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
806 memberExpression(isArrow())));
807 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
808 memberExpression(isArrow())));
809 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
810 memberExpression(isArrow())));
811}
812
813TEST(IsArrow, MatchesMemberCallsViaArrow) {
814 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
815 memberExpression(isArrow())));
816 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
817 memberExpression(isArrow())));
818 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
819 memberExpression(isArrow())));
820}
821
822TEST(Callee, MatchesDeclarations) {
823 StatementMatcher CallMethodX = call(callee(method(hasName("x"))));
824
825 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
826 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
827}
828
829TEST(Callee, MatchesMemberExpressions) {
830 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
831 call(callee(memberExpression()))));
832 EXPECT_TRUE(
833 notMatches("class Y { void x() { this->x(); } };", call(callee(call()))));
834}
835
836TEST(Function, MatchesFunctionDeclarations) {
837 StatementMatcher CallFunctionF = call(callee(function(hasName("f"))));
838
839 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
840 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
841
842 // Dependent contexts, but a non-dependent call.
843 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
844 CallFunctionF));
845 EXPECT_TRUE(
846 matches("void f(); template <int N> struct S { void g() { f(); } };",
847 CallFunctionF));
848
849 // Depedent calls don't match.
850 EXPECT_TRUE(
851 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
852 CallFunctionF));
853 EXPECT_TRUE(
854 notMatches("void f(int);"
855 "template <typename T> struct S { void g(T t) { f(t); } };",
856 CallFunctionF));
857}
858
859TEST(Matcher, Argument) {
860 StatementMatcher CallArgumentY = expression(call(
861 hasArgument(0, declarationReference(to(variable(hasName("y")))))));
862
863 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
864 EXPECT_TRUE(
865 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
866 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
867
868 StatementMatcher WrongIndex = expression(call(
869 hasArgument(42, declarationReference(to(variable(hasName("y")))))));
870 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
871}
872
873TEST(Matcher, AnyArgument) {
874 StatementMatcher CallArgumentY = expression(call(
875 hasAnyArgument(declarationReference(to(variable(hasName("y")))))));
876 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
877 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
878 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
879}
880
881TEST(Matcher, ArgumentCount) {
882 StatementMatcher Call1Arg = expression(call(argumentCountIs(1)));
883
884 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
885 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
886 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
887}
888
889TEST(Matcher, References) {
890 DeclarationMatcher ReferenceClassX = variable(
891 hasType(references(record(hasName("X")))));
892 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
893 ReferenceClassX));
894 EXPECT_TRUE(
895 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
896 EXPECT_TRUE(
897 notMatches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
898 EXPECT_TRUE(
899 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
900}
901
902TEST(HasParameter, CallsInnerMatcher) {
903 EXPECT_TRUE(matches("class X { void x(int) {} };",
904 method(hasParameter(0, variable()))));
905 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
906 method(hasParameter(0, hasName("x")))));
907}
908
909TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
910 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
911 method(hasParameter(42, variable()))));
912}
913
914TEST(HasType, MatchesParameterVariableTypesStrictly) {
915 EXPECT_TRUE(matches("class X { void x(X x) {} };",
916 method(hasParameter(0, hasType(record(hasName("X")))))));
917 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
918 method(hasParameter(0, hasType(record(hasName("X")))))));
919 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
920 method(hasParameter(0, hasType(pointsTo(record(hasName("X"))))))));
921 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
922 method(hasParameter(0, hasType(references(record(hasName("X"))))))));
923}
924
925TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
926 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
927 method(hasAnyParameter(hasType(record(hasName("X")))))));
928 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
929 method(hasAnyParameter(hasType(record(hasName("X")))))));
930}
931
932TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
933 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
934 method(hasAnyParameter(hasType(record(hasName("X")))))));
935}
936
937TEST(HasAnyParameter, DoesNotMatchThisPointer) {
938 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
939 method(hasAnyParameter(hasType(pointsTo(record(hasName("X"))))))));
940}
941
942TEST(HasName, MatchesParameterVariableDeclartions) {
943 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
944 method(hasAnyParameter(hasName("x")))));
945 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
946 method(hasAnyParameter(hasName("x")))));
947}
948
949TEST(Matcher, ConstructorCall) {
950 StatementMatcher Constructor = expression(constructorCall());
951
952 EXPECT_TRUE(
953 matches("class X { public: X(); }; void x() { X x; }", Constructor));
954 EXPECT_TRUE(
955 matches("class X { public: X(); }; void x() { X x = X(); }",
956 Constructor));
957 EXPECT_TRUE(
958 matches("class X { public: X(int); }; void x() { X x = 0; }",
959 Constructor));
960 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
961}
962
963TEST(Matcher, ConstructorArgument) {
964 StatementMatcher Constructor = expression(constructorCall(
965 hasArgument(0, declarationReference(to(variable(hasName("y")))))));
966
967 EXPECT_TRUE(
968 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
969 Constructor));
970 EXPECT_TRUE(
971 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
972 Constructor));
973 EXPECT_TRUE(
974 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
975 Constructor));
976 EXPECT_TRUE(
977 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
978 Constructor));
979
980 StatementMatcher WrongIndex = expression(constructorCall(
981 hasArgument(42, declarationReference(to(variable(hasName("y")))))));
982 EXPECT_TRUE(
983 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
984 WrongIndex));
985}
986
987TEST(Matcher, ConstructorArgumentCount) {
988 StatementMatcher Constructor1Arg =
989 expression(constructorCall(argumentCountIs(1)));
990
991 EXPECT_TRUE(
992 matches("class X { public: X(int); }; void x() { X x(0); }",
993 Constructor1Arg));
994 EXPECT_TRUE(
995 matches("class X { public: X(int); }; void x() { X x = X(0); }",
996 Constructor1Arg));
997 EXPECT_TRUE(
998 matches("class X { public: X(int); }; void x() { X x = 0; }",
999 Constructor1Arg));
1000 EXPECT_TRUE(
1001 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1002 Constructor1Arg));
1003}
1004
1005TEST(Matcher, BindTemporaryExpression) {
1006 StatementMatcher TempExpression = expression(bindTemporaryExpression());
1007
1008 std::string ClassString = "class string { public: string(); ~string(); }; ";
1009
1010 EXPECT_TRUE(
1011 matches(ClassString +
1012 "string GetStringByValue();"
1013 "void FunctionTakesString(string s);"
1014 "void run() { FunctionTakesString(GetStringByValue()); }",
1015 TempExpression));
1016
1017 EXPECT_TRUE(
1018 notMatches(ClassString +
1019 "string* GetStringPointer(); "
1020 "void FunctionTakesStringPtr(string* s);"
1021 "void run() {"
1022 " string* s = GetStringPointer();"
1023 " FunctionTakesStringPtr(GetStringPointer());"
1024 " FunctionTakesStringPtr(s);"
1025 "}",
1026 TempExpression));
1027
1028 EXPECT_TRUE(
1029 notMatches("class no_dtor {};"
1030 "no_dtor GetObjByValue();"
1031 "void ConsumeObj(no_dtor param);"
1032 "void run() { ConsumeObj(GetObjByValue()); }",
1033 TempExpression));
1034}
1035
1036TEST(ConstructorDeclaration, SimpleCase) {
1037 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
1038 constructor(ofClass(hasName("Foo")))));
1039 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
1040 constructor(ofClass(hasName("Bar")))));
1041}
1042
1043TEST(ConstructorDeclaration, IsImplicit) {
1044 // This one doesn't match because the constructor is not added by the
1045 // compiler (it is not needed).
1046 EXPECT_TRUE(notMatches("class Foo { };",
1047 constructor(isImplicit())));
1048 // The compiler added the implicit default constructor.
1049 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
1050 constructor(isImplicit())));
1051 EXPECT_TRUE(matches("class Foo { Foo(){} };",
1052 constructor(unless(isImplicit()))));
1053}
1054
1055TEST(HasAnyConstructorInitializer, SimpleCase) {
1056 EXPECT_TRUE(notMatches(
1057 "class Foo { Foo() { } };",
1058 constructor(hasAnyConstructorInitializer(anything()))));
1059 EXPECT_TRUE(matches(
1060 "class Foo {"
1061 " Foo() : foo_() { }"
1062 " int foo_;"
1063 "};",
1064 constructor(hasAnyConstructorInitializer(anything()))));
1065}
1066
1067TEST(HasAnyConstructorInitializer, ForField) {
1068 static const char Code[] =
1069 "class Baz { };"
1070 "class Foo {"
1071 " Foo() : foo_() { }"
1072 " Baz foo_;"
1073 " Baz bar_;"
1074 "};";
1075 EXPECT_TRUE(matches(Code, constructor(hasAnyConstructorInitializer(
1076 forField(hasType(record(hasName("Baz"))))))));
1077 EXPECT_TRUE(matches(Code, constructor(hasAnyConstructorInitializer(
1078 forField(hasName("foo_"))))));
1079 EXPECT_TRUE(notMatches(Code, constructor(hasAnyConstructorInitializer(
1080 forField(hasType(record(hasName("Bar"))))))));
1081}
1082
1083TEST(HasAnyConstructorInitializer, WithInitializer) {
1084 static const char Code[] =
1085 "class Foo {"
1086 " Foo() : foo_(0) { }"
1087 " int foo_;"
1088 "};";
1089 EXPECT_TRUE(matches(Code, constructor(hasAnyConstructorInitializer(
1090 withInitializer(integerLiteral(equals(0)))))));
1091 EXPECT_TRUE(notMatches(Code, constructor(hasAnyConstructorInitializer(
1092 withInitializer(integerLiteral(equals(1)))))));
1093}
1094
1095TEST(HasAnyConstructorInitializer, IsWritten) {
1096 static const char Code[] =
1097 "struct Bar { Bar(){} };"
1098 "class Foo {"
1099 " Foo() : foo_() { }"
1100 " Bar foo_;"
1101 " Bar bar_;"
1102 "};";
1103 EXPECT_TRUE(matches(Code, constructor(hasAnyConstructorInitializer(
1104 allOf(forField(hasName("foo_")), isWritten())))));
1105 EXPECT_TRUE(notMatches(Code, constructor(hasAnyConstructorInitializer(
1106 allOf(forField(hasName("bar_")), isWritten())))));
1107 EXPECT_TRUE(matches(Code, constructor(hasAnyConstructorInitializer(
1108 allOf(forField(hasName("bar_")), unless(isWritten()))))));
1109}
1110
1111TEST(Matcher, NewExpression) {
1112 StatementMatcher New = expression(newExpression());
1113
1114 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
1115 EXPECT_TRUE(
1116 matches("class X { public: X(); }; void x() { new X(); }", New));
1117 EXPECT_TRUE(
1118 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1119 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
1120}
1121
1122TEST(Matcher, NewExpressionArgument) {
1123 StatementMatcher New = expression(constructorCall(
1124 hasArgument(
1125 0, declarationReference(to(variable(hasName("y")))))));
1126
1127 EXPECT_TRUE(
1128 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1129 New));
1130 EXPECT_TRUE(
1131 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
1132 New));
1133 EXPECT_TRUE(
1134 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
1135 New));
1136
1137 StatementMatcher WrongIndex = expression(constructorCall(
1138 hasArgument(
1139 42, declarationReference(to(variable(hasName("y")))))));
1140 EXPECT_TRUE(
1141 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
1142 WrongIndex));
1143}
1144
1145TEST(Matcher, NewExpressionArgumentCount) {
1146 StatementMatcher New = constructorCall(argumentCountIs(1));
1147
1148 EXPECT_TRUE(
1149 matches("class X { public: X(int); }; void x() { new X(0); }", New));
1150 EXPECT_TRUE(
1151 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
1152 New));
1153}
1154
1155TEST(Matcher, DefaultArgument) {
1156 StatementMatcher Arg = defaultArgument();
1157
1158 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
1159 EXPECT_TRUE(
1160 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
1161 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
1162}
1163
1164TEST(Matcher, StringLiterals) {
1165 StatementMatcher Literal = expression(stringLiteral());
1166 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
1167 // wide string
1168 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
1169 // with escaped characters
1170 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
1171 // no matching -- though the data type is the same, there is no string literal
1172 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
1173}
1174
1175TEST(Matcher, CharacterLiterals) {
1176 StatementMatcher CharLiteral = expression(characterLiteral());
1177 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
1178 // wide character
1179 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
1180 // wide character, Hex encoded, NOT MATCHED!
1181 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
1182 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
1183}
1184
1185TEST(Matcher, IntegerLiterals) {
1186 StatementMatcher HasIntLiteral = expression(integerLiteral());
1187 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
1188 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
1189 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
1190 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
1191
1192 // Non-matching cases (character literals, float and double)
1193 EXPECT_TRUE(notMatches("int i = L'a';",
1194 HasIntLiteral)); // this is actually a character
1195 // literal cast to int
1196 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
1197 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
1198 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
1199}
1200
1201TEST(Matcher, Conditions) {
1202 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
1203
1204 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1205 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1206 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1207 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1208 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1209}
1210
1211TEST(MatchBinaryOperator, HasOperatorName) {
1212 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
1213
1214 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
1215 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
1216}
1217
1218TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
1219 StatementMatcher OperatorTrueFalse =
1220 binaryOperator(hasLHS(boolLiteral(equals(true))),
1221 hasRHS(boolLiteral(equals(false))));
1222
1223 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
1224 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
1225 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
1226}
1227
1228TEST(MatchBinaryOperator, HasEitherOperand) {
1229 StatementMatcher HasOperand =
1230 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
1231
1232 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
1233 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
1234 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
1235}
1236
1237TEST(Matcher, BinaryOperatorTypes) {
1238 // Integration test that verifies the AST provides all binary operators in
1239 // a way we expect.
1240 // FIXME: Operator ','
1241 EXPECT_TRUE(
1242 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
1243 EXPECT_TRUE(
1244 matches("bool b; bool c = (b = true);",
1245 binaryOperator(hasOperatorName("="))));
1246 EXPECT_TRUE(
1247 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
1248 EXPECT_TRUE(
1249 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
1250 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
1251 EXPECT_TRUE(
1252 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
1253 EXPECT_TRUE(
1254 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
1255 EXPECT_TRUE(
1256 matches("int i = 1; int j = (i <<= 2);",
1257 binaryOperator(hasOperatorName("<<="))));
1258 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
1259 EXPECT_TRUE(
1260 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
1261 EXPECT_TRUE(
1262 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
1263 EXPECT_TRUE(
1264 matches("int i = 1; int j = (i >>= 2);",
1265 binaryOperator(hasOperatorName(">>="))));
1266 EXPECT_TRUE(
1267 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
1268 EXPECT_TRUE(
1269 matches("int i = 42; int j = (i ^= 42);",
1270 binaryOperator(hasOperatorName("^="))));
1271 EXPECT_TRUE(
1272 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
1273 EXPECT_TRUE(
1274 matches("int i = 42; int j = (i %= 42);",
1275 binaryOperator(hasOperatorName("%="))));
1276 EXPECT_TRUE(
1277 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
1278 EXPECT_TRUE(
1279 matches("bool b = true && false;",
1280 binaryOperator(hasOperatorName("&&"))));
1281 EXPECT_TRUE(
1282 matches("bool b = true; bool c = (b &= false);",
1283 binaryOperator(hasOperatorName("&="))));
1284 EXPECT_TRUE(
1285 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
1286 EXPECT_TRUE(
1287 matches("bool b = true || false;",
1288 binaryOperator(hasOperatorName("||"))));
1289 EXPECT_TRUE(
1290 matches("bool b = true; bool c = (b |= false);",
1291 binaryOperator(hasOperatorName("|="))));
1292 EXPECT_TRUE(
1293 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
1294 EXPECT_TRUE(
1295 matches("int i = 42; int j = (i *= 23);",
1296 binaryOperator(hasOperatorName("*="))));
1297 EXPECT_TRUE(
1298 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
1299 EXPECT_TRUE(
1300 matches("int i = 42; int j = (i /= 23);",
1301 binaryOperator(hasOperatorName("/="))));
1302 EXPECT_TRUE(
1303 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
1304 EXPECT_TRUE(
1305 matches("int i = 42; int j = (i += 23);",
1306 binaryOperator(hasOperatorName("+="))));
1307 EXPECT_TRUE(
1308 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
1309 EXPECT_TRUE(
1310 matches("int i = 42; int j = (i -= 23);",
1311 binaryOperator(hasOperatorName("-="))));
1312 EXPECT_TRUE(
1313 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
1314 binaryOperator(hasOperatorName("->*"))));
1315 EXPECT_TRUE(
1316 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
1317 binaryOperator(hasOperatorName(".*"))));
1318
1319 // Member expressions as operators are not supported in matches.
1320 EXPECT_TRUE(
1321 notMatches("struct A { void x(A *a) { a->x(this); } };",
1322 binaryOperator(hasOperatorName("->"))));
1323
1324 // Initializer assignments are not represented as operator equals.
1325 EXPECT_TRUE(
1326 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
1327
1328 // Array indexing is not represented as operator.
1329 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
1330
1331 // Overloaded operators do not match at all.
1332 EXPECT_TRUE(notMatches(
1333 "struct A { bool operator&&(const A &a) const { return false; } };"
1334 "void x() { A a, b; a && b; }",
1335 binaryOperator()));
1336}
1337
1338TEST(MatchUnaryOperator, HasOperatorName) {
1339 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
1340
1341 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
1342 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
1343}
1344
1345TEST(MatchUnaryOperator, HasUnaryOperand) {
1346 StatementMatcher OperatorOnFalse =
1347 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
1348
1349 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
1350 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
1351}
1352
1353TEST(Matcher, UnaryOperatorTypes) {
1354 // Integration test that verifies the AST provides all unary operators in
1355 // a way we expect.
1356 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
1357 EXPECT_TRUE(
1358 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
1359 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
1360 EXPECT_TRUE(
1361 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
1362 EXPECT_TRUE(
1363 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
1364 EXPECT_TRUE(
1365 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
1366 EXPECT_TRUE(
1367 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
1368 EXPECT_TRUE(
1369 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
1370 EXPECT_TRUE(
1371 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
1372 EXPECT_TRUE(
1373 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
1374
1375 // We don't match conversion operators.
1376 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
1377
1378 // Function calls are not represented as operator.
1379 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
1380
1381 // Overloaded operators do not match at all.
1382 // FIXME: We probably want to add that.
1383 EXPECT_TRUE(notMatches(
1384 "struct A { bool operator!() const { return false; } };"
1385 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
1386}
1387
1388TEST(Matcher, ConditionalOperator) {
1389 StatementMatcher Conditional = conditionalOperator(
1390 hasCondition(boolLiteral(equals(true))),
1391 hasTrueExpression(boolLiteral(equals(false))));
1392
1393 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
1394 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
1395 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
1396
1397 StatementMatcher ConditionalFalse = conditionalOperator(
1398 hasFalseExpression(boolLiteral(equals(false))));
1399
1400 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1401 EXPECT_TRUE(
1402 notMatches("void x() { true ? false : true; }", ConditionalFalse));
1403}
1404
1405TEST(Matcher, HasNameSupportsNamespaces) {
1406 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1407 record(hasName("a::b::C"))));
1408 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1409 record(hasName("::a::b::C"))));
1410 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1411 record(hasName("b::C"))));
1412 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1413 record(hasName("C"))));
1414 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1415 record(hasName("c::b::C"))));
1416 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1417 record(hasName("a::c::C"))));
1418 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1419 record(hasName("a::b::A"))));
1420 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1421 record(hasName("::C"))));
1422 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1423 record(hasName("::b::C"))));
1424 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1425 record(hasName("z::a::b::C"))));
1426 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1427 record(hasName("a+b::C"))));
1428 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
1429 record(hasName("C"))));
1430}
1431
1432TEST(Matcher, HasNameSupportsOuterClasses) {
1433 EXPECT_TRUE(
1434 matches("class A { class B { class C; }; };", record(hasName("A::B::C"))));
1435 EXPECT_TRUE(
1436 matches("class A { class B { class C; }; };",
1437 record(hasName("::A::B::C"))));
1438 EXPECT_TRUE(
1439 matches("class A { class B { class C; }; };", record(hasName("B::C"))));
1440 EXPECT_TRUE(
1441 matches("class A { class B { class C; }; };", record(hasName("C"))));
1442 EXPECT_TRUE(
1443 notMatches("class A { class B { class C; }; };",
1444 record(hasName("c::B::C"))));
1445 EXPECT_TRUE(
1446 notMatches("class A { class B { class C; }; };",
1447 record(hasName("A::c::C"))));
1448 EXPECT_TRUE(
1449 notMatches("class A { class B { class C; }; };",
1450 record(hasName("A::B::A"))));
1451 EXPECT_TRUE(
1452 notMatches("class A { class B { class C; }; };", record(hasName("::C"))));
1453 EXPECT_TRUE(
1454 notMatches("class A { class B { class C; }; };",
1455 record(hasName("::B::C"))));
1456 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
1457 record(hasName("z::A::B::C"))));
1458 EXPECT_TRUE(
1459 notMatches("class A { class B { class C; }; };",
1460 record(hasName("A+B::C"))));
1461}
1462
1463TEST(Matcher, IsDefinition) {
1464 DeclarationMatcher DefinitionOfClassA =
1465 record(hasName("A"), isDefinition());
1466 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
1467 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
1468
1469 DeclarationMatcher DefinitionOfVariableA =
1470 variable(hasName("a"), isDefinition());
1471 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
1472 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
1473
1474 DeclarationMatcher DefinitionOfMethodA =
1475 method(hasName("a"), isDefinition());
1476 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
1477 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
1478}
1479
1480TEST(Matcher, OfClass) {
1481 StatementMatcher Constructor = constructorCall(hasDeclaration(method(
1482 ofClass(hasName("X")))));
1483
1484 EXPECT_TRUE(
1485 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
1486 EXPECT_TRUE(
1487 matches("class X { public: X(); }; void x(int) { X x = X(); }",
1488 Constructor));
1489 EXPECT_TRUE(
1490 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
1491 Constructor));
1492}
1493
1494TEST(Matcher, VisitsTemplateInstantiations) {
1495 EXPECT_TRUE(matches(
1496 "class A { public: void x(); };"
1497 "template <typename T> class B { public: void y() { T t; t.x(); } };"
1498 "void f() { B<A> b; b.y(); }", call(callee(method(hasName("x"))))));
1499
1500 EXPECT_TRUE(matches(
1501 "class A { public: void x(); };"
1502 "class C {"
1503 " public:"
1504 " template <typename T> class B { public: void y() { T t; t.x(); } };"
1505 "};"
1506 "void f() {"
1507 " C::B<A> b; b.y();"
1508 "}", record(hasName("C"),
1509 hasDescendant(call(callee(method(hasName("x"))))))));
1510}
1511
1512// For testing AST_MATCHER_P().
1513AST_MATCHER_P(clang::Decl, just, internal::Matcher<clang::Decl>, AMatcher) {
1514 // Make sure all special variables are used: node, match_finder,
1515 // bound_nodes_builder, and the parameter named 'AMatcher'.
1516 return AMatcher.matches(Node, Finder, Builder);
1517}
1518
1519TEST(AstMatcherPMacro, Works) {
1520 DeclarationMatcher HasClassB = just(has(id("b", record(hasName("B")))));
1521
1522 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
1523 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("b")));
1524
1525 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
1526 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("a")));
1527
1528 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
1529 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("b")));
1530}
1531
1532AST_POLYMORPHIC_MATCHER_P(
1533 polymorphicHas, internal::Matcher<clang::Decl>, AMatcher) {
1534 TOOLING_COMPILE_ASSERT((llvm::is_same<NodeType, clang::Decl>::value) ||
1535 (llvm::is_same<NodeType, clang::Stmt>::value),
1536 assert_node_type_is_accessible);
1537 internal::TypedBaseMatcher<clang::Decl> ChildMatcher(AMatcher);
1538 return Finder->matchesChildOf(
1539 Node, ChildMatcher, Builder,
1540 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1541 ASTMatchFinder::BK_First);
1542}
1543
1544TEST(AstPolymorphicMatcherPMacro, Works) {
1545 DeclarationMatcher HasClassB = polymorphicHas(id("b", record(hasName("B"))));
1546
1547 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
1548 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("b")));
1549
1550 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
1551 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("a")));
1552
1553 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
1554 HasClassB, new VerifyIdIsBoundToDecl<clang::Decl>("b")));
1555
1556 StatementMatcher StatementHasClassB =
1557 polymorphicHas(record(hasName("B")));
1558
1559 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
1560}
1561
1562TEST(For, FindsForLoops) {
1563 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1564 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
1565}
1566
1567TEST(For, ReportsNoFalsePositives) {
1568 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1569 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
1570}
1571
1572TEST(CompoundStatement, HandlesSimpleCases) {
1573 EXPECT_TRUE(notMatches("void f();", compoundStatement()));
1574 EXPECT_TRUE(matches("void f() {}", compoundStatement()));
1575 EXPECT_TRUE(matches("void f() {{}}", compoundStatement()));
1576}
1577
1578TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
1579 // It's not a compound statement just because there's "{}" in the source
1580 // text. This is an AST search, not grep.
1581 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
1582 compoundStatement()));
1583 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
1584 compoundStatement()));
1585}
1586
1587TEST(HasBody, FindsBodyOfForLoop) {
1588 StatementMatcher HasCompoundStatementBody =
1589 forStmt(hasBody(compoundStatement()));
1590 EXPECT_TRUE(matches("void f() { for(;;) {} }",
1591 HasCompoundStatementBody));
1592 EXPECT_TRUE(notMatches("void f() { for(;;); }",
1593 HasCompoundStatementBody));
1594}
1595
1596TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
1597 // The simplest case: every compound statement is in a function
1598 // definition, and the function body itself must be a compound
1599 // statement.
1600 EXPECT_TRUE(matches("void f() { for (;;); }",
1601 compoundStatement(hasAnySubstatement(forStmt()))));
1602}
1603
1604TEST(HasAnySubstatement, IsNotRecursive) {
1605 // It's really "has any immediate substatement".
1606 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
1607 compoundStatement(hasAnySubstatement(forStmt()))));
1608}
1609
1610TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
1611 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
1612 compoundStatement(hasAnySubstatement(forStmt()))));
1613}
1614
1615TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
1616 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
1617 compoundStatement(hasAnySubstatement(forStmt()))));
1618}
1619
1620TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
1621 EXPECT_TRUE(matches("void f() { }",
1622 compoundStatement(statementCountIs(0))));
1623 EXPECT_TRUE(notMatches("void f() {}",
1624 compoundStatement(statementCountIs(1))));
1625}
1626
1627TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
1628 EXPECT_TRUE(matches("void f() { 1; }",
1629 compoundStatement(statementCountIs(1))));
1630 EXPECT_TRUE(notMatches("void f() { 1; }",
1631 compoundStatement(statementCountIs(0))));
1632 EXPECT_TRUE(notMatches("void f() { 1; }",
1633 compoundStatement(statementCountIs(2))));
1634}
1635
1636TEST(StatementCountIs, WorksWithMultipleStatements) {
1637 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
1638 compoundStatement(statementCountIs(3))));
1639}
1640
1641TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
1642 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1643 compoundStatement(statementCountIs(1))));
1644 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1645 compoundStatement(statementCountIs(2))));
1646 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
1647 compoundStatement(statementCountIs(3))));
1648 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1649 compoundStatement(statementCountIs(4))));
1650}
1651
1652TEST(Member, WorksInSimplestCase) {
1653 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
1654 memberExpression(member(hasName("first")))));
1655}
1656
1657TEST(Member, DoesNotMatchTheBaseExpression) {
1658 // Don't pick out the wrong part of the member expression, this should
1659 // be checking the member (name) only.
1660 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
1661 memberExpression(member(hasName("first")))));
1662}
1663
1664TEST(Member, MatchesInMemberFunctionCall) {
1665 EXPECT_TRUE(matches("void f() {"
1666 " struct { void first() {}; } s;"
1667 " s.first();"
1668 "};",
1669 memberExpression(member(hasName("first")))));
1670}
1671
1672TEST(HasObjectExpression, DoesNotMatchMember) {
1673 EXPECT_TRUE(notMatches(
1674 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
1675 memberExpression(hasObjectExpression(hasType(record(hasName("X")))))));
1676}
1677
1678TEST(HasObjectExpression, MatchesBaseOfVariable) {
1679 EXPECT_TRUE(matches(
1680 "struct X { int m; }; void f(X x) { x.m; }",
1681 memberExpression(hasObjectExpression(hasType(record(hasName("X")))))));
1682 EXPECT_TRUE(matches(
1683 "struct X { int m; }; void f(X* x) { x->m; }",
1684 memberExpression(hasObjectExpression(
1685 hasType(pointsTo(record(hasName("X"))))))));
1686}
1687
1688TEST(HasObjectExpression,
1689 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
1690 EXPECT_TRUE(matches(
1691 "class X {}; struct S { X m; void f() { this->m; } };",
1692 memberExpression(hasObjectExpression(
1693 hasType(pointsTo(record(hasName("S"))))))));
1694 EXPECT_TRUE(matches(
1695 "class X {}; struct S { X m; void f() { m; } };",
1696 memberExpression(hasObjectExpression(
1697 hasType(pointsTo(record(hasName("S"))))))));
1698}
1699
1700TEST(Field, DoesNotMatchNonFieldMembers) {
1701 EXPECT_TRUE(notMatches("class X { void m(); };", field(hasName("m"))));
1702 EXPECT_TRUE(notMatches("class X { class m {}; };", field(hasName("m"))));
1703 EXPECT_TRUE(notMatches("class X { enum { m }; };", field(hasName("m"))));
1704 EXPECT_TRUE(notMatches("class X { enum m {}; };", field(hasName("m"))));
1705}
1706
1707TEST(Field, MatchesField) {
1708 EXPECT_TRUE(matches("class X { int m; };", field(hasName("m"))));
1709}
1710
1711TEST(IsConstQualified, MatchesConstInt) {
1712 EXPECT_TRUE(matches("const int i = 42;",
1713 variable(hasType(isConstQualified()))));
1714}
1715
1716TEST(IsConstQualified, MatchesConstPointer) {
1717 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
1718 variable(hasType(isConstQualified()))));
1719}
1720
1721TEST(IsConstQualified, MatchesThroughTypedef) {
1722 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
1723 variable(hasType(isConstQualified()))));
1724 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
1725 variable(hasType(isConstQualified()))));
1726}
1727
1728TEST(IsConstQualified, DoesNotMatchInappropriately) {
1729 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
1730 variable(hasType(isConstQualified()))));
1731 EXPECT_TRUE(notMatches("int const* p;",
1732 variable(hasType(isConstQualified()))));
1733}
1734
1735TEST(ReinterpretCast, MatchesSimpleCase) {
1736 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1737 expression(reinterpretCast())));
1738}
1739
1740TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
1741 EXPECT_TRUE(notMatches("char* p = (char*)(&p);",
1742 expression(reinterpretCast())));
1743 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1744 expression(reinterpretCast())));
1745 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1746 expression(reinterpretCast())));
1747 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1748 "B b;"
1749 "D* p = dynamic_cast<D*>(&b);",
1750 expression(reinterpretCast())));
1751}
1752
1753TEST(FunctionalCast, MatchesSimpleCase) {
1754 std::string foo_class = "class Foo { public: Foo(char*); };";
1755 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
1756 expression(functionalCast())));
1757}
1758
1759TEST(FunctionalCast, DoesNotMatchOtherCasts) {
1760 std::string FooClass = "class Foo { public: Foo(char*); };";
1761 EXPECT_TRUE(
1762 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
1763 expression(functionalCast())));
1764 EXPECT_TRUE(
1765 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
1766 expression(functionalCast())));
1767}
1768
1769TEST(DynamicCast, MatchesSimpleCase) {
1770 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1771 "B b;"
1772 "D* p = dynamic_cast<D*>(&b);",
1773 expression(dynamicCast())));
1774}
1775
1776TEST(StaticCast, MatchesSimpleCase) {
1777 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
1778 expression(staticCast())));
1779}
1780
1781TEST(StaticCast, DoesNotMatchOtherCasts) {
1782 EXPECT_TRUE(notMatches("char* p = (char*)(&p);",
1783 expression(staticCast())));
1784 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1785 expression(staticCast())));
1786 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1787 expression(staticCast())));
1788 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1789 "B b;"
1790 "D* p = dynamic_cast<D*>(&b);",
1791 expression(staticCast())));
1792}
1793
1794TEST(HasDestinationType, MatchesSimpleCase) {
1795 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
1796 expression(
1797 staticCast(hasDestinationType(
1798 pointsTo(TypeMatcher(anything())))))));
1799}
1800
1801TEST(HasSourceExpression, MatchesSimpleCase) {
1802 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
1803 "void r() {string a_string; URL url = a_string; }",
1804 expression(implicitCast(
1805 hasSourceExpression(constructorCall())))));
1806}
1807
1808TEST(Statement, DoesNotMatchDeclarations) {
1809 EXPECT_TRUE(notMatches("class X {};", statement()));
1810}
1811
1812TEST(Statement, MatchesCompoundStatments) {
1813 EXPECT_TRUE(matches("void x() {}", statement()));
1814}
1815
1816TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
1817 EXPECT_TRUE(notMatches("void x() {}", declarationStatement()));
1818}
1819
1820TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
1821 EXPECT_TRUE(matches("void x() { int a; }", declarationStatement()));
1822}
1823
1824TEST(While, MatchesWhileLoops) {
1825 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1826 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
1827 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
1828}
1829
1830TEST(Do, MatchesDoLoops) {
1831 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
1832 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
1833}
1834
1835TEST(Do, DoesNotMatchWhileLoops) {
1836 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
1837}
1838
1839TEST(SwitchCase, MatchesCase) {
1840 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1841 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1842 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1843 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1844}
1845
1846TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
1847 EXPECT_TRUE(notMatches(
1848 "void x() { if(true) {} }",
1849 ifStmt(hasConditionVariableStatement(declarationStatement()))));
1850 EXPECT_TRUE(notMatches(
1851 "void x() { int x; if((x = 42)) {} }",
1852 ifStmt(hasConditionVariableStatement(declarationStatement()))));
1853}
1854
1855TEST(HasConditionVariableStatement, MatchesConditionVariables) {
1856 EXPECT_TRUE(matches(
1857 "void x() { if(int* a = 0) {} }",
1858 ifStmt(hasConditionVariableStatement(declarationStatement()))));
1859}
1860
1861TEST(ForEach, BindsOneNode) {
1862 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
1863 record(hasName("C"), forEach(id("x", field(hasName("x"))))),
1864 new VerifyIdIsBoundToDecl<clang::FieldDecl>("x", 1)));
1865}
1866
1867TEST(ForEach, BindsMultipleNodes) {
1868 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
1869 record(hasName("C"), forEach(id("f", field()))),
1870 new VerifyIdIsBoundToDecl<clang::FieldDecl>("f", 3)));
1871}
1872
1873TEST(ForEach, BindsRecursiveCombinations) {
1874 EXPECT_TRUE(matchAndVerifyResultTrue(
1875 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
1876 record(hasName("C"), forEach(record(forEach(id("f", field()))))),
1877 new VerifyIdIsBoundToDecl<clang::FieldDecl>("f", 4)));
1878}
1879
1880TEST(ForEachDescendant, BindsOneNode) {
1881 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
1882 record(hasName("C"), forEachDescendant(id("x", field(hasName("x"))))),
1883 new VerifyIdIsBoundToDecl<clang::FieldDecl>("x", 1)));
1884}
1885
1886TEST(ForEachDescendant, BindsMultipleNodes) {
1887 EXPECT_TRUE(matchAndVerifyResultTrue(
1888 "class C { class D { int x; int y; }; "
1889 " class E { class F { int y; int z; }; }; };",
1890 record(hasName("C"), forEachDescendant(id("f", field()))),
1891 new VerifyIdIsBoundToDecl<clang::FieldDecl>("f", 4)));
1892}
1893
1894TEST(ForEachDescendant, BindsRecursiveCombinations) {
1895 EXPECT_TRUE(matchAndVerifyResultTrue(
1896 "class C { class D { "
1897 " class E { class F { class G { int y; int z; }; }; }; }; };",
1898 record(hasName("C"), forEachDescendant(record(
1899 forEachDescendant(id("f", field()))))),
1900 new VerifyIdIsBoundToDecl<clang::FieldDecl>("f", 8)));
1901}
1902
1903
1904TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
1905 // Make sure that we can both match the class by name (::X) and by the type
1906 // the template was instantiated with (via a field).
1907
1908 EXPECT_TRUE(matches(
1909 "template <typename T> class X {}; class A {}; X<A> x;",
1910 record(hasName("::X"), isTemplateInstantiation())));
1911
1912 EXPECT_TRUE(matches(
1913 "template <typename T> class X { T t; }; class A {}; X<A> x;",
1914 record(isTemplateInstantiation(), hasDescendant(
1915 field(hasType(record(hasName("A"))))))));
1916}
1917
1918TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
1919 EXPECT_TRUE(matches(
1920 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
1921 function(hasParameter(0, hasType(record(hasName("A")))),
1922 isTemplateInstantiation())));
1923}
1924
1925TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
1926 EXPECT_TRUE(matches(
1927 "template <typename T> class X { T t; }; class A {};"
1928 "template class X<A>;",
1929 record(isTemplateInstantiation(), hasDescendant(
1930 field(hasType(record(hasName("A"))))))));
1931}
1932
1933TEST(IsTemplateInstantiation,
1934 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
1935 EXPECT_TRUE(matches(
1936 "template <typename T> class X {};"
1937 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
1938 record(hasName("::X"), isTemplateInstantiation())));
1939}
1940
1941TEST(IsTemplateInstantiation,
1942 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
1943 EXPECT_TRUE(matches(
1944 "class A {};"
1945 "class X {"
1946 " template <typename U> class Y { U u; };"
1947 " Y<A> y;"
1948 "};",
1949 record(hasName("::X::Y"), isTemplateInstantiation())));
1950}
1951
1952TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
1953 // FIXME: Figure out whether this makes sense. It doesn't affect the
1954 // normal use case as long as the uppermost instantiation always is marked
1955 // as template instantiation, but it might be confusing as a predicate.
1956 EXPECT_TRUE(matches(
1957 "class A {};"
1958 "template <typename T> class X {"
1959 " template <typename U> class Y { U u; };"
1960 " Y<T> y;"
1961 "}; X<A> x;",
1962 record(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
1963}
1964
1965TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
1966 EXPECT_TRUE(notMatches(
1967 "template <typename T> class X {}; class A {};"
1968 "template <> class X<A> {}; X<A> x;",
1969 record(hasName("::X"), isTemplateInstantiation())));
1970}
1971
1972TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
1973 EXPECT_TRUE(notMatches(
1974 "class A {}; class Y { A a; };",
1975 record(isTemplateInstantiation())));
1976}
1977
1978} // end namespace ast_matchers
1979} // end namespace clang