blob: 7325e06503933b9e8e6e8f8eaebd6a9fcbae6808 [file] [log] [blame]
Manuel Klimek04616e42012-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"
Benjamin Kramere5015e52012-12-01 17:22:05 +000011#include "clang/AST/PrettyPrinter.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Chandler Carruth320d9662012-12-04 09:45:34 +000013#include "clang/ASTMatchers/ASTMatchers.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000014#include "clang/Tooling/Tooling.h"
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +000015#include "llvm/ADT/Triple.h"
16#include "llvm/Support/Host.h"
Manuel Klimek04616e42012-07-06 05:48:52 +000017#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000022#if GTEST_HAS_DEATH_TEST
Manuel Klimek04616e42012-07-06 05:48:52 +000023TEST(HasNameDeathTest, DiesOnEmptyName) {
24 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000025 DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000026 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
27 }, "");
28}
29
Daniel Jasper1dad1832012-07-10 20:20:19 +000030TEST(HasNameDeathTest, DiesOnEmptyPattern) {
31 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000032 DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
Daniel Jasper1dad1832012-07-10 20:20:19 +000033 EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
34 }, "");
35}
36
Manuel Klimek04616e42012-07-06 05:48:52 +000037TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
38 ASSERT_DEBUG_DEATH({
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000039 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
Manuel Klimek04616e42012-07-06 05:48:52 +000040 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
41 }, "");
42}
Benjamin Kramer60d7f5a2012-07-10 17:30:44 +000043#endif
Manuel Klimek04616e42012-07-06 05:48:52 +000044
Peter Collingbourne2b9471302013-11-07 22:30:32 +000045TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
46 MatchFinder Finder;
Craig Topper416fa342014-06-08 08:38:12 +000047 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
48 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
49 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
50 nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000051
52 // Do not accept non-toplevel matchers.
Craig Topper416fa342014-06-08 08:38:12 +000053 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
54 EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
55 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
Peter Collingbourne2b9471302013-11-07 22:30:32 +000056}
57
Manuel Klimeke9235692012-07-25 10:02:02 +000058TEST(Decl, MatchesDeclarations) {
59 EXPECT_TRUE(notMatches("", decl(usingDecl())));
60 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
61 decl(usingDecl())));
62}
63
Manuel Klimek04616e42012-07-06 05:48:52 +000064TEST(NameableDeclaration, MatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000065 DeclarationMatcher NamedX = namedDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +000066 EXPECT_TRUE(matches("typedef int X;", NamedX));
67 EXPECT_TRUE(matches("int X;", NamedX));
68 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
69 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
70 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
71 EXPECT_TRUE(matches("namespace X { }", NamedX));
Daniel Jasper1dad1832012-07-10 20:20:19 +000072 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
Manuel Klimek04616e42012-07-06 05:48:52 +000073
74 EXPECT_TRUE(notMatches("#define X 1", NamedX));
75}
76
Daniel Jasper1dad1832012-07-10 20:20:19 +000077TEST(NameableDeclaration, REMatchesVariousDecls) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000078 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000079 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
80 EXPECT_TRUE(matches("int Xb;", NamedX));
81 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
82 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
83 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
84 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
85 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
86
87 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
88
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000089 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000090 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
91 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
92
Daniel Jasperbd3d76d2012-08-24 05:12:34 +000093 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
Daniel Jasper1dad1832012-07-10 20:20:19 +000094 EXPECT_TRUE(matches("int abc;", Abc));
95 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
96 EXPECT_TRUE(notMatches("int cab;", Abc));
97 EXPECT_TRUE(matches("int cabc;", Abc));
Manuel Klimeke792efd2012-12-10 07:08:53 +000098
99 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
100 EXPECT_TRUE(matches("int k;", StartsWithK));
101 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
102 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
103 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
104 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000105}
106
Manuel Klimek04616e42012-07-06 05:48:52 +0000107TEST(DeclarationMatcher, MatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000108 DeclarationMatcher ClassMatcher(recordDecl());
Saleem Abdulrasool377066a2014-03-27 22:50:18 +0000109 llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
110 if (Triple.getOS() != llvm::Triple::Win32 ||
111 Triple.getEnvironment() != llvm::Triple::MSVC)
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +0000112 EXPECT_FALSE(matches("", ClassMatcher));
113 else
114 // Matches class type_info.
115 EXPECT_TRUE(matches("", ClassMatcher));
Manuel Klimek04616e42012-07-06 05:48:52 +0000116
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000117 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000118 EXPECT_TRUE(matches("class X;", ClassX));
119 EXPECT_TRUE(matches("class X {};", ClassX));
120 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
121 EXPECT_TRUE(notMatches("", ClassX));
122}
123
124TEST(DeclarationMatcher, ClassIsDerived) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000125 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000126
127 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000128 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
129 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
Manuel Klimek04616e42012-07-06 05:48:52 +0000130 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
131 EXPECT_TRUE(notMatches("", IsDerivedFromX));
132
Daniel Jasperd6b82cb2012-09-12 21:14:15 +0000133 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000134
135 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
136 EXPECT_TRUE(matches("class X {};", IsAX));
137 EXPECT_TRUE(matches("class X;", IsAX));
138 EXPECT_TRUE(notMatches("class Y;", IsAX));
139 EXPECT_TRUE(notMatches("", IsAX));
140
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 DeclarationMatcher ZIsDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000142 recordDecl(hasName("Z"), isDerivedFrom("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000143 EXPECT_TRUE(
144 matches("class X {}; class Y : public X {}; class Z : public Y {};",
145 ZIsDerivedFromX));
146 EXPECT_TRUE(
147 matches("class X {};"
148 "template<class T> class Y : public X {};"
149 "class Z : public Y<int> {};", ZIsDerivedFromX));
150 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
151 ZIsDerivedFromX));
152 EXPECT_TRUE(
153 matches("template<class T> class X {}; "
154 "template<class T> class Z : public X<T> {};",
155 ZIsDerivedFromX));
156 EXPECT_TRUE(
157 matches("template<class T, class U=T> class X {}; "
158 "template<class T> class Z : public X<T> {};",
159 ZIsDerivedFromX));
160 EXPECT_TRUE(
161 notMatches("template<class X> class A { class Z : public X {}; };",
162 ZIsDerivedFromX));
163 EXPECT_TRUE(
164 matches("template<class X> class A { public: class Z : public X {}; }; "
165 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
166 EXPECT_TRUE(
167 matches("template <class T> class X {}; "
168 "template<class Y> class A { class Z : public X<Y> {}; };",
169 ZIsDerivedFromX));
170 EXPECT_TRUE(
171 notMatches("template<template<class T> class X> class A { "
172 " class Z : public X<int> {}; };", ZIsDerivedFromX));
173 EXPECT_TRUE(
174 matches("template<template<class T> class X> class A { "
175 " public: class Z : public X<int> {}; }; "
176 "template<class T> class X {}; void y() { A<X>::Z z; }",
177 ZIsDerivedFromX));
178 EXPECT_TRUE(
179 notMatches("template<class X> class A { class Z : public X::D {}; };",
180 ZIsDerivedFromX));
181 EXPECT_TRUE(
182 matches("template<class X> class A { public: "
183 " class Z : public X::D {}; }; "
184 "class Y { public: class X {}; typedef X D; }; "
185 "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
186 EXPECT_TRUE(
187 matches("class X {}; typedef X Y; class Z : public Y {};",
188 ZIsDerivedFromX));
189 EXPECT_TRUE(
190 matches("template<class T> class Y { typedef typename T::U X; "
191 " class Z : public X {}; };", ZIsDerivedFromX));
192 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
193 ZIsDerivedFromX));
194 EXPECT_TRUE(
195 notMatches("template<class T> class X {}; "
196 "template<class T> class A { class Z : public X<T>::D {}; };",
197 ZIsDerivedFromX));
198 EXPECT_TRUE(
199 matches("template<class T> class X { public: typedef X<T> D; }; "
200 "template<class T> class A { public: "
201 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
202 ZIsDerivedFromX));
203 EXPECT_TRUE(
204 notMatches("template<class X> class A { class Z : public X::D::E {}; };",
205 ZIsDerivedFromX));
206 EXPECT_TRUE(
207 matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
208 ZIsDerivedFromX));
209 EXPECT_TRUE(
210 matches("class X {}; class Y : public X {}; "
211 "typedef Y V; typedef V W; class Z : public W {};",
212 ZIsDerivedFromX));
213 EXPECT_TRUE(
214 matches("template<class T, class U> class X {}; "
215 "template<class T> class A { class Z : public X<T, int> {}; };",
216 ZIsDerivedFromX));
217 EXPECT_TRUE(
218 notMatches("template<class X> class D { typedef X A; typedef A B; "
219 " typedef B C; class Z : public C {}; };",
220 ZIsDerivedFromX));
221 EXPECT_TRUE(
222 matches("class X {}; typedef X A; typedef A B; "
223 "class Z : public B {};", ZIsDerivedFromX));
224 EXPECT_TRUE(
225 matches("class X {}; typedef X A; typedef A B; typedef B C; "
226 "class Z : public C {};", ZIsDerivedFromX));
227 EXPECT_TRUE(
228 matches("class U {}; typedef U X; typedef X V; "
229 "class Z : public V {};", ZIsDerivedFromX));
230 EXPECT_TRUE(
231 matches("class Base {}; typedef Base X; "
232 "class Z : public Base {};", ZIsDerivedFromX));
233 EXPECT_TRUE(
234 matches("class Base {}; typedef Base Base2; typedef Base2 X; "
235 "class Z : public Base {};", ZIsDerivedFromX));
236 EXPECT_TRUE(
237 notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
238 "class Z : public Base {};", ZIsDerivedFromX));
239 EXPECT_TRUE(
240 matches("class A {}; typedef A X; typedef A Y; "
241 "class Z : public Y {};", ZIsDerivedFromX));
242 EXPECT_TRUE(
243 notMatches("template <typename T> class Z;"
244 "template <> class Z<void> {};"
245 "template <typename T> class Z : public Z<void> {};",
246 IsDerivedFromX));
247 EXPECT_TRUE(
248 matches("template <typename T> class X;"
249 "template <> class X<void> {};"
250 "template <typename T> class X : public X<void> {};",
251 IsDerivedFromX));
252 EXPECT_TRUE(matches(
253 "class X {};"
254 "template <typename T> class Z;"
255 "template <> class Z<void> {};"
256 "template <typename T> class Z : public Z<void>, public X {};",
257 ZIsDerivedFromX));
Manuel Klimek5472a522012-12-04 13:40:29 +0000258 EXPECT_TRUE(
259 notMatches("template<int> struct X;"
260 "template<int i> struct X : public X<i-1> {};",
261 recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
262 EXPECT_TRUE(matches(
263 "struct A {};"
264 "template<int> struct X;"
265 "template<int i> struct X : public X<i-1> {};"
266 "template<> struct X<0> : public A {};"
267 "struct B : public X<42> {};",
268 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000269
270 // FIXME: Once we have better matchers for template type matching,
271 // get rid of the Variable(...) matching and match the right template
272 // declarations directly.
273 const char *RecursiveTemplateOneParameter =
274 "class Base1 {}; class Base2 {};"
275 "template <typename T> class Z;"
276 "template <> class Z<void> : public Base1 {};"
277 "template <> class Z<int> : public Base2 {};"
278 "template <> class Z<float> : public Z<void> {};"
279 "template <> class Z<double> : public Z<int> {};"
280 "template <typename T> class Z : public Z<float>, public Z<double> {};"
281 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
282 EXPECT_TRUE(matches(
283 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000284 varDecl(hasName("z_float"),
285 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000286 EXPECT_TRUE(notMatches(
287 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000288 varDecl(hasName("z_float"),
289 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000290 EXPECT_TRUE(matches(
291 RecursiveTemplateOneParameter,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000292 varDecl(hasName("z_char"),
293 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
294 isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000295
296 const char *RecursiveTemplateTwoParameters =
297 "class Base1 {}; class Base2 {};"
298 "template <typename T1, typename T2> class Z;"
299 "template <typename T> class Z<void, T> : public Base1 {};"
300 "template <typename T> class Z<int, T> : public Base2 {};"
301 "template <typename T> class Z<float, T> : public Z<void, T> {};"
302 "template <typename T> class Z<double, T> : public Z<int, T> {};"
303 "template <typename T1, typename T2> class Z : "
304 " public Z<float, T2>, public Z<double, T2> {};"
305 "void f() { Z<float, void> z_float; Z<double, void> z_double; "
306 " Z<char, void> z_char; }";
307 EXPECT_TRUE(matches(
308 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000309 varDecl(hasName("z_float"),
310 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000311 EXPECT_TRUE(notMatches(
312 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000313 varDecl(hasName("z_float"),
314 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000315 EXPECT_TRUE(matches(
316 RecursiveTemplateTwoParameters,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000317 varDecl(hasName("z_char"),
318 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
319 isDerivedFrom("Base2")))))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000320 EXPECT_TRUE(matches(
321 "namespace ns { class X {}; class Y : public X {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000322 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000323 EXPECT_TRUE(notMatches(
324 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000325 recordDecl(isDerivedFrom("::ns::X"))));
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000326
327 EXPECT_TRUE(matches(
328 "class X {}; class Y : public X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000329 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
Manuel Klimek1863e502013-08-02 21:24:09 +0000330
331 EXPECT_TRUE(matches(
332 "template<typename T> class X {};"
333 "template<typename T> using Z = X<T>;"
334 "template <typename T> class Y : Z<T> {};",
335 recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000336}
337
Edwin Vane0a4836e2013-03-06 17:02:57 +0000338TEST(DeclarationMatcher, hasMethod) {
339 EXPECT_TRUE(matches("class A { void func(); };",
340 recordDecl(hasMethod(hasName("func")))));
341 EXPECT_TRUE(notMatches("class A { void func(); };",
342 recordDecl(hasMethod(isPublic()))));
343}
344
Daniel Jasper83dafaf2012-09-18 14:17:42 +0000345TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
346 EXPECT_TRUE(matches(
347 "template <typename T> struct A {"
348 " template <typename T2> struct F {};"
349 "};"
350 "template <typename T> struct B : A<T>::template F<T> {};"
351 "B<int> b;",
352 recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
353}
354
Edwin Vaneb6eae142013-02-25 20:43:32 +0000355TEST(DeclarationMatcher, hasDeclContext) {
356 EXPECT_TRUE(matches(
357 "namespace N {"
358 " namespace M {"
359 " class D {};"
360 " }"
361 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000362 recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000363 EXPECT_TRUE(notMatches(
364 "namespace N {"
365 " namespace M {"
366 " class D {};"
367 " }"
368 "}",
Daniel Jasper9fcdc462013-04-08 16:44:05 +0000369 recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
370
371 EXPECT_TRUE(matches("namespace {"
372 " namespace M {"
373 " class D {};"
374 " }"
375 "}",
376 recordDecl(hasDeclContext(namespaceDecl(
377 hasName("M"), hasDeclContext(namespaceDecl()))))));
Samuel Benzaquend93fcc12014-10-27 20:58:44 +0000378
379 EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +0000380}
381
Manuel Klimek94ad0bf2014-09-04 08:51:06 +0000382TEST(DeclarationMatcher, LinkageSpecification) {
383 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
384 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
385}
386
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000387TEST(ClassTemplate, DoesNotMatchClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000388 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000389 EXPECT_TRUE(notMatches("class X;", ClassX));
390 EXPECT_TRUE(notMatches("class X {};", ClassX));
391}
392
393TEST(ClassTemplate, MatchesClassTemplate) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000394 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000395 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
396 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
397}
398
399TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
400 EXPECT_TRUE(notMatches("template<typename T> class X { };"
401 "template<> class X<int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000402 classTemplateDecl(hasName("X"),
403 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000404}
405
406TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
407 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
408 "template<typename T> class X<T, int> { int a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000409 classTemplateDecl(hasName("X"),
410 hasDescendant(fieldDecl(hasName("a"))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +0000411}
412
Daniel Jasper4e566c42012-07-12 08:50:38 +0000413TEST(AllOf, AllOverloadsWork) {
414 const char Program[] =
Edwin Vanee9dd3602013-02-12 13:55:40 +0000415 "struct T { };"
416 "int f(int, T*, int, int);"
417 "void g(int x) { T t; f(x, &t, 3, 4); }";
Daniel Jasper4e566c42012-07-12 08:50:38 +0000418 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000419 callExpr(allOf(callee(functionDecl(hasName("f"))),
420 hasArgument(0, declRefExpr(to(varDecl())))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000421 EXPECT_TRUE(matches(Program,
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000422 callExpr(allOf(callee(functionDecl(hasName("f"))),
423 hasArgument(0, declRefExpr(to(varDecl()))),
424 hasArgument(1, hasType(pointsTo(
425 recordDecl(hasName("T")))))))));
Edwin Vanee9dd3602013-02-12 13:55:40 +0000426 EXPECT_TRUE(matches(Program,
427 callExpr(allOf(callee(functionDecl(hasName("f"))),
428 hasArgument(0, declRefExpr(to(varDecl()))),
429 hasArgument(1, hasType(pointsTo(
430 recordDecl(hasName("T"))))),
431 hasArgument(2, integerLiteral(equals(3)))))));
432 EXPECT_TRUE(matches(Program,
433 callExpr(allOf(callee(functionDecl(hasName("f"))),
434 hasArgument(0, declRefExpr(to(varDecl()))),
435 hasArgument(1, hasType(pointsTo(
436 recordDecl(hasName("T"))))),
437 hasArgument(2, integerLiteral(equals(3))),
438 hasArgument(3, integerLiteral(equals(4)))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +0000439}
440
Manuel Klimek04616e42012-07-06 05:48:52 +0000441TEST(DeclarationMatcher, MatchAnyOf) {
442 DeclarationMatcher YOrZDerivedFromX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000443 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000444 EXPECT_TRUE(
445 matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
446 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
447 EXPECT_TRUE(
448 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
449 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
450
Daniel Jasper84c763e2012-07-15 19:57:12 +0000451 DeclarationMatcher XOrYOrZOrU =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000452 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
Daniel Jasper84c763e2012-07-15 19:57:12 +0000453 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
454 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
455
Manuel Klimek04616e42012-07-06 05:48:52 +0000456 DeclarationMatcher XOrYOrZOrUOrV =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000457 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
458 hasName("V")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000459 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
460 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
461 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
462 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
463 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
464 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
Samuel Benzaquena1170022014-10-06 13:14:30 +0000465
466 StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
467 EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
468 EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
469 EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
Manuel Klimek04616e42012-07-06 05:48:52 +0000470}
471
472TEST(DeclarationMatcher, MatchHas) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000473 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000474 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
475 EXPECT_TRUE(matches("class X {};", HasClassX));
476
477 DeclarationMatcher YHasClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000478 recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000479 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
480 EXPECT_TRUE(notMatches("class X {};", YHasClassX));
481 EXPECT_TRUE(
482 notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
483}
484
485TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
486 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000487 recordDecl(
488 has(recordDecl(
489 has(recordDecl(hasName("X"))),
490 has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000491 hasName("Z"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000492 has(recordDecl(
493 has(recordDecl(hasName("A"))),
494 has(recordDecl(hasName("B"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000495 hasName("C"))),
496 hasName("F"));
497
498 EXPECT_TRUE(matches(
499 "class F {"
500 " class Z {"
501 " class X {};"
502 " class Y {};"
503 " };"
504 " class C {"
505 " class A {};"
506 " class B {};"
507 " };"
508 "};", Recursive));
509
510 EXPECT_TRUE(matches(
511 "class F {"
512 " class Z {"
513 " class A {};"
514 " class X {};"
515 " class Y {};"
516 " };"
517 " class C {"
518 " class X {};"
519 " class A {};"
520 " class B {};"
521 " };"
522 "};", Recursive));
523
524 EXPECT_TRUE(matches(
525 "class O1 {"
526 " class O2 {"
527 " class F {"
528 " class Z {"
529 " class A {};"
530 " class X {};"
531 " class Y {};"
532 " };"
533 " class C {"
534 " class X {};"
535 " class A {};"
536 " class B {};"
537 " };"
538 " };"
539 " };"
540 "};", Recursive));
541}
542
543TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
544 DeclarationMatcher Recursive =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000545 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000546 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000547 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000548 anyOf(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000549 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000550 hasName("X"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000551 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000552 hasName("Y"))),
553 hasName("Z")))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000554 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000555 anyOf(
556 hasName("C"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000557 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000558 hasName("A"))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000559 has(recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000560 hasName("B")))))),
561 hasName("F")));
562
563 EXPECT_TRUE(matches("class F {};", Recursive));
564 EXPECT_TRUE(matches("class Z {};", Recursive));
565 EXPECT_TRUE(matches("class C {};", Recursive));
566 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
567 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
568 EXPECT_TRUE(
569 matches("class O1 { class O2 {"
570 " class M { class N { class B {}; }; }; "
571 "}; };", Recursive));
572}
573
574TEST(DeclarationMatcher, MatchNot) {
575 DeclarationMatcher NotClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000576 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000577 isDerivedFrom("Y"),
Manuel Klimek04616e42012-07-06 05:48:52 +0000578 unless(hasName("X")));
579 EXPECT_TRUE(notMatches("", NotClassX));
580 EXPECT_TRUE(notMatches("class Y {};", NotClassX));
581 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
582 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
583 EXPECT_TRUE(
584 notMatches("class Y {}; class Z {}; class X : public Y {};",
585 NotClassX));
586
587 DeclarationMatcher ClassXHasNotClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000588 recordDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +0000589 hasName("X"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000590 has(recordDecl(hasName("Z"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000591 unless(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000592 has(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000593 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
594 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
595 ClassXHasNotClassY));
Samuel Benzaquen20099602014-10-13 17:38:12 +0000596
597 DeclarationMatcher NamedNotRecord =
598 namedDecl(hasName("Foo"), unless(recordDecl()));
599 EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
600 EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
Manuel Klimek04616e42012-07-06 05:48:52 +0000601}
602
603TEST(DeclarationMatcher, HasDescendant) {
604 DeclarationMatcher ZDescendantClassX =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000605 recordDecl(
606 hasDescendant(recordDecl(hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000607 hasName("Z"));
608 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
609 EXPECT_TRUE(
610 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
611 EXPECT_TRUE(
612 matches("class Z { class A { class Y { class X {}; }; }; };",
613 ZDescendantClassX));
614 EXPECT_TRUE(
615 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
616 ZDescendantClassX));
617 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
618
619 DeclarationMatcher ZDescendantClassXHasClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000620 recordDecl(
621 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000622 hasName("X"))),
623 hasName("Z"));
624 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
625 ZDescendantClassXHasClassY));
626 EXPECT_TRUE(
627 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
628 ZDescendantClassXHasClassY));
629 EXPECT_TRUE(notMatches(
630 "class Z {"
631 " class A {"
632 " class B {"
633 " class X {"
634 " class C {"
635 " class Y {};"
636 " };"
637 " };"
638 " }; "
639 " };"
640 "};", ZDescendantClassXHasClassY));
641
642 DeclarationMatcher ZDescendantClassXDescendantClassY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000643 recordDecl(
644 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
645 hasName("X"))),
Manuel Klimek04616e42012-07-06 05:48:52 +0000646 hasName("Z"));
647 EXPECT_TRUE(
648 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
649 ZDescendantClassXDescendantClassY));
650 EXPECT_TRUE(matches(
651 "class Z {"
652 " class A {"
653 " class X {"
654 " class B {"
655 " class Y {};"
656 " };"
657 " class Y {};"
658 " };"
659 " };"
660 "};", ZDescendantClassXDescendantClassY));
661}
662
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000663TEST(DeclarationMatcher, HasDescendantMemoization) {
664 DeclarationMatcher CannotMemoize =
665 decl(hasDescendant(typeLoc().bind("x")), has(decl()));
666 EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
667}
668
Samuel Benzaquenf28d9972014-10-01 15:08:07 +0000669TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
670 auto Name = hasName("i");
671 auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
672 auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
673 // Matching VD first should not make a cache hit for RD.
674 EXPECT_TRUE(notMatches("void f() { int i; }",
675 decl(hasDescendant(VD), hasDescendant(RD))));
676 EXPECT_TRUE(notMatches("void f() { int i; }",
677 decl(hasDescendant(RD), hasDescendant(VD))));
678 // Not matching RD first should not make a cache hit for VD either.
679 EXPECT_TRUE(matches("void f() { int i; }",
680 decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
681}
682
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000683TEST(DeclarationMatcher, HasAttr) {
684 EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
685 decl(hasAttr(clang::attr::WarnUnused))));
686 EXPECT_FALSE(matches("struct X {};",
687 decl(hasAttr(clang::attr::WarnUnused))));
688}
689
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000690TEST(DeclarationMatcher, MatchCudaDecl) {
691 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
692 "void g() { f<<<1, 2>>>(); }",
693 CUDAKernelCallExpr()));
694 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000695 hasAttr(clang::attr::CUDADevice)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000696 EXPECT_TRUE(notMatchesWithCuda("void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000697 CUDAKernelCallExpr()));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000698 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
Manuel Klimek3fe8a382014-08-25 11:23:50 +0000699 hasAttr(clang::attr::CUDAGlobal)));
Manuel Klimekd52a3b82014-08-05 09:45:53 +0000700}
701
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000702// Implements a run method that returns whether BoundNodes contains a
703// Decl bound to Id that can be dynamically cast to T.
704// Optionally checks that the check succeeded a specific number of times.
705template <typename T>
706class VerifyIdIsBoundTo : public BoundNodesCallback {
707public:
708 // Create an object that checks that a node of type \c T was bound to \c Id.
709 // Does not check for a certain number of matches.
710 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
711 : Id(Id), ExpectedCount(-1), Count(0) {}
712
713 // Create an object that checks that a node of type \c T was bound to \c Id.
714 // Checks that there were exactly \c ExpectedCount matches.
715 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
716 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
717
718 // Create an object that checks that a node of type \c T was bound to \c Id.
719 // Checks that there was exactly one match with the name \c ExpectedName.
720 // Note that \c T must be a NamedDecl for this to work.
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000721 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
722 int ExpectedCount = 1)
723 : Id(Id), ExpectedCount(ExpectedCount), Count(0),
724 ExpectedName(ExpectedName) {}
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000725
Craig Toppera798a9d2014-03-02 09:32:10 +0000726 void onEndOfTranslationUnit() override {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000727 if (ExpectedCount != -1)
728 EXPECT_EQ(ExpectedCount, Count);
729 if (!ExpectedName.empty())
730 EXPECT_EQ(ExpectedName, Name);
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000731 Count = 0;
732 Name.clear();
733 }
734
735 ~VerifyIdIsBoundTo() {
736 EXPECT_EQ(0, Count);
737 EXPECT_EQ("", Name);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000738 }
739
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000740 virtual bool run(const BoundNodes *Nodes) override {
Peter Collingbourne093a7292013-11-06 00:27:07 +0000741 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000742 if (Nodes->getNodeAs<T>(Id)) {
743 ++Count;
744 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
745 Name = Named->getNameAsString();
746 } else if (const NestedNameSpecifier *NNS =
747 Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
748 llvm::raw_string_ostream OS(Name);
749 NNS->print(OS, PrintingPolicy(LangOptions()));
750 }
Peter Collingbourne093a7292013-11-06 00:27:07 +0000751 BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
752 EXPECT_NE(M.end(), I);
753 if (I != M.end())
754 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000755 return true;
756 }
Craig Topper416fa342014-06-08 08:38:12 +0000757 EXPECT_TRUE(M.count(Id) == 0 ||
758 M.find(Id)->second.template get<T>() == nullptr);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000759 return false;
760 }
761
Fariborz Jahanian5afc8692014-10-01 16:56:40 +0000762 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) override {
Daniel Jaspere9aa6872012-10-29 10:48:25 +0000763 return run(Nodes);
764 }
765
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000766private:
767 const std::string Id;
768 const int ExpectedCount;
769 int Count;
770 const std::string ExpectedName;
771 std::string Name;
772};
773
774TEST(HasDescendant, MatchesDescendantTypes) {
775 EXPECT_TRUE(matches("void f() { int i = 3; }",
776 decl(hasDescendant(loc(builtinType())))));
777 EXPECT_TRUE(matches("void f() { int i = 3; }",
778 stmt(hasDescendant(builtinType()))));
779
780 EXPECT_TRUE(matches("void f() { int i = 3; }",
781 stmt(hasDescendant(loc(builtinType())))));
782 EXPECT_TRUE(matches("void f() { int i = 3; }",
783 stmt(hasDescendant(qualType(builtinType())))));
784
785 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
786 stmt(hasDescendant(isInteger()))));
787
788 EXPECT_TRUE(matchAndVerifyResultTrue(
789 "void f() { int a; float c; int d; int e; }",
790 functionDecl(forEachDescendant(
791 varDecl(hasDescendant(isInteger())).bind("x"))),
792 new VerifyIdIsBoundTo<Decl>("x", 3)));
793}
794
795TEST(HasDescendant, MatchesDescendantsOfTypes) {
796 EXPECT_TRUE(matches("void f() { int*** i; }",
797 qualType(hasDescendant(builtinType()))));
798 EXPECT_TRUE(matches("void f() { int*** i; }",
799 qualType(hasDescendant(
800 pointerType(pointee(builtinType()))))));
801 EXPECT_TRUE(matches("void f() { int*** i; }",
David Blaikieb61d0872013-02-18 19:04:16 +0000802 typeLoc(hasDescendant(loc(builtinType())))));
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000803
804 EXPECT_TRUE(matchAndVerifyResultTrue(
805 "void f() { int*** i; }",
806 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
807 new VerifyIdIsBoundTo<Type>("x", 2)));
808}
809
810TEST(Has, MatchesChildrenOfTypes) {
811 EXPECT_TRUE(matches("int i;",
812 varDecl(hasName("i"), has(isInteger()))));
813 EXPECT_TRUE(notMatches("int** i;",
814 varDecl(hasName("i"), has(isInteger()))));
815 EXPECT_TRUE(matchAndVerifyResultTrue(
816 "int (*f)(float, int);",
817 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
818 new VerifyIdIsBoundTo<QualType>("x", 2)));
819}
820
821TEST(Has, MatchesChildTypes) {
822 EXPECT_TRUE(matches(
823 "int* i;",
824 varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
825 EXPECT_TRUE(notMatches(
826 "int* i;",
827 varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
828}
829
Samuel Benzaquenc640ef52014-10-28 13:33:58 +0000830TEST(ValueDecl, Matches) {
831 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
832 valueDecl(hasType(asString("enum EnumType")))));
833 EXPECT_TRUE(matches("void FunctionDecl();",
834 valueDecl(hasType(asString("void (void)")))));
835}
836
Daniel Jasper1dad1832012-07-10 20:20:19 +0000837TEST(Enum, DoesNotMatchClasses) {
838 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
839}
840
841TEST(Enum, MatchesEnums) {
842 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
843}
844
845TEST(EnumConstant, Matches) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000846 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000847 EXPECT_TRUE(matches("enum X{ A };", Matcher));
848 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
849 EXPECT_TRUE(notMatches("enum X {};", Matcher));
850}
851
Manuel Klimek04616e42012-07-06 05:48:52 +0000852TEST(StatementMatcher, Has) {
853 StatementMatcher HasVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000854 expr(hasType(pointsTo(recordDecl(hasName("X")))),
855 has(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000856
857 EXPECT_TRUE(matches(
858 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
859 EXPECT_TRUE(notMatches(
860 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
861}
862
863TEST(StatementMatcher, HasDescendant) {
864 StatementMatcher HasDescendantVariableI =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000865 expr(hasType(pointsTo(recordDecl(hasName("X")))),
866 hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000867
868 EXPECT_TRUE(matches(
869 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
870 HasDescendantVariableI));
871 EXPECT_TRUE(notMatches(
872 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
873 HasDescendantVariableI));
874}
875
876TEST(TypeMatcher, MatchesClassType) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000877 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000878
879 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
880 EXPECT_TRUE(notMatches("class A {};", TypeA));
881
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000882 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000883
884 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
885 TypeDerivedFromA));
886 EXPECT_TRUE(notMatches("class A {};", TypeA));
887
888 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000889 recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000890
891 EXPECT_TRUE(
892 matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
893}
894
Manuel Klimek04616e42012-07-06 05:48:52 +0000895TEST(Matcher, BindMatchedNodes) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000896 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000897
898 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000899 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000900
901 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000902 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000903
904 TypeMatcher TypeAHasClassB = hasDeclaration(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000905 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000906
907 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
908 TypeAHasClassB,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000909 new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000910
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000911 StatementMatcher MethodX =
912 callExpr(callee(methodDecl(hasName("x")))).bind("x");
Manuel Klimek04616e42012-07-06 05:48:52 +0000913
914 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
915 MethodX,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000916 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000917}
918
919TEST(Matcher, BindTheSameNameInAlternatives) {
920 StatementMatcher matcher = anyOf(
921 binaryOperator(hasOperatorName("+"),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000922 hasLHS(expr().bind("x")),
Daniel Jasper1dad1832012-07-10 20:20:19 +0000923 hasRHS(integerLiteral(equals(0)))),
924 binaryOperator(hasOperatorName("+"),
925 hasLHS(integerLiteral(equals(0))),
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000926 hasRHS(expr().bind("x"))));
Daniel Jasper1dad1832012-07-10 20:20:19 +0000927
928 EXPECT_TRUE(matchAndVerifyResultTrue(
929 // The first branch of the matcher binds x to 0 but then fails.
930 // The second branch binds x to f() and succeeds.
931 "int f() { return 0 + f(); }",
932 matcher,
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000933 new VerifyIdIsBoundTo<CallExpr>("x")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000934}
935
Manuel Klimekfdf98762012-08-30 19:41:06 +0000936TEST(Matcher, BindsIDForMemoizedResults) {
937 // Using the same matcher in two match expressions will make memoization
938 // kick in.
939 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
940 EXPECT_TRUE(matchAndVerifyResultTrue(
941 "class A { class B { class X {}; }; };",
942 DeclarationMatcher(anyOf(
943 recordDecl(hasName("A"), hasDescendant(ClassX)),
944 recordDecl(hasName("B"), hasDescendant(ClassX)))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000945 new VerifyIdIsBoundTo<Decl>("x", 2)));
Manuel Klimekfdf98762012-08-30 19:41:06 +0000946}
947
Daniel Jasper856194d02012-12-03 15:43:25 +0000948TEST(HasDeclaration, HasDeclarationOfEnumType) {
949 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
950 expr(hasType(pointsTo(
951 qualType(hasDeclaration(enumDecl(hasName("X")))))))));
952}
953
Edwin Vaneed936452013-02-25 14:32:42 +0000954TEST(HasDeclaration, HasGetDeclTraitTest) {
955 EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
956 EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
957 EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
958}
959
Edwin Vane2c197e02013-02-19 17:14:34 +0000960TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
961 EXPECT_TRUE(matches("typedef int X; X a;",
962 varDecl(hasName("a"),
963 hasType(typedefType(hasDeclaration(decl()))))));
964
965 // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
966}
967
Edwin Vanef901b712013-02-25 14:49:29 +0000968TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
969 EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
970 varDecl(hasType(templateSpecializationType(
971 hasDeclaration(namedDecl(hasName("A"))))))));
972}
973
Manuel Klimek04616e42012-07-06 05:48:52 +0000974TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000975 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000976 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000977 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000978 EXPECT_TRUE(
979 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000980 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000981 EXPECT_TRUE(
982 matches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000983 expr(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000984}
985
986TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000987 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
Manuel Klimek04616e42012-07-06 05:48:52 +0000988 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000989 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000990 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000991 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000992 EXPECT_TRUE(
993 matches("class X {}; void y() { X *x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000994 varDecl(hasType(pointsTo(ClassX)))));
Manuel Klimek04616e42012-07-06 05:48:52 +0000995}
996
997TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +0000998 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +0000999 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001000 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001001 EXPECT_TRUE(
1002 notMatches("class X {}; void y(X *x) { x; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001003 expr(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001004}
1005
1006TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001007 DeclarationMatcher ClassX = recordDecl(hasName("X"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001008 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001009 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001010 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001011 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001012}
1013
Manuel Klimekc16c6522013-06-20 13:08:29 +00001014TEST(HasTypeLoc, MatchesDeclaratorDecls) {
1015 EXPECT_TRUE(matches("int x;",
1016 varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
1017
1018 // Make sure we don't crash on implicit constructors.
1019 EXPECT_TRUE(notMatches("class X {}; X x;",
1020 declaratorDecl(hasTypeLoc(loc(asString("int"))))));
1021}
1022
Manuel Klimek04616e42012-07-06 05:48:52 +00001023TEST(Matcher, Call) {
1024 // FIXME: Do we want to overload Call() to directly take
Daniel Jasper1dad1832012-07-10 20:20:19 +00001025 // Matcher<Decl>, too?
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001026 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001027
1028 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
1029 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
1030
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001031 StatementMatcher MethodOnY =
1032 memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001033
1034 EXPECT_TRUE(
1035 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1036 MethodOnY));
1037 EXPECT_TRUE(
1038 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1039 MethodOnY));
1040 EXPECT_TRUE(
1041 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1042 MethodOnY));
1043 EXPECT_TRUE(
1044 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1045 MethodOnY));
1046 EXPECT_TRUE(
1047 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1048 MethodOnY));
1049
1050 StatementMatcher MethodOnYPointer =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001051 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001052
1053 EXPECT_TRUE(
1054 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1055 MethodOnYPointer));
1056 EXPECT_TRUE(
1057 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1058 MethodOnYPointer));
1059 EXPECT_TRUE(
1060 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1061 MethodOnYPointer));
1062 EXPECT_TRUE(
1063 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1064 MethodOnYPointer));
1065 EXPECT_TRUE(
1066 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1067 MethodOnYPointer));
1068}
1069
Daniel Jasper5901e472012-10-01 13:40:41 +00001070TEST(Matcher, Lambda) {
Richard Smith3d584b02014-02-06 21:49:08 +00001071 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
Daniel Jasper5901e472012-10-01 13:40:41 +00001072 lambdaExpr()));
1073}
1074
1075TEST(Matcher, ForRange) {
Daniel Jasper6f595392012-10-01 15:05:34 +00001076 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
1077 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00001078 forRangeStmt()));
1079 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
1080 forRangeStmt()));
1081}
1082
Alexander Kornienko9e41b5c2014-06-29 22:18:53 +00001083TEST(Matcher, SubstNonTypeTemplateParm) {
1084 EXPECT_FALSE(matches("template<int N>\n"
1085 "struct A { static const int n = 0; };\n"
1086 "struct B : public A<42> {};",
1087 substNonTypeTemplateParmExpr()));
1088 EXPECT_TRUE(matches("template<int N>\n"
1089 "struct A { static const int n = N; };\n"
1090 "struct B : public A<42> {};",
1091 substNonTypeTemplateParmExpr()));
1092}
1093
Daniel Jasper5901e472012-10-01 13:40:41 +00001094TEST(Matcher, UserDefinedLiteral) {
1095 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
1096 " return i + 1;"
1097 "}"
1098 "char c = 'a'_inc;",
1099 userDefinedLiteral()));
1100}
1101
Daniel Jasper87c3d362012-09-20 14:12:57 +00001102TEST(Matcher, FlowControl) {
1103 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
1104 EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
1105 continueStmt()));
1106 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
1107 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
1108 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
1109}
1110
Daniel Jasper1dad1832012-07-10 20:20:19 +00001111TEST(HasType, MatchesAsString) {
1112 EXPECT_TRUE(
1113 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001114 memberCallExpr(on(hasType(asString("class Y *"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001115 EXPECT_TRUE(matches("class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001116 methodDecl(hasParameter(0, hasType(asString("int"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001117 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001118 fieldDecl(hasType(asString("ns::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001119 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
David Blaikieabe1a392014-04-02 05:58:29 +00001120 fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001121}
1122
Manuel Klimek04616e42012-07-06 05:48:52 +00001123TEST(Matcher, OverloadedOperatorCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001124 StatementMatcher OpCall = operatorCallExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001125 // Unary operator
1126 EXPECT_TRUE(matches("class Y { }; "
1127 "bool operator!(Y x) { return false; }; "
1128 "Y y; bool c = !y;", OpCall));
1129 // No match -- special operators like "new", "delete"
1130 // FIXME: operator new takes size_t, for which we need stddef.h, for which
1131 // we need to figure out include paths in the test.
1132 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
1133 // "class Y { }; "
1134 // "void *operator new(size_t size) { return 0; } "
1135 // "Y *y = new Y;", OpCall));
1136 EXPECT_TRUE(notMatches("class Y { }; "
1137 "void operator delete(void *p) { } "
1138 "void a() {Y *y = new Y; delete y;}", OpCall));
1139 // Binary operator
1140 EXPECT_TRUE(matches("class Y { }; "
1141 "bool operator&&(Y x, Y y) { return true; }; "
1142 "Y a; Y b; bool c = a && b;",
1143 OpCall));
1144 // No match -- normal operator, not an overloaded one.
1145 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
1146 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
1147}
1148
1149TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
1150 StatementMatcher OpCallAndAnd =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001151 operatorCallExpr(hasOverloadedOperatorName("&&"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001152 EXPECT_TRUE(matches("class Y { }; "
1153 "bool operator&&(Y x, Y y) { return true; }; "
1154 "Y a; Y b; bool c = a && b;", OpCallAndAnd));
1155 StatementMatcher OpCallLessLess =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001156 operatorCallExpr(hasOverloadedOperatorName("<<"));
Manuel Klimek04616e42012-07-06 05:48:52 +00001157 EXPECT_TRUE(notMatches("class Y { }; "
1158 "bool operator&&(Y x, Y y) { return true; }; "
1159 "Y a; Y b; bool c = a && b;",
1160 OpCallLessLess));
Benjamin Kramer09514492014-07-14 14:05:02 +00001161 StatementMatcher OpStarCall =
1162 operatorCallExpr(hasOverloadedOperatorName("*"));
1163 EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
1164 OpStarCall));
Edwin Vane0a4836e2013-03-06 17:02:57 +00001165 DeclarationMatcher ClassWithOpStar =
1166 recordDecl(hasMethod(hasOverloadedOperatorName("*")));
1167 EXPECT_TRUE(matches("class Y { int operator*(); };",
1168 ClassWithOpStar));
1169 EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
1170 ClassWithOpStar)) ;
Benjamin Kramer09514492014-07-14 14:05:02 +00001171 DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
1172 EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
1173 EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
Manuel Klimek04616e42012-07-06 05:48:52 +00001174}
1175
Daniel Jasper0f9f0192012-11-15 03:29:05 +00001176TEST(Matcher, NestedOverloadedOperatorCalls) {
1177 EXPECT_TRUE(matchAndVerifyResultTrue(
1178 "class Y { }; "
1179 "Y& operator&&(Y& x, Y& y) { return x; }; "
1180 "Y a; Y b; Y c; Y d = a && b && c;",
1181 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
1182 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
1183 EXPECT_TRUE(matches(
1184 "class Y { }; "
1185 "Y& operator&&(Y& x, Y& y) { return x; }; "
1186 "Y a; Y b; Y c; Y d = a && b && c;",
1187 operatorCallExpr(hasParent(operatorCallExpr()))));
1188 EXPECT_TRUE(matches(
1189 "class Y { }; "
1190 "Y& operator&&(Y& x, Y& y) { return x; }; "
1191 "Y a; Y b; Y c; Y d = a && b && c;",
1192 operatorCallExpr(hasDescendant(operatorCallExpr()))));
1193}
1194
Manuel Klimek04616e42012-07-06 05:48:52 +00001195TEST(Matcher, ThisPointerType) {
Manuel Klimek86f8bbc2012-07-24 13:37:29 +00001196 StatementMatcher MethodOnY =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001197 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001198
1199 EXPECT_TRUE(
1200 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
1201 MethodOnY));
1202 EXPECT_TRUE(
1203 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
1204 MethodOnY));
1205 EXPECT_TRUE(
1206 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
1207 MethodOnY));
1208 EXPECT_TRUE(
1209 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
1210 MethodOnY));
1211 EXPECT_TRUE(
1212 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
1213 MethodOnY));
1214
1215 EXPECT_TRUE(matches(
1216 "class Y {"
1217 " public: virtual void x();"
1218 "};"
1219 "class X : public Y {"
1220 " public: virtual void x();"
1221 "};"
1222 "void z() { X *x; x->Y::x(); }", MethodOnY));
1223}
1224
1225TEST(Matcher, VariableUsage) {
1226 StatementMatcher Reference =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001227 declRefExpr(to(
1228 varDecl(hasInitializer(
1229 memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001230
1231 EXPECT_TRUE(matches(
1232 "class Y {"
1233 " public:"
1234 " bool x() const;"
1235 "};"
1236 "void z(const Y &y) {"
1237 " bool b = y.x();"
1238 " if (b) {}"
1239 "}", Reference));
1240
1241 EXPECT_TRUE(notMatches(
1242 "class Y {"
1243 " public:"
1244 " bool x() const;"
1245 "};"
1246 "void z(const Y &y) {"
1247 " bool b = y.x();"
1248 "}", Reference));
1249}
1250
Samuel Benzaquenf56a2992014-06-05 18:22:14 +00001251TEST(Matcher, VarDecl_Storage) {
1252 auto M = varDecl(hasName("X"), hasLocalStorage());
1253 EXPECT_TRUE(matches("void f() { int X; }", M));
1254 EXPECT_TRUE(notMatches("int X;", M));
1255 EXPECT_TRUE(notMatches("void f() { static int X; }", M));
1256
1257 M = varDecl(hasName("X"), hasGlobalStorage());
1258 EXPECT_TRUE(notMatches("void f() { int X; }", M));
1259 EXPECT_TRUE(matches("int X;", M));
1260 EXPECT_TRUE(matches("void f() { static int X; }", M));
1261}
1262
Manuel Klimek61379422012-12-04 14:42:08 +00001263TEST(Matcher, FindsVarDeclInFunctionParameter) {
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001264 EXPECT_TRUE(matches(
1265 "void f(int i) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001266 varDecl(hasName("i"))));
Daniel Jasper3cb72b42012-07-30 05:03:25 +00001267}
1268
Manuel Klimek04616e42012-07-06 05:48:52 +00001269TEST(Matcher, CalledVariable) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001270 StatementMatcher CallOnVariableY =
1271 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001272
1273 EXPECT_TRUE(matches(
1274 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
1275 EXPECT_TRUE(matches(
1276 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
1277 EXPECT_TRUE(matches(
1278 "class Y { public: void x(); };"
1279 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
1280 EXPECT_TRUE(matches(
1281 "class Y { public: void x(); };"
1282 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
1283 EXPECT_TRUE(notMatches(
1284 "class Y { public: void x(); };"
1285 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
1286 CallOnVariableY));
1287}
1288
Daniel Jasper1dad1832012-07-10 20:20:19 +00001289TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
1290 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
1291 unaryExprOrTypeTraitExpr()));
1292 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
1293 alignOfExpr(anything())));
1294 // FIXME: Uncomment once alignof is enabled.
1295 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
1296 // unaryExprOrTypeTraitExpr()));
1297 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
1298 // sizeOfExpr()));
1299}
1300
1301TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
1302 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
1303 hasArgumentOfType(asString("int")))));
1304 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
1305 hasArgumentOfType(asString("float")))));
1306 EXPECT_TRUE(matches(
1307 "struct A {}; void x() { A a; int b = sizeof(a); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001308 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001309 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001310 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001311}
1312
Manuel Klimek04616e42012-07-06 05:48:52 +00001313TEST(MemberExpression, DoesNotMatchClasses) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001314 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001315}
1316
1317TEST(MemberExpression, MatchesMemberFunctionCall) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001318 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001319}
1320
1321TEST(MemberExpression, MatchesVariable) {
1322 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001323 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001324 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001325 matches("class Y { void x() { y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001326 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001327 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001328}
1329
1330TEST(MemberExpression, MatchesStaticVariable) {
1331 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001332 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001333 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001334 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001335 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001336 memberExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00001337}
1338
Daniel Jasper4e566c42012-07-12 08:50:38 +00001339TEST(IsInteger, MatchesIntegers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001340 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
1341 EXPECT_TRUE(matches(
1342 "long long i = 0; void f(long long) { }; void g() {f(i);}",
1343 callExpr(hasArgument(0, declRefExpr(
1344 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001345}
1346
1347TEST(IsInteger, ReportsNoFalsePositives) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001348 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001349 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001350 callExpr(hasArgument(0, declRefExpr(
1351 to(varDecl(hasType(isInteger()))))))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00001352}
1353
Manuel Klimek04616e42012-07-06 05:48:52 +00001354TEST(IsArrow, MatchesMemberVariablesViaArrow) {
1355 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001356 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001357 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001358 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001359 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001360 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001361}
1362
1363TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
1364 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001365 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001366 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001367 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001368 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001369 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001370}
1371
1372TEST(IsArrow, MatchesMemberCallsViaArrow) {
1373 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001374 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001375 EXPECT_TRUE(matches("class Y { void x() { x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001376 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001377 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001378 memberExpr(isArrow())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001379}
1380
1381TEST(Callee, MatchesDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001382 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001383
1384 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
1385 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
1386}
1387
1388TEST(Callee, MatchesMemberExpressions) {
1389 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001390 callExpr(callee(memberExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001391 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001392 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001393}
1394
1395TEST(Function, MatchesFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001396 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001397
1398 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
1399 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
1400
NAKAMURA Takumi7d2da0b2014-02-16 10:16:09 +00001401 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1402 llvm::Triple::Win32) {
1403 // FIXME: Make this work for MSVC.
1404 // Dependent contexts, but a non-dependent call.
1405 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
1406 CallFunctionF));
1407 EXPECT_TRUE(
1408 matches("void f(); template <int N> struct S { void g() { f(); } };",
1409 CallFunctionF));
1410 }
Manuel Klimek04616e42012-07-06 05:48:52 +00001411
1412 // Depedent calls don't match.
1413 EXPECT_TRUE(
1414 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
1415 CallFunctionF));
1416 EXPECT_TRUE(
1417 notMatches("void f(int);"
1418 "template <typename T> struct S { void g(T t) { f(t); } };",
1419 CallFunctionF));
1420}
1421
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001422TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
1423 EXPECT_TRUE(
1424 matches("template <typename T> void f(T t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001425 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001426}
1427
1428TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
1429 EXPECT_TRUE(
1430 notMatches("void f(double d); void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001431 functionTemplateDecl(hasName("f"))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001432}
1433
1434TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
1435 EXPECT_TRUE(
1436 notMatches("void g(); template <typename T> void f(T t) {}"
1437 "template <> void f(int t) { g(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001438 functionTemplateDecl(hasName("f"),
1439 hasDescendant(declRefExpr(to(
1440 functionDecl(hasName("g"))))))));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00001441}
1442
Manuel Klimek04616e42012-07-06 05:48:52 +00001443TEST(Matcher, Argument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001444 StatementMatcher CallArgumentY = callExpr(
1445 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001446
1447 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
1448 EXPECT_TRUE(
1449 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
1450 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
1451
Daniel Jasper848cbe12012-09-18 13:09:13 +00001452 StatementMatcher WrongIndex = callExpr(
1453 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001454 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
1455}
1456
1457TEST(Matcher, AnyArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001458 StatementMatcher CallArgumentY = callExpr(
1459 hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001460 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
1461 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
1462 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
1463}
1464
1465TEST(Matcher, ArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001466 StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001467
1468 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
1469 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
1470 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
1471}
1472
Daniel Jasper9f501292012-12-04 11:54:27 +00001473TEST(Matcher, ParameterCount) {
1474 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
1475 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
1476 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
1477 EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
1478 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
1479}
1480
Manuel Klimek04616e42012-07-06 05:48:52 +00001481TEST(Matcher, References) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001482 DeclarationMatcher ReferenceClassX = varDecl(
1483 hasType(references(recordDecl(hasName("X")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001484 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
1485 ReferenceClassX));
1486 EXPECT_TRUE(
1487 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
Michael Hanc90d12d2013-09-11 15:53:29 +00001488 // The match here is on the implicit copy constructor code for
1489 // class X, not on code 'X x = y'.
Manuel Klimek04616e42012-07-06 05:48:52 +00001490 EXPECT_TRUE(
Michael Hanc90d12d2013-09-11 15:53:29 +00001491 matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
1492 EXPECT_TRUE(
1493 notMatches("class X {}; extern X x;", ReferenceClassX));
Manuel Klimek04616e42012-07-06 05:48:52 +00001494 EXPECT_TRUE(
1495 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
1496}
1497
Edwin Vane0a4836e2013-03-06 17:02:57 +00001498TEST(QualType, hasCanonicalType) {
1499 EXPECT_TRUE(notMatches("typedef int &int_ref;"
1500 "int a;"
1501 "int_ref b = a;",
1502 varDecl(hasType(qualType(referenceType())))));
1503 EXPECT_TRUE(
1504 matches("typedef int &int_ref;"
1505 "int a;"
1506 "int_ref b = a;",
1507 varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
1508}
1509
Edwin Vane119d3df2013-04-02 18:15:55 +00001510TEST(QualType, hasLocalQualifiers) {
1511 EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1512 varDecl(hasType(hasLocalQualifiers()))));
1513 EXPECT_TRUE(matches("int *const j = nullptr;",
1514 varDecl(hasType(hasLocalQualifiers()))));
1515 EXPECT_TRUE(matches("int *volatile k;",
1516 varDecl(hasType(hasLocalQualifiers()))));
1517 EXPECT_TRUE(notMatches("int m;",
1518 varDecl(hasType(hasLocalQualifiers()))));
1519}
1520
Manuel Klimek04616e42012-07-06 05:48:52 +00001521TEST(HasParameter, CallsInnerMatcher) {
1522 EXPECT_TRUE(matches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001523 methodDecl(hasParameter(0, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001524 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001525 methodDecl(hasParameter(0, hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001526}
1527
1528TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
1529 EXPECT_TRUE(notMatches("class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001530 methodDecl(hasParameter(42, varDecl()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001531}
1532
1533TEST(HasType, MatchesParameterVariableTypesStrictly) {
1534 EXPECT_TRUE(matches("class X { void x(X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001535 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001536 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001537 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001538 EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001539 methodDecl(hasParameter(0,
1540 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001541 EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001542 methodDecl(hasParameter(0,
1543 hasType(references(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001544}
1545
1546TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
1547 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001548 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001549 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001550 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001551}
1552
Daniel Jasper1dad1832012-07-10 20:20:19 +00001553TEST(Returns, MatchesReturnTypes) {
1554 EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001555 functionDecl(returns(asString("int")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001556 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001557 functionDecl(returns(asString("float")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001558 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001559 functionDecl(returns(hasDeclaration(
1560 recordDecl(hasName("Y")))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001561}
1562
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001563TEST(IsExternC, MatchesExternCFunctionDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001564 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1565 EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1566 functionDecl(isExternC())));
1567 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
Daniel Jasperfaaffe32012-08-15 18:52:19 +00001568}
1569
Samuel Benzaquen8e7f9962014-08-15 14:20:59 +00001570TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1571 EXPECT_TRUE(
1572 notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1573 EXPECT_TRUE(matches("void Func() = delete;",
1574 functionDecl(hasName("Func"), isDeleted())));
1575}
1576
Manuel Klimek04616e42012-07-06 05:48:52 +00001577TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
1578 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001579 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001580}
1581
1582TEST(HasAnyParameter, DoesNotMatchThisPointer) {
1583 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001584 methodDecl(hasAnyParameter(hasType(pointsTo(
1585 recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001586}
1587
Alp Toker8db6e7a2014-01-05 06:38:57 +00001588TEST(HasName, MatchesParameterVariableDeclarations) {
Manuel Klimek04616e42012-07-06 05:48:52 +00001589 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001590 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001591 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001592 methodDecl(hasAnyParameter(hasName("x")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001593}
1594
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001595TEST(Matcher, MatchesClassTemplateSpecialization) {
1596 EXPECT_TRUE(matches("template<typename T> struct A {};"
1597 "template<> struct A<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001598 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001599 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001600 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001601 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001602 classTemplateSpecializationDecl()));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001603}
1604
Manuel Klimekc16c6522013-06-20 13:08:29 +00001605TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
1606 EXPECT_TRUE(matches("int x;", declaratorDecl()));
1607 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
1608}
1609
1610TEST(ParmVarDecl, MatchesParmVars) {
1611 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
1612 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
1613}
1614
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001615TEST(Matcher, MatchesTypeTemplateArgument) {
1616 EXPECT_TRUE(matches(
1617 "template<typename T> struct B {};"
1618 "B<int> b;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001619 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001620 asString("int"))))));
1621}
1622
1623TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
1624 EXPECT_TRUE(matches(
1625 "struct B { int next; };"
1626 "template<int(B::*next_ptr)> struct A {};"
1627 "A<&B::next> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001628 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1629 refersToDeclaration(fieldDecl(hasName("next")))))));
Daniel Jasper0c303372012-09-29 15:55:18 +00001630
1631 EXPECT_TRUE(notMatches(
1632 "template <typename T> struct A {};"
1633 "A<int> a;",
1634 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1635 refersToDeclaration(decl())))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001636
1637 EXPECT_TRUE(matches(
1638 "struct B { int next; };"
1639 "template<int(B::*next_ptr)> struct A {};"
1640 "A<&B::next> a;",
1641 templateSpecializationType(hasAnyTemplateArgument(isExpr(
1642 hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
1643
1644 EXPECT_TRUE(notMatches(
1645 "template <typename T> struct A {};"
1646 "A<int> a;",
1647 templateSpecializationType(hasAnyTemplateArgument(
1648 refersToDeclaration(decl())))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001649}
1650
1651TEST(Matcher, MatchesSpecificArgument) {
1652 EXPECT_TRUE(matches(
1653 "template<typename T, typename U> class A {};"
1654 "A<bool, int> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001655 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001656 1, refersToType(asString("int"))))));
1657 EXPECT_TRUE(notMatches(
1658 "template<typename T, typename U> class A {};"
1659 "A<int, bool> a;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001660 classTemplateSpecializationDecl(hasTemplateArgument(
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001661 1, refersToType(asString("int"))))));
Peter Collingbourne564597f2014-02-20 19:18:03 +00001662
1663 EXPECT_TRUE(matches(
1664 "template<typename T, typename U> class A {};"
1665 "A<bool, int> a;",
1666 templateSpecializationType(hasTemplateArgument(
1667 1, refersToType(asString("int"))))));
1668 EXPECT_TRUE(notMatches(
1669 "template<typename T, typename U> class A {};"
1670 "A<int, bool> a;",
1671 templateSpecializationType(hasTemplateArgument(
1672 1, refersToType(asString("int"))))));
Daniel Jasper8bd14aa2012-08-01 08:40:24 +00001673}
1674
Manuel Klimek7735e402014-10-09 13:06:22 +00001675TEST(TemplateArgument, Matches) {
1676 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1677 classTemplateSpecializationDecl(
1678 hasAnyTemplateArgument(templateArgument()))));
1679 EXPECT_TRUE(matches(
1680 "template<typename T> struct C {}; C<int> c;",
1681 templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
1682}
1683
1684TEST(TemplateArgumentCountIs, Matches) {
1685 EXPECT_TRUE(
1686 matches("template<typename T> struct C {}; C<int> c;",
1687 classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1688 EXPECT_TRUE(
1689 notMatches("template<typename T> struct C {}; C<int> c;",
1690 classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1691
1692 EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1693 templateSpecializationType(templateArgumentCountIs(1))));
1694 EXPECT_TRUE(
1695 notMatches("template<typename T> struct C {}; C<int> c;",
1696 templateSpecializationType(templateArgumentCountIs(2))));
1697}
1698
1699TEST(IsIntegral, Matches) {
1700 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1701 classTemplateSpecializationDecl(
1702 hasAnyTemplateArgument(isIntegral()))));
1703 EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1704 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1705 templateArgument(isIntegral())))));
1706}
1707
1708TEST(RefersToIntegralType, Matches) {
1709 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1710 classTemplateSpecializationDecl(
1711 hasAnyTemplateArgument(refersToIntegralType(
1712 asString("int"))))));
1713 EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
1714 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1715 refersToIntegralType(asString("int"))))));
1716}
1717
1718TEST(EqualsIntegralValue, Matches) {
1719 EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1720 classTemplateSpecializationDecl(
1721 hasAnyTemplateArgument(equalsIntegralValue("42")))));
1722 EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1723 classTemplateSpecializationDecl(
1724 hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1725 EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1726 classTemplateSpecializationDecl(
1727 hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1728 EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1729 classTemplateSpecializationDecl(hasAnyTemplateArgument(
1730 equalsIntegralValue("0042")))));
1731}
1732
Daniel Jasper639522c2013-02-25 12:02:08 +00001733TEST(Matcher, MatchesAccessSpecDecls) {
1734 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1735 EXPECT_TRUE(
1736 matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1737 EXPECT_TRUE(
1738 notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1739 EXPECT_TRUE(
1740 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1741
1742 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1743}
1744
Edwin Vane37ee1d72013-04-09 20:46:36 +00001745TEST(Matcher, MatchesVirtualMethod) {
1746 EXPECT_TRUE(matches("class X { virtual int f(); };",
1747 methodDecl(isVirtual(), hasName("::X::f"))));
1748 EXPECT_TRUE(notMatches("class X { int f(); };",
1749 methodDecl(isVirtual())));
1750}
1751
Dmitri Gribenko51c1b552014-02-24 09:27:46 +00001752TEST(Matcher, MatchesPureMethod) {
1753 EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1754 methodDecl(isPure(), hasName("::X::f"))));
1755 EXPECT_TRUE(notMatches("class X { int f(); };",
1756 methodDecl(isPure())));
1757}
1758
Edwin Vanefc4f7dc2013-05-09 17:00:17 +00001759TEST(Matcher, MatchesConstMethod) {
1760 EXPECT_TRUE(matches("struct A { void foo() const; };",
1761 methodDecl(isConst())));
1762 EXPECT_TRUE(notMatches("struct A { void foo(); };",
1763 methodDecl(isConst())));
1764}
1765
Edwin Vane37ee1d72013-04-09 20:46:36 +00001766TEST(Matcher, MatchesOverridingMethod) {
1767 EXPECT_TRUE(matches("class X { virtual int f(); }; "
1768 "class Y : public X { int f(); };",
1769 methodDecl(isOverride(), hasName("::Y::f"))));
1770 EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1771 "class Y : public X { int f(); };",
1772 methodDecl(isOverride(), hasName("::X::f"))));
1773 EXPECT_TRUE(notMatches("class X { int f(); }; "
1774 "class Y : public X { int f(); };",
1775 methodDecl(isOverride())));
1776 EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1777 methodDecl(isOverride())));
1778}
1779
Manuel Klimek04616e42012-07-06 05:48:52 +00001780TEST(Matcher, ConstructorCall) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001781 StatementMatcher Constructor = constructExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001782
1783 EXPECT_TRUE(
1784 matches("class X { public: X(); }; void x() { X x; }", Constructor));
1785 EXPECT_TRUE(
1786 matches("class X { public: X(); }; void x() { X x = X(); }",
1787 Constructor));
1788 EXPECT_TRUE(
1789 matches("class X { public: X(int); }; void x() { X x = 0; }",
1790 Constructor));
1791 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
1792}
1793
1794TEST(Matcher, ConstructorArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001795 StatementMatcher Constructor = constructExpr(
1796 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001797
1798 EXPECT_TRUE(
1799 matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1800 Constructor));
1801 EXPECT_TRUE(
1802 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1803 Constructor));
1804 EXPECT_TRUE(
1805 matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1806 Constructor));
1807 EXPECT_TRUE(
1808 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1809 Constructor));
1810
Daniel Jasper848cbe12012-09-18 13:09:13 +00001811 StatementMatcher WrongIndex = constructExpr(
1812 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001813 EXPECT_TRUE(
1814 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1815 WrongIndex));
1816}
1817
1818TEST(Matcher, ConstructorArgumentCount) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001819 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00001820
1821 EXPECT_TRUE(
1822 matches("class X { public: X(int); }; void x() { X x(0); }",
1823 Constructor1Arg));
1824 EXPECT_TRUE(
1825 matches("class X { public: X(int); }; void x() { X x = X(0); }",
1826 Constructor1Arg));
1827 EXPECT_TRUE(
1828 matches("class X { public: X(int); }; void x() { X x = 0; }",
1829 Constructor1Arg));
1830 EXPECT_TRUE(
1831 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1832 Constructor1Arg));
1833}
1834
Peter Collingbourne1fec3df2014-02-06 21:52:24 +00001835TEST(Matcher, ConstructorListInitialization) {
1836 StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
1837
1838 EXPECT_TRUE(
1839 matches("class X { public: X(int); }; void x() { X x{0}; }",
1840 ConstructorListInit));
1841 EXPECT_FALSE(
1842 matches("class X { public: X(int); }; void x() { X x(0); }",
1843 ConstructorListInit));
1844}
1845
Manuel Klimek7fca93b2012-10-23 10:40:50 +00001846TEST(Matcher,ThisExpr) {
1847 EXPECT_TRUE(
1848 matches("struct X { int a; int f () { return a; } };", thisExpr()));
1849 EXPECT_TRUE(
1850 notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
1851}
1852
Manuel Klimek04616e42012-07-06 05:48:52 +00001853TEST(Matcher, BindTemporaryExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00001854 StatementMatcher TempExpression = bindTemporaryExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00001855
1856 std::string ClassString = "class string { public: string(); ~string(); }; ";
1857
1858 EXPECT_TRUE(
1859 matches(ClassString +
1860 "string GetStringByValue();"
1861 "void FunctionTakesString(string s);"
1862 "void run() { FunctionTakesString(GetStringByValue()); }",
1863 TempExpression));
1864
1865 EXPECT_TRUE(
1866 notMatches(ClassString +
1867 "string* GetStringPointer(); "
1868 "void FunctionTakesStringPtr(string* s);"
1869 "void run() {"
1870 " string* s = GetStringPointer();"
1871 " FunctionTakesStringPtr(GetStringPointer());"
1872 " FunctionTakesStringPtr(s);"
1873 "}",
1874 TempExpression));
1875
1876 EXPECT_TRUE(
1877 notMatches("class no_dtor {};"
1878 "no_dtor GetObjByValue();"
1879 "void ConsumeObj(no_dtor param);"
1880 "void run() { ConsumeObj(GetObjByValue()); }",
1881 TempExpression));
1882}
1883
Sam Panzer68a35af2012-08-24 22:04:44 +00001884TEST(MaterializeTemporaryExpr, MatchesTemporary) {
1885 std::string ClassString =
1886 "class string { public: string(); int length(); }; ";
1887
1888 EXPECT_TRUE(
1889 matches(ClassString +
1890 "string GetStringByValue();"
1891 "void FunctionTakesString(string s);"
1892 "void run() { FunctionTakesString(GetStringByValue()); }",
1893 materializeTemporaryExpr()));
1894
1895 EXPECT_TRUE(
1896 notMatches(ClassString +
1897 "string* GetStringPointer(); "
1898 "void FunctionTakesStringPtr(string* s);"
1899 "void run() {"
1900 " string* s = GetStringPointer();"
1901 " FunctionTakesStringPtr(GetStringPointer());"
1902 " FunctionTakesStringPtr(s);"
1903 "}",
1904 materializeTemporaryExpr()));
1905
1906 EXPECT_TRUE(
1907 notMatches(ClassString +
1908 "string GetStringByValue();"
1909 "void run() { int k = GetStringByValue().length(); }",
1910 materializeTemporaryExpr()));
1911
1912 EXPECT_TRUE(
1913 notMatches(ClassString +
1914 "string GetStringByValue();"
1915 "void run() { GetStringByValue(); }",
1916 materializeTemporaryExpr()));
1917}
1918
Manuel Klimek04616e42012-07-06 05:48:52 +00001919TEST(ConstructorDeclaration, SimpleCase) {
1920 EXPECT_TRUE(matches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001921 constructorDecl(ofClass(hasName("Foo")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001922 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001923 constructorDecl(ofClass(hasName("Bar")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001924}
1925
1926TEST(ConstructorDeclaration, IsImplicit) {
1927 // This one doesn't match because the constructor is not added by the
1928 // compiler (it is not needed).
1929 EXPECT_TRUE(notMatches("class Foo { };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001930 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001931 // The compiler added the implicit default constructor.
1932 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001933 constructorDecl(isImplicit())));
Manuel Klimek04616e42012-07-06 05:48:52 +00001934 EXPECT_TRUE(matches("class Foo { Foo(){} };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001935 constructorDecl(unless(isImplicit()))));
Joey Gouly0d9a2b22014-05-16 19:31:08 +00001936 // The compiler added an implicit assignment operator.
1937 EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1938 methodDecl(isImplicit(), hasName("operator="))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001939}
1940
Daniel Jasper1dad1832012-07-10 20:20:19 +00001941TEST(DestructorDeclaration, MatchesVirtualDestructor) {
1942 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001943 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001944}
1945
1946TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001947 EXPECT_TRUE(notMatches("class Foo {};",
1948 destructorDecl(ofClass(hasName("Foo")))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00001949}
1950
Manuel Klimek04616e42012-07-06 05:48:52 +00001951TEST(HasAnyConstructorInitializer, SimpleCase) {
1952 EXPECT_TRUE(notMatches(
1953 "class Foo { Foo() { } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001954 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001955 EXPECT_TRUE(matches(
1956 "class Foo {"
1957 " Foo() : foo_() { }"
1958 " int foo_;"
1959 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001960 constructorDecl(hasAnyConstructorInitializer(anything()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001961}
1962
1963TEST(HasAnyConstructorInitializer, ForField) {
1964 static const char Code[] =
1965 "class Baz { };"
1966 "class Foo {"
1967 " Foo() : foo_() { }"
1968 " Baz foo_;"
1969 " Baz bar_;"
1970 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001971 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
1972 forField(hasType(recordDecl(hasName("Baz"))))))));
1973 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001974 forField(hasName("foo_"))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001975 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
1976 forField(hasType(recordDecl(hasName("Bar"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00001977}
1978
1979TEST(HasAnyConstructorInitializer, WithInitializer) {
1980 static const char Code[] =
1981 "class Foo {"
1982 " Foo() : foo_(0) { }"
1983 " int foo_;"
1984 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001985 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001986 withInitializer(integerLiteral(equals(0)))))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001987 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00001988 withInitializer(integerLiteral(equals(1)))))));
1989}
1990
1991TEST(HasAnyConstructorInitializer, IsWritten) {
1992 static const char Code[] =
1993 "struct Bar { Bar(){} };"
1994 "class Foo {"
1995 " Foo() : foo_() { }"
1996 " Bar foo_;"
1997 " Bar bar_;"
1998 "};";
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00001999 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002000 allOf(forField(hasName("foo_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002001 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002002 allOf(forField(hasName("bar_")), isWritten())))));
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002003 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
Manuel Klimek04616e42012-07-06 05:48:52 +00002004 allOf(forField(hasName("bar_")), unless(isWritten()))))));
2005}
2006
2007TEST(Matcher, NewExpression) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002008 StatementMatcher New = newExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002009
2010 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
2011 EXPECT_TRUE(
2012 matches("class X { public: X(); }; void x() { new X(); }", New));
2013 EXPECT_TRUE(
2014 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2015 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
2016}
2017
2018TEST(Matcher, NewExpressionArgument) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002019 StatementMatcher New = constructExpr(
2020 hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002021
2022 EXPECT_TRUE(
2023 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2024 New));
2025 EXPECT_TRUE(
2026 matches("class X { public: X(int); }; void x() { int y; new X(y); }",
2027 New));
2028 EXPECT_TRUE(
2029 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
2030 New));
2031
Daniel Jasper848cbe12012-09-18 13:09:13 +00002032 StatementMatcher WrongIndex = constructExpr(
2033 hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002034 EXPECT_TRUE(
2035 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
2036 WrongIndex));
2037}
2038
2039TEST(Matcher, NewExpressionArgumentCount) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002040 StatementMatcher New = constructExpr(argumentCountIs(1));
Manuel Klimek04616e42012-07-06 05:48:52 +00002041
2042 EXPECT_TRUE(
2043 matches("class X { public: X(int); }; void x() { new X(0); }", New));
2044 EXPECT_TRUE(
2045 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
2046 New));
2047}
2048
Daniel Jasper1dad1832012-07-10 20:20:19 +00002049TEST(Matcher, DeleteExpression) {
2050 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002051 deleteExpr()));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002052}
2053
Manuel Klimek04616e42012-07-06 05:48:52 +00002054TEST(Matcher, DefaultArgument) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002055 StatementMatcher Arg = defaultArgExpr();
Manuel Klimek04616e42012-07-06 05:48:52 +00002056
2057 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
2058 EXPECT_TRUE(
2059 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
2060 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
2061}
2062
2063TEST(Matcher, StringLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002064 StatementMatcher Literal = stringLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002065 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
2066 // wide string
2067 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
2068 // with escaped characters
2069 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
2070 // no matching -- though the data type is the same, there is no string literal
2071 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
2072}
2073
2074TEST(Matcher, CharacterLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002075 StatementMatcher CharLiteral = characterLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002076 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
2077 // wide character
2078 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
2079 // wide character, Hex encoded, NOT MATCHED!
2080 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
2081 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
2082}
2083
2084TEST(Matcher, IntegerLiterals) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002085 StatementMatcher HasIntLiteral = integerLiteral();
Manuel Klimek04616e42012-07-06 05:48:52 +00002086 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
2087 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
2088 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
2089 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
2090
2091 // Non-matching cases (character literals, float and double)
2092 EXPECT_TRUE(notMatches("int i = L'a';",
2093 HasIntLiteral)); // this is actually a character
2094 // literal cast to int
2095 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
2096 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
2097 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
2098}
2099
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002100TEST(Matcher, FloatLiterals) {
2101 StatementMatcher HasFloatLiteral = floatLiteral();
2102 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
2103 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
2104 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
2105 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
2106 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002107 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
2108 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
2109 EXPECT_TRUE(
2110 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002111
2112 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
Daniel Jasperd1423812015-02-03 09:45:52 +00002113 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
2114 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
2115 EXPECT_TRUE(
2116 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
Daniel Jasper91f1c8c2013-07-26 18:52:58 +00002117}
2118
Daniel Jasper5901e472012-10-01 13:40:41 +00002119TEST(Matcher, NullPtrLiteral) {
2120 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
2121}
2122
Daniel Jasper87c3d362012-09-20 14:12:57 +00002123TEST(Matcher, AsmStatement) {
2124 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
2125}
2126
Manuel Klimek04616e42012-07-06 05:48:52 +00002127TEST(Matcher, Conditions) {
2128 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
2129
2130 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
2131 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
2132 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
2133 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
2134 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
2135}
2136
Manuel Klimek909b5c942014-05-27 10:04:12 +00002137TEST(IfStmt, ChildTraversalMatchers) {
2138 EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
2139 ifStmt(hasThen(boolLiteral(equals(true))))));
2140 EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
2141 ifStmt(hasThen(boolLiteral(equals(true))))));
2142 EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
2143 ifStmt(hasElse(boolLiteral(equals(true))))));
2144 EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
2145 ifStmt(hasElse(boolLiteral(equals(true))))));
2146}
2147
Manuel Klimek04616e42012-07-06 05:48:52 +00002148TEST(MatchBinaryOperator, HasOperatorName) {
2149 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
2150
2151 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
2152 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
2153}
2154
2155TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
2156 StatementMatcher OperatorTrueFalse =
2157 binaryOperator(hasLHS(boolLiteral(equals(true))),
2158 hasRHS(boolLiteral(equals(false))));
2159
2160 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
2161 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
2162 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
2163}
2164
2165TEST(MatchBinaryOperator, HasEitherOperand) {
2166 StatementMatcher HasOperand =
2167 binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
2168
2169 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
2170 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
2171 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
2172}
2173
2174TEST(Matcher, BinaryOperatorTypes) {
2175 // Integration test that verifies the AST provides all binary operators in
2176 // a way we expect.
2177 // FIXME: Operator ','
2178 EXPECT_TRUE(
2179 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
2180 EXPECT_TRUE(
2181 matches("bool b; bool c = (b = true);",
2182 binaryOperator(hasOperatorName("="))));
2183 EXPECT_TRUE(
2184 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
2185 EXPECT_TRUE(
2186 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
2187 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
2188 EXPECT_TRUE(
2189 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
2190 EXPECT_TRUE(
2191 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
2192 EXPECT_TRUE(
2193 matches("int i = 1; int j = (i <<= 2);",
2194 binaryOperator(hasOperatorName("<<="))));
2195 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
2196 EXPECT_TRUE(
2197 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
2198 EXPECT_TRUE(
2199 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
2200 EXPECT_TRUE(
2201 matches("int i = 1; int j = (i >>= 2);",
2202 binaryOperator(hasOperatorName(">>="))));
2203 EXPECT_TRUE(
2204 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
2205 EXPECT_TRUE(
2206 matches("int i = 42; int j = (i ^= 42);",
2207 binaryOperator(hasOperatorName("^="))));
2208 EXPECT_TRUE(
2209 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
2210 EXPECT_TRUE(
2211 matches("int i = 42; int j = (i %= 42);",
2212 binaryOperator(hasOperatorName("%="))));
2213 EXPECT_TRUE(
2214 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
2215 EXPECT_TRUE(
2216 matches("bool b = true && false;",
2217 binaryOperator(hasOperatorName("&&"))));
2218 EXPECT_TRUE(
2219 matches("bool b = true; bool c = (b &= false);",
2220 binaryOperator(hasOperatorName("&="))));
2221 EXPECT_TRUE(
2222 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
2223 EXPECT_TRUE(
2224 matches("bool b = true || false;",
2225 binaryOperator(hasOperatorName("||"))));
2226 EXPECT_TRUE(
2227 matches("bool b = true; bool c = (b |= false);",
2228 binaryOperator(hasOperatorName("|="))));
2229 EXPECT_TRUE(
2230 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
2231 EXPECT_TRUE(
2232 matches("int i = 42; int j = (i *= 23);",
2233 binaryOperator(hasOperatorName("*="))));
2234 EXPECT_TRUE(
2235 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
2236 EXPECT_TRUE(
2237 matches("int i = 42; int j = (i /= 23);",
2238 binaryOperator(hasOperatorName("/="))));
2239 EXPECT_TRUE(
2240 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
2241 EXPECT_TRUE(
2242 matches("int i = 42; int j = (i += 23);",
2243 binaryOperator(hasOperatorName("+="))));
2244 EXPECT_TRUE(
2245 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
2246 EXPECT_TRUE(
2247 matches("int i = 42; int j = (i -= 23);",
2248 binaryOperator(hasOperatorName("-="))));
2249 EXPECT_TRUE(
2250 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
2251 binaryOperator(hasOperatorName("->*"))));
2252 EXPECT_TRUE(
2253 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
2254 binaryOperator(hasOperatorName(".*"))));
2255
2256 // Member expressions as operators are not supported in matches.
2257 EXPECT_TRUE(
2258 notMatches("struct A { void x(A *a) { a->x(this); } };",
2259 binaryOperator(hasOperatorName("->"))));
2260
2261 // Initializer assignments are not represented as operator equals.
2262 EXPECT_TRUE(
2263 notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
2264
2265 // Array indexing is not represented as operator.
2266 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
2267
2268 // Overloaded operators do not match at all.
2269 EXPECT_TRUE(notMatches(
2270 "struct A { bool operator&&(const A &a) const { return false; } };"
2271 "void x() { A a, b; a && b; }",
2272 binaryOperator()));
2273}
2274
2275TEST(MatchUnaryOperator, HasOperatorName) {
2276 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
2277
2278 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
2279 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
2280}
2281
2282TEST(MatchUnaryOperator, HasUnaryOperand) {
2283 StatementMatcher OperatorOnFalse =
2284 unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
2285
2286 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
2287 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
2288}
2289
2290TEST(Matcher, UnaryOperatorTypes) {
2291 // Integration test that verifies the AST provides all unary operators in
2292 // a way we expect.
2293 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
2294 EXPECT_TRUE(
2295 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
2296 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
2297 EXPECT_TRUE(
2298 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
2299 EXPECT_TRUE(
2300 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
2301 EXPECT_TRUE(
2302 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
2303 EXPECT_TRUE(
2304 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
2305 EXPECT_TRUE(
2306 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
2307 EXPECT_TRUE(
2308 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
2309 EXPECT_TRUE(
2310 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
2311
2312 // We don't match conversion operators.
2313 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
2314
2315 // Function calls are not represented as operator.
2316 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
2317
2318 // Overloaded operators do not match at all.
2319 // FIXME: We probably want to add that.
2320 EXPECT_TRUE(notMatches(
2321 "struct A { bool operator!() const { return false; } };"
2322 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
2323}
2324
2325TEST(Matcher, ConditionalOperator) {
2326 StatementMatcher Conditional = conditionalOperator(
2327 hasCondition(boolLiteral(equals(true))),
2328 hasTrueExpression(boolLiteral(equals(false))));
2329
2330 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
2331 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
2332 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
2333
2334 StatementMatcher ConditionalFalse = conditionalOperator(
2335 hasFalseExpression(boolLiteral(equals(false))));
2336
2337 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
2338 EXPECT_TRUE(
2339 notMatches("void x() { true ? false : true; }", ConditionalFalse));
2340}
2341
Daniel Jasper1dad1832012-07-10 20:20:19 +00002342TEST(ArraySubscriptMatchers, ArraySubscripts) {
2343 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
2344 arraySubscriptExpr()));
2345 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
2346 arraySubscriptExpr()));
2347}
2348
2349TEST(ArraySubscriptMatchers, ArrayIndex) {
2350 EXPECT_TRUE(matches(
2351 "int i[2]; void f() { i[1] = 1; }",
2352 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2353 EXPECT_TRUE(matches(
2354 "int i[2]; void f() { 1[i] = 1; }",
2355 arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
2356 EXPECT_TRUE(notMatches(
2357 "int i[2]; void f() { i[1] = 1; }",
2358 arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
2359}
2360
2361TEST(ArraySubscriptMatchers, MatchesArrayBase) {
2362 EXPECT_TRUE(matches(
2363 "int i[2]; void f() { i[1] = 2; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002364 arraySubscriptExpr(hasBase(implicitCastExpr(
2365 hasSourceExpression(declRefExpr()))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00002366}
2367
Manuel Klimek04616e42012-07-06 05:48:52 +00002368TEST(Matcher, HasNameSupportsNamespaces) {
2369 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002370 recordDecl(hasName("a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002371 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002372 recordDecl(hasName("::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002373 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002374 recordDecl(hasName("b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002375 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002376 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002377 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002378 recordDecl(hasName("c::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002379 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002380 recordDecl(hasName("a::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002381 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002382 recordDecl(hasName("a::b::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002383 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002384 recordDecl(hasName("::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002385 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002386 recordDecl(hasName("::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002387 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002388 recordDecl(hasName("z::a::b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002389 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002390 recordDecl(hasName("a+b::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002391 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002392 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002393}
2394
2395TEST(Matcher, HasNameSupportsOuterClasses) {
2396 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002397 matches("class A { class B { class C; }; };",
2398 recordDecl(hasName("A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002399 EXPECT_TRUE(
2400 matches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002401 recordDecl(hasName("::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002402 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002403 matches("class A { class B { class C; }; };",
2404 recordDecl(hasName("B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002405 EXPECT_TRUE(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002406 matches("class A { class B { class C; }; };",
2407 recordDecl(hasName("C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002408 EXPECT_TRUE(
2409 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002410 recordDecl(hasName("c::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002411 EXPECT_TRUE(
2412 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002413 recordDecl(hasName("A::c::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002414 EXPECT_TRUE(
2415 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002416 recordDecl(hasName("A::B::A"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002417 EXPECT_TRUE(
2418 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002419 recordDecl(hasName("::C"))));
2420 EXPECT_TRUE(
2421 notMatches("class A { class B { class C; }; };",
2422 recordDecl(hasName("::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002423 EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002424 recordDecl(hasName("z::A::B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002425 EXPECT_TRUE(
2426 notMatches("class A { class B { class C; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002427 recordDecl(hasName("A+B::C"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002428}
2429
2430TEST(Matcher, IsDefinition) {
2431 DeclarationMatcher DefinitionOfClassA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002432 recordDecl(hasName("A"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002433 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
2434 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
2435
2436 DeclarationMatcher DefinitionOfVariableA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002437 varDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002438 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
2439 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
2440
2441 DeclarationMatcher DefinitionOfMethodA =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002442 methodDecl(hasName("a"), isDefinition());
Manuel Klimek04616e42012-07-06 05:48:52 +00002443 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
2444 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
2445}
2446
2447TEST(Matcher, OfClass) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002448 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
Manuel Klimek04616e42012-07-06 05:48:52 +00002449 ofClass(hasName("X")))));
2450
2451 EXPECT_TRUE(
2452 matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
2453 EXPECT_TRUE(
2454 matches("class X { public: X(); }; void x(int) { X x = X(); }",
2455 Constructor));
2456 EXPECT_TRUE(
2457 notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
2458 Constructor));
2459}
2460
2461TEST(Matcher, VisitsTemplateInstantiations) {
2462 EXPECT_TRUE(matches(
2463 "class A { public: void x(); };"
2464 "template <typename T> class B { public: void y() { T t; t.x(); } };"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002465 "void f() { B<A> b; b.y(); }",
2466 callExpr(callee(methodDecl(hasName("x"))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002467
2468 EXPECT_TRUE(matches(
2469 "class A { public: void x(); };"
2470 "class C {"
2471 " public:"
2472 " template <typename T> class B { public: void y() { T t; t.x(); } };"
2473 "};"
2474 "void f() {"
2475 " C::B<A> b; b.y();"
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002476 "}",
2477 recordDecl(hasName("C"),
2478 hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002479}
2480
Daniel Jasper1dad1832012-07-10 20:20:19 +00002481TEST(Matcher, HandlesNullQualTypes) {
2482 // FIXME: Add a Type matcher so we can replace uses of this
2483 // variable with Type(True())
2484 const TypeMatcher AnyType = anything();
2485
2486 // We don't really care whether this matcher succeeds; we're testing that
2487 // it completes without crashing.
2488 EXPECT_TRUE(matches(
2489 "struct A { };"
2490 "template <typename T>"
2491 "void f(T t) {"
2492 " T local_t(t /* this becomes a null QualType in the AST */);"
2493 "}"
2494 "void g() {"
2495 " f(0);"
2496 "}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002497 expr(hasType(TypeMatcher(
Daniel Jasper1dad1832012-07-10 20:20:19 +00002498 anyOf(
2499 TypeMatcher(hasDeclaration(anything())),
2500 pointsTo(AnyType),
2501 references(AnyType)
2502 // Other QualType matchers should go here.
2503 ))))));
2504}
2505
Manuel Klimek04616e42012-07-06 05:48:52 +00002506// For testing AST_MATCHER_P().
Daniel Jasper1dad1832012-07-10 20:20:19 +00002507AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002508 // Make sure all special variables are used: node, match_finder,
2509 // bound_nodes_builder, and the parameter named 'AMatcher'.
2510 return AMatcher.matches(Node, Finder, Builder);
2511}
2512
2513TEST(AstMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002514 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002515
2516 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002517 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002518
2519 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002520 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002521
2522 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002523 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002524}
2525
2526AST_POLYMORPHIC_MATCHER_P(
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +00002527 polymorphicHas,
2528 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Decl, Stmt),
2529 internal::Matcher<Decl>, AMatcher) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002530 return Finder->matchesChildOf(
Manuel Klimekeb958de2012-09-05 12:12:07 +00002531 Node, AMatcher, Builder,
Manuel Klimek04616e42012-07-06 05:48:52 +00002532 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
2533 ASTMatchFinder::BK_First);
2534}
2535
2536TEST(AstPolymorphicMatcherPMacro, Works) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002537 DeclarationMatcher HasClassB =
2538 polymorphicHas(recordDecl(hasName("B")).bind("b"));
Manuel Klimek04616e42012-07-06 05:48:52 +00002539
2540 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002541 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002542
2543 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002544 HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002545
2546 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00002547 HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002548
2549 StatementMatcher StatementHasClassB =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002550 polymorphicHas(recordDecl(hasName("B")));
Manuel Klimek04616e42012-07-06 05:48:52 +00002551
2552 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
2553}
2554
2555TEST(For, FindsForLoops) {
2556 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
2557 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
Daniel Jasper6f595392012-10-01 15:05:34 +00002558 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
2559 "void f() { for (auto &a : as); }",
Daniel Jasper5901e472012-10-01 13:40:41 +00002560 forStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002561}
2562
Daniel Jasper4e566c42012-07-12 08:50:38 +00002563TEST(For, ForLoopInternals) {
2564 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
2565 forStmt(hasCondition(anything()))));
2566 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
2567 forStmt(hasLoopInit(anything()))));
2568}
2569
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002570TEST(For, ForRangeLoopInternals) {
2571 EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
2572 forRangeStmt(hasLoopVariable(anything()))));
Manuel Klimek86510812014-05-23 17:49:03 +00002573 EXPECT_TRUE(matches(
2574 "void f(){ int a[] {1, 2}; for (int i : a); }",
2575 forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
Alexander Kornienko9b539e12014-02-05 16:35:08 +00002576}
2577
Daniel Jasper4e566c42012-07-12 08:50:38 +00002578TEST(For, NegativeForLoopInternals) {
2579 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002580 forStmt(hasCondition(expr()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002581 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
2582 forStmt(hasLoopInit(anything()))));
2583}
2584
Manuel Klimek04616e42012-07-06 05:48:52 +00002585TEST(For, ReportsNoFalsePositives) {
2586 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
2587 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
2588}
2589
2590TEST(CompoundStatement, HandlesSimpleCases) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002591 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
2592 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
2593 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002594}
2595
2596TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
2597 // It's not a compound statement just because there's "{}" in the source
2598 // text. This is an AST search, not grep.
2599 EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002600 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002601 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002602 compoundStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002603}
2604
Daniel Jasper4e566c42012-07-12 08:50:38 +00002605TEST(HasBody, FindsBodyOfForWhileDoLoops) {
Manuel Klimek04616e42012-07-06 05:48:52 +00002606 EXPECT_TRUE(matches("void f() { for(;;) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002607 forStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002608 EXPECT_TRUE(notMatches("void f() { for(;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002609 forStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002610 EXPECT_TRUE(matches("void f() { while(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002611 whileStmt(hasBody(compoundStmt()))));
Daniel Jasper4e566c42012-07-12 08:50:38 +00002612 EXPECT_TRUE(matches("void f() { do {} while(true); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002613 doStmt(hasBody(compoundStmt()))));
Manuel Klimek2af0a912014-05-27 07:45:18 +00002614 EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
2615 forRangeStmt(hasBody(compoundStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002616}
2617
2618TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
2619 // The simplest case: every compound statement is in a function
2620 // definition, and the function body itself must be a compound
2621 // statement.
2622 EXPECT_TRUE(matches("void f() { for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002623 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002624}
2625
2626TEST(HasAnySubstatement, IsNotRecursive) {
2627 // It's really "has any immediate substatement".
2628 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002629 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002630}
2631
2632TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
2633 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002634 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002635}
2636
2637TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
2638 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002639 compoundStmt(hasAnySubstatement(forStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002640}
2641
2642TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
2643 EXPECT_TRUE(matches("void f() { }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002644 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002645 EXPECT_TRUE(notMatches("void f() {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002646 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002647}
2648
2649TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
2650 EXPECT_TRUE(matches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002651 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002652 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002653 compoundStmt(statementCountIs(0))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002654 EXPECT_TRUE(notMatches("void f() { 1; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002655 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002656}
2657
2658TEST(StatementCountIs, WorksWithMultipleStatements) {
2659 EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002660 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002661}
2662
2663TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
2664 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002665 compoundStmt(statementCountIs(1))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002666 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002667 compoundStmt(statementCountIs(2))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002668 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002669 compoundStmt(statementCountIs(3))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002670 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002671 compoundStmt(statementCountIs(4))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002672}
2673
2674TEST(Member, WorksInSimplestCase) {
2675 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002676 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002677}
2678
2679TEST(Member, DoesNotMatchTheBaseExpression) {
2680 // Don't pick out the wrong part of the member expression, this should
2681 // be checking the member (name) only.
2682 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002683 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002684}
2685
2686TEST(Member, MatchesInMemberFunctionCall) {
2687 EXPECT_TRUE(matches("void f() {"
2688 " struct { void first() {}; } s;"
2689 " s.first();"
2690 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002691 memberExpr(member(hasName("first")))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002692}
2693
Daniel Jasperb0c7b612012-10-23 15:46:39 +00002694TEST(Member, MatchesMember) {
2695 EXPECT_TRUE(matches(
2696 "struct A { int i; }; void f() { A a; a.i = 2; }",
2697 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2698 EXPECT_TRUE(notMatches(
2699 "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
2700 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
2701}
2702
Daniel Jasper639522c2013-02-25 12:02:08 +00002703TEST(Member, UnderstandsAccess) {
2704 EXPECT_TRUE(matches(
2705 "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2706 EXPECT_TRUE(notMatches(
2707 "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2708 EXPECT_TRUE(notMatches(
2709 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2710
2711 EXPECT_TRUE(notMatches(
2712 "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
2713 EXPECT_TRUE(notMatches(
2714 "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
2715 EXPECT_TRUE(matches(
2716 "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
2717
2718 EXPECT_TRUE(notMatches(
2719 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
2720 EXPECT_TRUE(matches("class A { protected: int i; };",
2721 fieldDecl(isProtected(), hasName("i"))));
2722 EXPECT_TRUE(notMatches(
2723 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
2724
2725 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
2726 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
2727 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
2728 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
2729}
2730
Dmitri Gribenko06963042012-08-18 00:29:27 +00002731TEST(Member, MatchesMemberAllocationFunction) {
Daniel Jasper5901e472012-10-01 13:40:41 +00002732 // Fails in C++11 mode
2733 EXPECT_TRUE(matchesConditionally(
2734 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2735 "class X { void *operator new(std::size_t); };",
2736 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002737
2738 EXPECT_TRUE(matches("class X { void operator delete(void*); };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002739 methodDecl(ofClass(hasName("X")))));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002740
Daniel Jasper5901e472012-10-01 13:40:41 +00002741 // Fails in C++11 mode
2742 EXPECT_TRUE(matchesConditionally(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002743 "namespace std { typedef typeof(sizeof(int)) size_t; }"
2744 "class X { void operator delete[](void*, std::size_t); };",
Daniel Jasper5901e472012-10-01 13:40:41 +00002745 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
Dmitri Gribenko06963042012-08-18 00:29:27 +00002746}
2747
Manuel Klimek04616e42012-07-06 05:48:52 +00002748TEST(HasObjectExpression, DoesNotMatchMember) {
2749 EXPECT_TRUE(notMatches(
2750 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002751 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002752}
2753
2754TEST(HasObjectExpression, MatchesBaseOfVariable) {
2755 EXPECT_TRUE(matches(
2756 "struct X { int m; }; void f(X x) { x.m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002757 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002758 EXPECT_TRUE(matches(
2759 "struct X { int m; }; void f(X* x) { x->m; }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002760 memberExpr(hasObjectExpression(
2761 hasType(pointsTo(recordDecl(hasName("X"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002762}
2763
2764TEST(HasObjectExpression,
2765 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
2766 EXPECT_TRUE(matches(
2767 "class X {}; struct S { X m; void f() { this->m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002768 memberExpr(hasObjectExpression(
2769 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002770 EXPECT_TRUE(matches(
2771 "class X {}; struct S { X m; void f() { m; } };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002772 memberExpr(hasObjectExpression(
2773 hasType(pointsTo(recordDecl(hasName("S"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002774}
2775
2776TEST(Field, DoesNotMatchNonFieldMembers) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002777 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
2778 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
2779 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
2780 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002781}
2782
2783TEST(Field, MatchesField) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002784 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002785}
2786
2787TEST(IsConstQualified, MatchesConstInt) {
2788 EXPECT_TRUE(matches("const int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002789 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002790}
2791
2792TEST(IsConstQualified, MatchesConstPointer) {
2793 EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002794 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002795}
2796
2797TEST(IsConstQualified, MatchesThroughTypedef) {
2798 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002799 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002800 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002801 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002802}
2803
2804TEST(IsConstQualified, DoesNotMatchInappropriately) {
2805 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002806 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002807 EXPECT_TRUE(notMatches("int const* p;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002808 varDecl(hasType(isConstQualified()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002809}
2810
Sam Panzer80c13772012-08-16 16:58:10 +00002811TEST(CastExpression, MatchesExplicitCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002812 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
2813 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
2814 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
2815 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002816}
2817TEST(CastExpression, MatchesImplicitCasts) {
2818 // This test creates an implicit cast from int to char.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002819 EXPECT_TRUE(matches("char c = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002820 // This test creates an implicit cast from lvalue to rvalue.
Daniel Jasper848cbe12012-09-18 13:09:13 +00002821 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002822}
2823
2824TEST(CastExpression, DoesNotMatchNonCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002825 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
2826 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
2827 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
2828 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
Sam Panzer80c13772012-08-16 16:58:10 +00002829}
2830
Manuel Klimek04616e42012-07-06 05:48:52 +00002831TEST(ReinterpretCast, MatchesSimpleCase) {
2832 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002833 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002834}
2835
2836TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002837 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002838 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002839 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002840 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002841 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002842 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2843 "B b;"
2844 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002845 reinterpretCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002846}
2847
2848TEST(FunctionalCast, MatchesSimpleCase) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002849 std::string foo_class = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002850 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002851 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002852}
2853
2854TEST(FunctionalCast, DoesNotMatchOtherCasts) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00002855 std::string FooClass = "class Foo { public: Foo(const char*); };";
Manuel Klimek04616e42012-07-06 05:48:52 +00002856 EXPECT_TRUE(
2857 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002858 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002859 EXPECT_TRUE(
2860 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002861 functionalCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002862}
2863
2864TEST(DynamicCast, MatchesSimpleCase) {
2865 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
2866 "B b;"
2867 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002868 dynamicCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002869}
2870
2871TEST(StaticCast, MatchesSimpleCase) {
2872 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002873 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002874}
2875
2876TEST(StaticCast, DoesNotMatchOtherCasts) {
Daniel Jasper848cbe12012-09-18 13:09:13 +00002877 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002878 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002879 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002880 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002881 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002882 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
2883 "B b;"
2884 "D* p = dynamic_cast<D*>(&b);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002885 staticCastExpr()));
Manuel Klimek04616e42012-07-06 05:48:52 +00002886}
2887
Daniel Jasper417f7762012-09-18 13:36:17 +00002888TEST(CStyleCast, MatchesSimpleCase) {
2889 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
2890}
2891
2892TEST(CStyleCast, DoesNotMatchOtherCasts) {
2893 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
2894 "char q, *r = const_cast<char*>(&q);"
2895 "void* s = reinterpret_cast<char*>(&s);"
2896 "struct B { virtual ~B() {} }; struct D : B {};"
2897 "B b;"
2898 "D* t = dynamic_cast<D*>(&b);",
2899 cStyleCastExpr()));
2900}
2901
Manuel Klimek04616e42012-07-06 05:48:52 +00002902TEST(HasDestinationType, MatchesSimpleCase) {
2903 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002904 staticCastExpr(hasDestinationType(
2905 pointsTo(TypeMatcher(anything()))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00002906}
2907
Sam Panzer80c13772012-08-16 16:58:10 +00002908TEST(HasImplicitDestinationType, MatchesSimpleCase) {
2909 // This test creates an implicit const cast.
2910 EXPECT_TRUE(matches("int x; const int i = x;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002911 implicitCastExpr(
2912 hasImplicitDestinationType(isInteger()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002913 // This test creates an implicit array-to-pointer cast.
2914 EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002915 implicitCastExpr(hasImplicitDestinationType(
2916 pointsTo(TypeMatcher(anything()))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002917}
2918
2919TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
2920 // This test creates an implicit cast from int to char.
2921 EXPECT_TRUE(notMatches("char c = 0;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002922 implicitCastExpr(hasImplicitDestinationType(
2923 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002924 // This test creates an implicit array-to-pointer cast.
2925 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
Daniel Jasper848cbe12012-09-18 13:09:13 +00002926 implicitCastExpr(hasImplicitDestinationType(
2927 unless(anything())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002928}
2929
2930TEST(ImplicitCast, MatchesSimpleCase) {
2931 // This test creates an implicit const cast.
2932 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002933 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002934 // This test creates an implicit cast from int to char.
2935 EXPECT_TRUE(matches("char c = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002936 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002937 // This test creates an implicit array-to-pointer cast.
2938 EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002939 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002940}
2941
2942TEST(ImplicitCast, DoesNotMatchIncorrectly) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002943 // This test verifies that implicitCastExpr() matches exactly when implicit casts
Sam Panzer80c13772012-08-16 16:58:10 +00002944 // are present, and that it ignores explicit and paren casts.
2945
2946 // These two test cases have no casts.
2947 EXPECT_TRUE(notMatches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002948 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002949 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002950 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002951
2952 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002953 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002954 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002955 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002956
2957 EXPECT_TRUE(notMatches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002958 varDecl(hasInitializer(implicitCastExpr()))));
Sam Panzer80c13772012-08-16 16:58:10 +00002959}
2960
2961TEST(IgnoringImpCasts, MatchesImpCasts) {
2962 // This test checks that ignoringImpCasts matches when implicit casts are
2963 // present and its inner matcher alone does not match.
2964 // Note that this test creates an implicit const cast.
2965 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002966 varDecl(hasInitializer(ignoringImpCasts(
2967 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00002968 // This test creates an implict cast from int to char.
2969 EXPECT_TRUE(matches("char x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002970 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002971 integerLiteral(equals(0)))))));
2972}
2973
2974TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
2975 // These tests verify that ignoringImpCasts does not match if the inner
2976 // matcher does not match.
2977 // Note that the first test creates an implicit const cast.
2978 EXPECT_TRUE(notMatches("int x; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002979 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002980 unless(anything()))))));
2981 EXPECT_TRUE(notMatches("int x; int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002982 varDecl(hasInitializer(ignoringImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00002983 unless(anything()))))));
2984
2985 // These tests verify that ignoringImplictCasts does not look through explicit
2986 // casts or parentheses.
2987 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002988 varDecl(hasInitializer(ignoringImpCasts(
2989 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002990 EXPECT_TRUE(notMatches("int i = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002991 varDecl(hasInitializer(ignoringImpCasts(
2992 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002993 EXPECT_TRUE(notMatches("float i = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002994 varDecl(hasInitializer(ignoringImpCasts(
2995 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002996 EXPECT_TRUE(notMatches("float i = float(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00002997 varDecl(hasInitializer(ignoringImpCasts(
2998 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00002999}
3000
3001TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
3002 // This test verifies that expressions that do not have implicit casts
3003 // still match the inner matcher.
3004 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003005 varDecl(hasInitializer(ignoringImpCasts(
3006 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003007}
3008
3009TEST(IgnoringParenCasts, MatchesParenCasts) {
3010 // This test checks that ignoringParenCasts matches when parentheses and/or
3011 // casts are present and its inner matcher alone does not match.
3012 EXPECT_TRUE(matches("int x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003013 varDecl(hasInitializer(ignoringParenCasts(
3014 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003015 EXPECT_TRUE(matches("int x = (((((0)))));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003016 varDecl(hasInitializer(ignoringParenCasts(
3017 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003018
3019 // This test creates an implict cast from int to char in addition to the
3020 // parentheses.
3021 EXPECT_TRUE(matches("char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003022 varDecl(hasInitializer(ignoringParenCasts(
3023 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003024
3025 EXPECT_TRUE(matches("char x = (char)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003026 varDecl(hasInitializer(ignoringParenCasts(
3027 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003028 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003029 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003030 integerLiteral(equals(0)))))));
3031}
3032
3033TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
3034 // This test verifies that expressions that do not have any casts still match.
3035 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003036 varDecl(hasInitializer(ignoringParenCasts(
3037 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003038}
3039
3040TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
3041 // These tests verify that ignoringImpCasts does not match if the inner
3042 // matcher does not match.
3043 EXPECT_TRUE(notMatches("int x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003044 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003045 unless(anything()))))));
3046
3047 // This test creates an implicit cast from int to char in addition to the
3048 // parentheses.
3049 EXPECT_TRUE(notMatches("char x = ((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003050 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003051 unless(anything()))))));
3052
3053 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003054 varDecl(hasInitializer(ignoringParenCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003055 unless(anything()))))));
3056}
3057
3058TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
3059 // This test checks that ignoringParenAndImpCasts matches when
3060 // parentheses and/or implicit casts are present and its inner matcher alone
3061 // does not match.
3062 // Note that this test creates an implicit const cast.
3063 EXPECT_TRUE(matches("int x = 0; const int y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003064 varDecl(hasInitializer(ignoringParenImpCasts(
3065 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003066 // This test creates an implicit cast from int to char.
3067 EXPECT_TRUE(matches("const char x = (0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003068 varDecl(hasInitializer(ignoringParenImpCasts(
3069 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003070}
3071
3072TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
3073 // This test verifies that expressions that do not have parentheses or
3074 // implicit casts still match.
3075 EXPECT_TRUE(matches("int x = 0; int &y = x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003076 varDecl(hasInitializer(ignoringParenImpCasts(
3077 declRefExpr(to(varDecl(hasName("x")))))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003078 EXPECT_TRUE(matches("int x = 0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003079 varDecl(hasInitializer(ignoringParenImpCasts(
3080 integerLiteral(equals(0)))))));
Sam Panzer80c13772012-08-16 16:58:10 +00003081}
3082
3083TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
3084 // These tests verify that ignoringParenImpCasts does not match if
3085 // the inner matcher does not match.
3086 // This test creates an implicit cast.
3087 EXPECT_TRUE(notMatches("char c = ((3));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003088 varDecl(hasInitializer(ignoringParenImpCasts(
Sam Panzer80c13772012-08-16 16:58:10 +00003089 unless(anything()))))));
3090 // These tests verify that ignoringParenAndImplictCasts does not look
3091 // through explicit casts.
3092 EXPECT_TRUE(notMatches("float y = (float(0));",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003093 varDecl(hasInitializer(ignoringParenImpCasts(
3094 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003095 EXPECT_TRUE(notMatches("float y = (float)0;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003096 varDecl(hasInitializer(ignoringParenImpCasts(
3097 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003098 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003099 varDecl(hasInitializer(ignoringParenImpCasts(
3100 integerLiteral())))));
Sam Panzer80c13772012-08-16 16:58:10 +00003101}
3102
Manuel Klimeke9235692012-07-25 10:02:02 +00003103TEST(HasSourceExpression, MatchesImplicitCasts) {
Manuel Klimek04616e42012-07-06 05:48:52 +00003104 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
3105 "void r() {string a_string; URL url = a_string; }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003106 implicitCastExpr(
3107 hasSourceExpression(constructExpr()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003108}
3109
Manuel Klimeke9235692012-07-25 10:02:02 +00003110TEST(HasSourceExpression, MatchesExplicitCasts) {
3111 EXPECT_TRUE(matches("float x = static_cast<float>(42);",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003112 explicitCastExpr(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003113 hasSourceExpression(hasDescendant(
Daniel Jasper848cbe12012-09-18 13:09:13 +00003114 expr(integerLiteral()))))));
Manuel Klimeke9235692012-07-25 10:02:02 +00003115}
3116
Manuel Klimek04616e42012-07-06 05:48:52 +00003117TEST(Statement, DoesNotMatchDeclarations) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003118 EXPECT_TRUE(notMatches("class X {};", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003119}
3120
3121TEST(Statement, MatchesCompoundStatments) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003122 EXPECT_TRUE(matches("void x() {}", stmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003123}
3124
3125TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003126 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003127}
3128
3129TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003130 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
Manuel Klimek04616e42012-07-06 05:48:52 +00003131}
3132
Samuel Benzaquenf1066292014-04-02 13:12:14 +00003133TEST(ExprWithCleanups, MatchesExprWithCleanups) {
3134 EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
3135 "const Foo f = Foo();",
3136 varDecl(hasInitializer(exprWithCleanups()))));
3137 EXPECT_FALSE(matches("struct Foo { };"
3138 "const Foo f = Foo();",
3139 varDecl(hasInitializer(exprWithCleanups()))));
3140}
3141
Daniel Jasper1dad1832012-07-10 20:20:19 +00003142TEST(InitListExpression, MatchesInitListExpression) {
3143 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
3144 initListExpr(hasType(asString("int [2]")))));
3145 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003146 initListExpr(hasType(recordDecl(hasName("B"))))));
Daniel Jasper1d8ecbd2015-02-04 13:11:42 +00003147 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
3148 "void f();"
3149 "S s[1] = { &f };",
3150 declRefExpr(to(functionDecl(hasName("f"))))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003151}
3152
3153TEST(UsingDeclaration, MatchesUsingDeclarations) {
3154 EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
3155 usingDecl()));
3156}
3157
3158TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
3159 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
3160 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
3161}
3162
3163TEST(UsingDeclaration, MatchesSpecificTarget) {
3164 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
3165 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003166 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003167 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
3168 usingDecl(hasAnyUsingShadowDecl(
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003169 hasTargetDecl(functionDecl())))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003170}
3171
3172TEST(UsingDeclaration, ThroughUsingDeclaration) {
3173 EXPECT_TRUE(matches(
3174 "namespace a { void f(); } using a::f; void g() { f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003175 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003176 EXPECT_TRUE(notMatches(
3177 "namespace a { void f(); } using a::f; void g() { a::f(); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003178 declRefExpr(throughUsingDecl(anything()))));
Daniel Jasper1dad1832012-07-10 20:20:19 +00003179}
3180
Benjamin Kramer73ef2162014-07-16 14:14:51 +00003181TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
3182 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
3183 usingDirectiveDecl()));
3184 EXPECT_FALSE(
3185 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
3186}
3187
Sam Panzerd624bfb2012-08-16 17:20:59 +00003188TEST(SingleDecl, IsSingleDecl) {
3189 StatementMatcher SingleDeclStmt =
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003190 declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003191 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
3192 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
3193 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
3194 SingleDeclStmt));
3195}
3196
3197TEST(DeclStmt, ContainsDeclaration) {
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003198 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003199
3200 EXPECT_TRUE(matches("void f() {int a = 4;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003201 declStmt(containsDeclaration(0, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003202 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003203 declStmt(containsDeclaration(0, MatchesInit),
3204 containsDeclaration(1, MatchesInit))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003205 unsigned WrongIndex = 42;
3206 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003207 declStmt(containsDeclaration(WrongIndex,
Sam Panzerd624bfb2012-08-16 17:20:59 +00003208 MatchesInit))));
3209}
3210
3211TEST(DeclCount, DeclCountIsCorrect) {
3212 EXPECT_TRUE(matches("void f() {int i,j;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003213 declStmt(declCountIs(2))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003214 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003215 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003216 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003217 declStmt(declCountIs(3))));
Sam Panzerd624bfb2012-08-16 17:20:59 +00003218}
3219
Manuel Klimek04616e42012-07-06 05:48:52 +00003220TEST(While, MatchesWhileLoops) {
3221 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
3222 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
3223 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
3224}
3225
3226TEST(Do, MatchesDoLoops) {
3227 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
3228 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
3229}
3230
3231TEST(Do, DoesNotMatchWhileLoops) {
3232 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
3233}
3234
3235TEST(SwitchCase, MatchesCase) {
3236 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
3237 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
3238 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
3239 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
3240}
3241
Daniel Jasper87c3d362012-09-20 14:12:57 +00003242TEST(SwitchCase, MatchesSwitch) {
3243 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
3244 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
3245 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
3246 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
3247}
3248
Peter Collingbourne3154a102013-05-10 11:52:02 +00003249TEST(SwitchCase, MatchesEachCase) {
3250 EXPECT_TRUE(notMatches("void x() { switch(42); }",
3251 switchStmt(forEachSwitchCase(caseStmt()))));
3252 EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
3253 switchStmt(forEachSwitchCase(caseStmt()))));
3254 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
3255 switchStmt(forEachSwitchCase(caseStmt()))));
3256 EXPECT_TRUE(notMatches(
3257 "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
3258 ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
3259 EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
3260 switchStmt(forEachSwitchCase(
3261 caseStmt(hasCaseConstant(integerLiteral()))))));
3262 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
3263 switchStmt(forEachSwitchCase(
3264 caseStmt(hasCaseConstant(integerLiteral()))))));
3265 EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
3266 switchStmt(forEachSwitchCase(
3267 caseStmt(hasCaseConstant(integerLiteral()))))));
3268 EXPECT_TRUE(matchAndVerifyResultTrue(
3269 "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
3270 switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
3271 new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
3272}
3273
Manuel Klimekba46fc02013-07-19 11:50:54 +00003274TEST(ForEachConstructorInitializer, MatchesInitializers) {
3275 EXPECT_TRUE(matches(
3276 "struct X { X() : i(42), j(42) {} int i, j; };",
3277 constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
3278}
3279
Daniel Jasper87c3d362012-09-20 14:12:57 +00003280TEST(ExceptionHandling, SimpleCases) {
3281 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
3282 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
3283 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
3284 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
3285 throwExpr()));
3286 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
3287 throwExpr()));
3288}
3289
Manuel Klimek04616e42012-07-06 05:48:52 +00003290TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
3291 EXPECT_TRUE(notMatches(
3292 "void x() { if(true) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003293 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003294 EXPECT_TRUE(notMatches(
3295 "void x() { int x; if((x = 42)) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003296 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003297}
3298
3299TEST(HasConditionVariableStatement, MatchesConditionVariables) {
3300 EXPECT_TRUE(matches(
3301 "void x() { if(int* a = 0) {} }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003302 ifStmt(hasConditionVariableStatement(declStmt()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003303}
3304
3305TEST(ForEach, BindsOneNode) {
3306 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003307 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003308 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003309}
3310
3311TEST(ForEach, BindsMultipleNodes) {
3312 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003313 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003314 new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003315}
3316
3317TEST(ForEach, BindsRecursiveCombinations) {
3318 EXPECT_TRUE(matchAndVerifyResultTrue(
3319 "class C { class D { int x; int y; }; class E { int y; int z; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003320 recordDecl(hasName("C"),
3321 forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003322 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003323}
3324
3325TEST(ForEachDescendant, BindsOneNode) {
3326 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003327 recordDecl(hasName("C"),
3328 forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003329 new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003330}
3331
Daniel Jasper94a56852012-11-16 18:39:22 +00003332TEST(ForEachDescendant, NestedForEachDescendant) {
3333 DeclarationMatcher m = recordDecl(
3334 isDefinition(), decl().bind("x"), hasName("C"));
3335 EXPECT_TRUE(matchAndVerifyResultTrue(
3336 "class A { class B { class C {}; }; };",
3337 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
3338 new VerifyIdIsBoundTo<Decl>("x", "C")));
3339
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003340 // Check that a partial match of 'm' that binds 'x' in the
3341 // first part of anyOf(m, anything()) will not overwrite the
3342 // binding created by the earlier binding in the hasDescendant.
3343 EXPECT_TRUE(matchAndVerifyResultTrue(
3344 "class A { class B { class C {}; }; };",
3345 recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
3346 new VerifyIdIsBoundTo<Decl>("x", "C")));
Daniel Jasper94a56852012-11-16 18:39:22 +00003347}
3348
Manuel Klimek04616e42012-07-06 05:48:52 +00003349TEST(ForEachDescendant, BindsMultipleNodes) {
3350 EXPECT_TRUE(matchAndVerifyResultTrue(
3351 "class C { class D { int x; int y; }; "
3352 " class E { class F { int y; int z; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003353 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003354 new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003355}
3356
3357TEST(ForEachDescendant, BindsRecursiveCombinations) {
3358 EXPECT_TRUE(matchAndVerifyResultTrue(
3359 "class C { class D { "
3360 " class E { class F { class G { int y; int z; }; }; }; }; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003361 recordDecl(hasName("C"), forEachDescendant(recordDecl(
3362 forEachDescendant(fieldDecl().bind("f"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003363 new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
Manuel Klimek04616e42012-07-06 05:48:52 +00003364}
3365
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003366TEST(ForEachDescendant, BindsCombinations) {
3367 EXPECT_TRUE(matchAndVerifyResultTrue(
3368 "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
3369 "(true) {} }",
3370 compoundStmt(forEachDescendant(ifStmt().bind("if")),
3371 forEachDescendant(whileStmt().bind("while"))),
3372 new VerifyIdIsBoundTo<IfStmt>("if", 6)));
3373}
3374
3375TEST(Has, DoesNotDeleteBindings) {
3376 EXPECT_TRUE(matchAndVerifyResultTrue(
3377 "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
3378 new VerifyIdIsBoundTo<Decl>("x", 1)));
3379}
3380
3381TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
3382 // Those matchers cover all the cases where an inner matcher is called
3383 // and there is not a 1:1 relationship between the match of the outer
3384 // matcher and the match of the inner matcher.
3385 // The pattern to look for is:
3386 // ... return InnerMatcher.matches(...); ...
3387 // In which case no special handling is needed.
3388 //
3389 // On the other hand, if there are multiple alternative matches
3390 // (for example forEach*) or matches might be discarded (for example has*)
3391 // the implementation must make sure that the discarded matches do not
3392 // affect the bindings.
3393 // When new such matchers are added, add a test here that:
3394 // - matches a simple node, and binds it as the first thing in the matcher:
3395 // recordDecl(decl().bind("x"), hasName("X")))
3396 // - uses the matcher under test afterwards in a way that not the first
3397 // alternative is matched; for anyOf, that means the first branch
3398 // would need to return false; for hasAncestor, it means that not
3399 // the direct parent matches the inner matcher.
3400
3401 EXPECT_TRUE(matchAndVerifyResultTrue(
3402 "class X { int y; };",
3403 recordDecl(
3404 recordDecl().bind("x"), hasName("::X"),
3405 anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
3406 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3407 EXPECT_TRUE(matchAndVerifyResultTrue(
3408 "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
3409 anyOf(unless(anything()), anything())),
3410 new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
3411 EXPECT_TRUE(matchAndVerifyResultTrue(
3412 "template<typename T1, typename T2> class X {}; X<float, int> x;",
3413 classTemplateSpecializationDecl(
3414 decl().bind("x"),
3415 hasAnyTemplateArgument(refersToType(asString("int")))),
3416 new VerifyIdIsBoundTo<Decl>("x", 1)));
3417 EXPECT_TRUE(matchAndVerifyResultTrue(
3418 "class X { void f(); void g(); };",
3419 recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
3420 new VerifyIdIsBoundTo<Decl>("x", 1)));
3421 EXPECT_TRUE(matchAndVerifyResultTrue(
3422 "class X { X() : a(1), b(2) {} double a; int b; };",
3423 recordDecl(decl().bind("x"),
3424 has(constructorDecl(
3425 hasAnyConstructorInitializer(forField(hasName("b")))))),
3426 new VerifyIdIsBoundTo<Decl>("x", 1)));
3427 EXPECT_TRUE(matchAndVerifyResultTrue(
3428 "void x(int, int) { x(0, 42); }",
3429 callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
3430 new VerifyIdIsBoundTo<Expr>("x", 1)));
3431 EXPECT_TRUE(matchAndVerifyResultTrue(
3432 "void x(int, int y) {}",
3433 functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
3434 new VerifyIdIsBoundTo<Decl>("x", 1)));
3435 EXPECT_TRUE(matchAndVerifyResultTrue(
3436 "void x() { return; if (true) {} }",
3437 functionDecl(decl().bind("x"),
3438 has(compoundStmt(hasAnySubstatement(ifStmt())))),
3439 new VerifyIdIsBoundTo<Decl>("x", 1)));
3440 EXPECT_TRUE(matchAndVerifyResultTrue(
3441 "namespace X { void b(int); void b(); }"
3442 "using X::b;",
3443 usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
3444 functionDecl(parameterCountIs(1))))),
3445 new VerifyIdIsBoundTo<Decl>("x", 1)));
3446 EXPECT_TRUE(matchAndVerifyResultTrue(
3447 "class A{}; class B{}; class C : B, A {};",
3448 recordDecl(decl().bind("x"), isDerivedFrom("::A")),
3449 new VerifyIdIsBoundTo<Decl>("x", 1)));
3450 EXPECT_TRUE(matchAndVerifyResultTrue(
3451 "class A{}; typedef A B; typedef A C; typedef A D;"
3452 "class E : A {};",
3453 recordDecl(decl().bind("x"), isDerivedFrom("C")),
3454 new VerifyIdIsBoundTo<Decl>("x", 1)));
3455 EXPECT_TRUE(matchAndVerifyResultTrue(
3456 "class A { class B { void f() {} }; };",
3457 functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3458 new VerifyIdIsBoundTo<Decl>("x", 1)));
3459 EXPECT_TRUE(matchAndVerifyResultTrue(
3460 "template <typename T> struct A { struct B {"
3461 " void f() { if(true) {} }"
3462 "}; };"
3463 "void t() { A<int>::B b; b.f(); }",
3464 ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
3465 new VerifyIdIsBoundTo<Stmt>("x", 2)));
3466 EXPECT_TRUE(matchAndVerifyResultTrue(
3467 "class A {};",
3468 recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
3469 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimekba46fc02013-07-19 11:50:54 +00003470 EXPECT_TRUE(matchAndVerifyResultTrue(
3471 "class A { A() : s(), i(42) {} const char *s; int i; };",
3472 constructorDecl(hasName("::A::A"), decl().bind("x"),
3473 forEachConstructorInitializer(forField(hasName("i")))),
3474 new VerifyIdIsBoundTo<Decl>("x", 1)));
Manuel Klimeka0c025f2013-06-19 15:42:45 +00003475}
3476
Daniel Jasper33806cd2012-11-11 22:14:55 +00003477TEST(ForEachDescendant, BindsCorrectNodes) {
3478 EXPECT_TRUE(matchAndVerifyResultTrue(
3479 "class C { void f(); int i; };",
3480 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3481 new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
3482 EXPECT_TRUE(matchAndVerifyResultTrue(
3483 "class C { void f() {} int i; };",
3484 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
3485 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
3486}
3487
Manuel Klimekabf43712013-02-04 10:59:20 +00003488TEST(FindAll, BindsNodeOnMatch) {
3489 EXPECT_TRUE(matchAndVerifyResultTrue(
3490 "class A {};",
3491 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
3492 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
3493}
3494
3495TEST(FindAll, BindsDescendantNodeOnMatch) {
3496 EXPECT_TRUE(matchAndVerifyResultTrue(
3497 "class A { int a; int b; };",
3498 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
3499 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3500}
3501
3502TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
3503 EXPECT_TRUE(matchAndVerifyResultTrue(
3504 "class A { int a; int b; };",
3505 recordDecl(hasName("::A"),
3506 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
3507 fieldDecl().bind("v"))))),
3508 new VerifyIdIsBoundTo<Decl>("v", 3)));
3509
3510 EXPECT_TRUE(matchAndVerifyResultTrue(
3511 "class A { class B {}; class C {}; };",
3512 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
3513 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
3514}
3515
Manuel Klimek88b95872013-02-04 09:42:38 +00003516TEST(EachOf, TriggersForEachMatch) {
3517 EXPECT_TRUE(matchAndVerifyResultTrue(
3518 "class A { int a; int b; };",
3519 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3520 has(fieldDecl(hasName("b")).bind("v")))),
3521 new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
3522}
3523
3524TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
3525 EXPECT_TRUE(matchAndVerifyResultTrue(
3526 "class A { int a; int c; };",
3527 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3528 has(fieldDecl(hasName("b")).bind("v")))),
3529 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3530 EXPECT_TRUE(matchAndVerifyResultTrue(
3531 "class A { int c; int b; };",
3532 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3533 has(fieldDecl(hasName("b")).bind("v")))),
3534 new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
3535 EXPECT_TRUE(notMatches(
3536 "class A { int c; int d; };",
3537 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
3538 has(fieldDecl(hasName("b")).bind("v"))))));
3539}
Manuel Klimek04616e42012-07-06 05:48:52 +00003540
3541TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
3542 // Make sure that we can both match the class by name (::X) and by the type
3543 // the template was instantiated with (via a field).
3544
3545 EXPECT_TRUE(matches(
3546 "template <typename T> class X {}; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003547 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003548
3549 EXPECT_TRUE(matches(
3550 "template <typename T> class X { T t; }; class A {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003551 recordDecl(isTemplateInstantiation(), hasDescendant(
3552 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003553}
3554
3555TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
3556 EXPECT_TRUE(matches(
3557 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003558 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
Manuel Klimek04616e42012-07-06 05:48:52 +00003559 isTemplateInstantiation())));
3560}
3561
3562TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
3563 EXPECT_TRUE(matches(
3564 "template <typename T> class X { T t; }; class A {};"
3565 "template class X<A>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003566 recordDecl(isTemplateInstantiation(), hasDescendant(
3567 fieldDecl(hasType(recordDecl(hasName("A"))))))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003568}
3569
3570TEST(IsTemplateInstantiation,
3571 MatchesInstantiationOfPartiallySpecializedClassTemplate) {
3572 EXPECT_TRUE(matches(
3573 "template <typename T> class X {};"
3574 "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003575 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003576}
3577
3578TEST(IsTemplateInstantiation,
3579 MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
3580 EXPECT_TRUE(matches(
3581 "class A {};"
3582 "class X {"
3583 " template <typename U> class Y { U u; };"
3584 " Y<A> y;"
3585 "};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003586 recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003587}
3588
3589TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
3590 // FIXME: Figure out whether this makes sense. It doesn't affect the
3591 // normal use case as long as the uppermost instantiation always is marked
3592 // as template instantiation, but it might be confusing as a predicate.
3593 EXPECT_TRUE(matches(
3594 "class A {};"
3595 "template <typename T> class X {"
3596 " template <typename U> class Y { U u; };"
3597 " Y<T> y;"
3598 "}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003599 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
Manuel Klimek04616e42012-07-06 05:48:52 +00003600}
3601
3602TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
3603 EXPECT_TRUE(notMatches(
3604 "template <typename T> class X {}; class A {};"
3605 "template <> class X<A> {}; X<A> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003606 recordDecl(hasName("::X"), isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003607}
3608
3609TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
3610 EXPECT_TRUE(notMatches(
3611 "class A {}; class Y { A a; };",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003612 recordDecl(isTemplateInstantiation())));
Manuel Klimek04616e42012-07-06 05:48:52 +00003613}
3614
Benjamin Kramer7ab84762014-09-03 12:08:14 +00003615TEST(IsInstantiated, MatchesInstantiation) {
3616 EXPECT_TRUE(
3617 matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
3618 recordDecl(isInstantiated())));
3619}
3620
3621TEST(IsInstantiated, NotMatchesDefinition) {
3622 EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
3623 recordDecl(isInstantiated())));
3624}
3625
3626TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
3627 EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
3628 "class Y { A<int> a; }; Y y;",
3629 declStmt(isInTemplateInstantiation())));
3630}
3631
3632TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
3633 EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
3634 declStmt(isInTemplateInstantiation())));
3635}
3636
3637TEST(IsInstantiated, MatchesFunctionInstantiation) {
3638 EXPECT_TRUE(
3639 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3640 functionDecl(isInstantiated())));
3641}
3642
3643TEST(IsInstantiated, NotMatchesFunctionDefinition) {
3644 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3645 varDecl(isInstantiated())));
3646}
3647
3648TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
3649 EXPECT_TRUE(
3650 matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
3651 declStmt(isInTemplateInstantiation())));
3652}
3653
3654TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
3655 EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
3656 declStmt(isInTemplateInstantiation())));
3657}
3658
3659TEST(IsInTemplateInstantiation, Sharing) {
3660 auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
3661 // FIXME: Node sharing is an implementation detail, exposing it is ugly
3662 // and makes the matcher behave in non-obvious ways.
3663 EXPECT_TRUE(notMatches(
3664 "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
3665 Matcher));
3666 EXPECT_TRUE(matches(
3667 "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
3668 Matcher));
3669}
3670
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003671TEST(IsExplicitTemplateSpecialization,
3672 DoesNotMatchPrimaryTemplate) {
3673 EXPECT_TRUE(notMatches(
3674 "template <typename T> class X {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003675 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003676 EXPECT_TRUE(notMatches(
3677 "template <typename T> void f(T t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003678 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003679}
3680
3681TEST(IsExplicitTemplateSpecialization,
3682 DoesNotMatchExplicitTemplateInstantiations) {
3683 EXPECT_TRUE(notMatches(
3684 "template <typename T> class X {};"
3685 "template class X<int>; extern template class X<long>;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003686 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003687 EXPECT_TRUE(notMatches(
3688 "template <typename T> void f(T t) {}"
3689 "template void f(int t); extern template void f(long t);",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003690 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003691}
3692
3693TEST(IsExplicitTemplateSpecialization,
3694 DoesNotMatchImplicitTemplateInstantiations) {
3695 EXPECT_TRUE(notMatches(
3696 "template <typename T> class X {}; X<int> x;",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003697 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003698 EXPECT_TRUE(notMatches(
3699 "template <typename T> void f(T t); void g() { f(10); }",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003700 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003701}
3702
3703TEST(IsExplicitTemplateSpecialization,
3704 MatchesExplicitTemplateSpecializations) {
3705 EXPECT_TRUE(matches(
3706 "template <typename T> class X {};"
3707 "template<> class X<int> {};",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003708 recordDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003709 EXPECT_TRUE(matches(
3710 "template <typename T> void f(T t) {}"
3711 "template<> void f(int t) {}",
Daniel Jasperbd3d76d2012-08-24 05:12:34 +00003712 functionDecl(isExplicitTemplateSpecialization())));
Dmitri Gribenkod394c8a2012-08-17 18:42:47 +00003713}
3714
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003715TEST(HasAncenstor, MatchesDeclarationAncestors) {
3716 EXPECT_TRUE(matches(
3717 "class A { class B { class C {}; }; };",
3718 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
3719}
3720
3721TEST(HasAncenstor, FailsIfNoAncestorMatches) {
3722 EXPECT_TRUE(notMatches(
3723 "class A { class B { class C {}; }; };",
3724 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
3725}
3726
3727TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
3728 EXPECT_TRUE(matches(
3729 "class A { class B { void f() { C c; } class C {}; }; };",
3730 varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
3731 hasAncestor(recordDecl(hasName("A"))))))));
3732}
3733
3734TEST(HasAncenstor, MatchesStatementAncestors) {
3735 EXPECT_TRUE(matches(
3736 "void f() { if (true) { while (false) { 42; } } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003737 integerLiteral(equals(42), hasAncestor(ifStmt()))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003738}
3739
3740TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
3741 EXPECT_TRUE(matches(
3742 "void f() { if (true) { int x = 42; } }",
Daniel Jasper848cbe12012-09-18 13:09:13 +00003743 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003744}
3745
3746TEST(HasAncestor, BindsRecursiveCombinations) {
3747 EXPECT_TRUE(matchAndVerifyResultTrue(
3748 "class C { class D { class E { class F { int y; }; }; }; };",
3749 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003750 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003751}
3752
3753TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
3754 EXPECT_TRUE(matchAndVerifyResultTrue(
3755 "class C { class D { class E { class F { int y; }; }; }; };",
3756 fieldDecl(hasAncestor(
3757 decl(
3758 hasDescendant(recordDecl(isDefinition(),
3759 hasAncestor(recordDecl())))
3760 ).bind("d")
3761 )),
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00003762 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003763}
3764
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003765TEST(HasAncestor, MatchesClosestAncestor) {
3766 EXPECT_TRUE(matchAndVerifyResultTrue(
3767 "template <typename T> struct C {"
3768 " void f(int) {"
3769 " struct I { void g(T) { int x; } } i; i.g(42);"
3770 " }"
3771 "};"
3772 "template struct C<int>;",
3773 varDecl(hasName("x"),
3774 hasAncestor(functionDecl(hasParameter(
3775 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
3776 new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
3777}
3778
Manuel Klimek3ca12c52012-09-07 09:26:10 +00003779TEST(HasAncestor, MatchesInTemplateInstantiations) {
3780 EXPECT_TRUE(matches(
3781 "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
3782 "A<int>::B::C a;",
3783 fieldDecl(hasType(asString("int")),
3784 hasAncestor(recordDecl(hasName("A"))))));
3785}
3786
3787TEST(HasAncestor, MatchesInImplicitCode) {
3788 EXPECT_TRUE(matches(
3789 "struct X {}; struct A { A() {} X x; };",
3790 constructorDecl(
3791 hasAnyConstructorInitializer(withInitializer(expr(
3792 hasAncestor(recordDecl(hasName("A")))))))));
3793}
3794
Daniel Jasper632aea92012-10-22 16:26:51 +00003795TEST(HasParent, MatchesOnlyParent) {
3796 EXPECT_TRUE(matches(
3797 "void f() { if (true) { int x = 42; } }",
3798 compoundStmt(hasParent(ifStmt()))));
3799 EXPECT_TRUE(notMatches(
3800 "void f() { for (;;) { int x = 42; } }",
3801 compoundStmt(hasParent(ifStmt()))));
3802 EXPECT_TRUE(notMatches(
3803 "void f() { if (true) for (;;) { int x = 42; } }",
3804 compoundStmt(hasParent(ifStmt()))));
3805}
3806
Manuel Klimekc844a462012-12-06 14:42:48 +00003807TEST(HasAncestor, MatchesAllAncestors) {
3808 EXPECT_TRUE(matches(
3809 "template <typename T> struct C { static void f() { 42; } };"
3810 "void t() { C<int>::f(); }",
3811 integerLiteral(
3812 equals(42),
3813 allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
3814 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
3815}
3816
3817TEST(HasParent, MatchesAllParents) {
3818 EXPECT_TRUE(matches(
3819 "template <typename T> struct C { static void f() { 42; } };"
3820 "void t() { C<int>::f(); }",
3821 integerLiteral(
3822 equals(42),
3823 hasParent(compoundStmt(hasParent(functionDecl(
3824 hasParent(recordDecl(isTemplateInstantiation())))))))));
3825 EXPECT_TRUE(matches(
3826 "template <typename T> struct C { static void f() { 42; } };"
3827 "void t() { C<int>::f(); }",
3828 integerLiteral(
3829 equals(42),
3830 hasParent(compoundStmt(hasParent(functionDecl(
3831 hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
3832 EXPECT_TRUE(matches(
3833 "template <typename T> struct C { static void f() { 42; } };"
3834 "void t() { C<int>::f(); }",
3835 integerLiteral(equals(42),
3836 hasParent(compoundStmt(allOf(
3837 hasParent(functionDecl(
3838 hasParent(recordDecl(isTemplateInstantiation())))),
3839 hasParent(functionDecl(hasParent(recordDecl(
3840 unless(isTemplateInstantiation())))))))))));
Manuel Klimekb64d6b72013-03-14 16:33:21 +00003841 EXPECT_TRUE(
3842 notMatches("template <typename T> struct C { static void f() {} };"
3843 "void t() { C<int>::f(); }",
3844 compoundStmt(hasParent(recordDecl()))));
Manuel Klimekc844a462012-12-06 14:42:48 +00003845}
3846
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00003847TEST(HasParent, NoDuplicateParents) {
3848 class HasDuplicateParents : public BoundNodesCallback {
3849 public:
3850 bool run(const BoundNodes *Nodes) override { return false; }
3851 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
3852 const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
3853 std::set<const void *> Parents;
3854 for (const auto &Parent : Context->getParents(*Node)) {
3855 if (!Parents.insert(Parent.getMemoizationData()).second) {
3856 return true;
3857 }
3858 }
3859 return false;
3860 }
3861 };
3862 EXPECT_FALSE(matchAndVerifyResultTrue(
3863 "template <typename T> int Foo() { return 1 + 2; }\n"
3864 "int x = Foo<int>() + Foo<unsigned>();",
3865 stmt().bind("node"), new HasDuplicateParents()));
3866}
3867
Daniel Jasper516b02e2012-10-17 08:52:59 +00003868TEST(TypeMatching, MatchesTypes) {
3869 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
3870}
3871
Samuel Benzaquenb405c082014-12-15 15:09:22 +00003872TEST(TypeMatching, MatchesVoid) {
3873 EXPECT_TRUE(
3874 matches("struct S { void func(); };", methodDecl(returns(voidType()))));
3875}
3876
Daniel Jasper516b02e2012-10-17 08:52:59 +00003877TEST(TypeMatching, MatchesArrayTypes) {
3878 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
3879 EXPECT_TRUE(matches("int a[42];", arrayType()));
3880 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
3881
3882 EXPECT_TRUE(notMatches("struct A {}; A a[7];",
3883 arrayType(hasElementType(builtinType()))));
3884
3885 EXPECT_TRUE(matches(
3886 "int const a[] = { 2, 3 };",
3887 qualType(arrayType(hasElementType(builtinType())))));
3888 EXPECT_TRUE(matches(
3889 "int const a[] = { 2, 3 };",
3890 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3891 EXPECT_TRUE(matches(
3892 "typedef const int T; T x[] = { 1, 2 };",
3893 qualType(isConstQualified(), arrayType())));
3894
3895 EXPECT_TRUE(notMatches(
3896 "int a[] = { 2, 3 };",
3897 qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
3898 EXPECT_TRUE(notMatches(
3899 "int a[] = { 2, 3 };",
3900 qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
3901 EXPECT_TRUE(notMatches(
3902 "int const a[] = { 2, 3 };",
3903 qualType(arrayType(hasElementType(builtinType())),
3904 unless(isConstQualified()))));
3905
3906 EXPECT_TRUE(matches("int a[2];",
3907 constantArrayType(hasElementType(builtinType()))));
3908 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
3909}
3910
3911TEST(TypeMatching, MatchesComplexTypes) {
3912 EXPECT_TRUE(matches("_Complex float f;", complexType()));
3913 EXPECT_TRUE(matches(
3914 "_Complex float f;",
3915 complexType(hasElementType(builtinType()))));
3916 EXPECT_TRUE(notMatches(
3917 "_Complex float f;",
3918 complexType(hasElementType(isInteger()))));
3919}
3920
3921TEST(TypeMatching, MatchesConstantArrayTypes) {
3922 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
3923 EXPECT_TRUE(notMatches(
3924 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
3925 constantArrayType(hasElementType(builtinType()))));
3926
3927 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
3928 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
3929 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
3930}
3931
3932TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
3933 EXPECT_TRUE(matches(
3934 "template <typename T, int Size> class array { T data[Size]; };",
3935 dependentSizedArrayType()));
3936 EXPECT_TRUE(notMatches(
3937 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
3938 dependentSizedArrayType()));
3939}
3940
3941TEST(TypeMatching, MatchesIncompleteArrayType) {
3942 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
3943 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
3944
3945 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
3946 incompleteArrayType()));
3947}
3948
3949TEST(TypeMatching, MatchesVariableArrayType) {
3950 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
3951 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
3952
3953 EXPECT_TRUE(matches(
3954 "void f(int b) { int a[b]; }",
3955 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3956 varDecl(hasName("b")))))))));
3957}
3958
3959TEST(TypeMatching, MatchesAtomicTypes) {
David Majnemer197e2102014-03-05 06:32:38 +00003960 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
3961 llvm::Triple::Win32) {
3962 // FIXME: Make this work for MSVC.
3963 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003964
David Majnemer197e2102014-03-05 06:32:38 +00003965 EXPECT_TRUE(matches("_Atomic(int) i;",
3966 atomicType(hasValueType(isInteger()))));
3967 EXPECT_TRUE(notMatches("_Atomic(float) f;",
3968 atomicType(hasValueType(isInteger()))));
3969 }
Daniel Jasper516b02e2012-10-17 08:52:59 +00003970}
3971
3972TEST(TypeMatching, MatchesAutoTypes) {
3973 EXPECT_TRUE(matches("auto i = 2;", autoType()));
3974 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
3975 autoType()));
3976
Richard Smith061f1e22013-04-30 21:23:01 +00003977 // FIXME: Matching against the type-as-written can't work here, because the
3978 // type as written was not deduced.
3979 //EXPECT_TRUE(matches("auto a = 1;",
3980 // autoType(hasDeducedType(isInteger()))));
3981 //EXPECT_TRUE(notMatches("auto b = 2.0;",
3982 // autoType(hasDeducedType(isInteger()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00003983}
3984
Daniel Jasperd29d5fa2012-10-29 10:14:44 +00003985TEST(TypeMatching, MatchesFunctionTypes) {
3986 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
3987 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
3988}
3989
Edwin Vaneec074802013-04-01 18:33:34 +00003990TEST(TypeMatching, MatchesParenType) {
3991 EXPECT_TRUE(
3992 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
3993 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
3994
3995 EXPECT_TRUE(matches(
3996 "int (*ptr_to_func)(int);",
3997 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
3998 EXPECT_TRUE(notMatches(
3999 "int (*ptr_to_array)[4];",
4000 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
4001}
4002
Daniel Jasper516b02e2012-10-17 08:52:59 +00004003TEST(TypeMatching, PointerTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004004 // FIXME: Reactive when these tests can be more specific (not matching
4005 // implicit code on certain platforms), likely when we have hasDescendant for
4006 // Types/TypeLocs.
4007 //EXPECT_TRUE(matchAndVerifyResultTrue(
4008 // "int* a;",
4009 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
4010 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
4011 //EXPECT_TRUE(matchAndVerifyResultTrue(
4012 // "int* a;",
4013 // pointerTypeLoc().bind("loc"),
4014 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004015 EXPECT_TRUE(matches(
4016 "int** a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004017 loc(pointerType(pointee(qualType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004018 EXPECT_TRUE(matches(
4019 "int** a;",
4020 loc(pointerType(pointee(pointerType())))));
4021 EXPECT_TRUE(matches(
4022 "int* b; int* * const a = &b;",
4023 loc(qualType(isConstQualified(), pointerType()))));
4024
4025 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
Daniel Jasper7943eb52012-10-17 13:35:36 +00004026 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4027 hasType(blockPointerType()))));
4028 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4029 hasType(memberPointerType()))));
4030 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4031 hasType(pointerType()))));
4032 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4033 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004034 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4035 hasType(lValueReferenceType()))));
4036 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4037 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004038
Daniel Jasper7943eb52012-10-17 13:35:36 +00004039 Fragment = "int *ptr;";
4040 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4041 hasType(blockPointerType()))));
4042 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4043 hasType(memberPointerType()))));
4044 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
4045 hasType(pointerType()))));
4046 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
4047 hasType(referenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004048
Daniel Jasper7943eb52012-10-17 13:35:36 +00004049 Fragment = "int a; int &ref = a;";
4050 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4051 hasType(blockPointerType()))));
4052 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4053 hasType(memberPointerType()))));
4054 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4055 hasType(pointerType()))));
4056 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4057 hasType(referenceType()))));
Edwin Vane2a760d02013-03-07 15:44:40 +00004058 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4059 hasType(lValueReferenceType()))));
4060 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4061 hasType(rValueReferenceType()))));
4062
4063 Fragment = "int &&ref = 2;";
4064 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4065 hasType(blockPointerType()))));
4066 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4067 hasType(memberPointerType()))));
4068 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4069 hasType(pointerType()))));
4070 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4071 hasType(referenceType()))));
4072 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
4073 hasType(lValueReferenceType()))));
4074 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
4075 hasType(rValueReferenceType()))));
4076}
4077
4078TEST(TypeMatching, AutoRefTypes) {
4079 std::string Fragment = "auto a = 1;"
4080 "auto b = a;"
4081 "auto &c = a;"
4082 "auto &&d = c;"
4083 "auto &&e = 2;";
4084 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
4085 hasType(referenceType()))));
4086 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
4087 hasType(referenceType()))));
4088 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4089 hasType(referenceType()))));
4090 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
4091 hasType(lValueReferenceType()))));
4092 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
4093 hasType(rValueReferenceType()))));
4094 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4095 hasType(referenceType()))));
4096 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
4097 hasType(lValueReferenceType()))));
4098 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
4099 hasType(rValueReferenceType()))));
4100 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4101 hasType(referenceType()))));
4102 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
4103 hasType(lValueReferenceType()))));
4104 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
4105 hasType(rValueReferenceType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004106}
4107
4108TEST(TypeMatching, PointeeTypes) {
4109 EXPECT_TRUE(matches("int b; int &a = b;",
4110 referenceType(pointee(builtinType()))));
4111 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
4112
4113 EXPECT_TRUE(matches("int *a;",
David Blaikieb61d0872013-02-18 19:04:16 +00004114 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004115
4116 EXPECT_TRUE(matches(
4117 "int const *A;",
4118 pointerType(pointee(isConstQualified(), builtinType()))));
4119 EXPECT_TRUE(notMatches(
4120 "int *A;",
4121 pointerType(pointee(isConstQualified(), builtinType()))));
4122}
4123
4124TEST(TypeMatching, MatchesPointersToConstTypes) {
4125 EXPECT_TRUE(matches("int b; int * const a = &b;",
4126 loc(pointerType())));
4127 EXPECT_TRUE(matches("int b; int * const a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004128 loc(pointerType())));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004129 EXPECT_TRUE(matches(
4130 "int b; const int * a = &b;",
David Blaikieb61d0872013-02-18 19:04:16 +00004131 loc(pointerType(pointee(builtinType())))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004132 EXPECT_TRUE(matches(
4133 "int b; const int * a = &b;",
4134 pointerType(pointee(builtinType()))));
4135}
4136
4137TEST(TypeMatching, MatchesTypedefTypes) {
Daniel Jasper7943eb52012-10-17 13:35:36 +00004138 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
4139 hasType(typedefType()))));
Daniel Jasper516b02e2012-10-17 08:52:59 +00004140}
4141
Edwin Vanef901b712013-02-25 14:49:29 +00004142TEST(TypeMatching, MatchesTemplateSpecializationType) {
Edwin Vaneb6eae142013-02-25 20:43:32 +00004143 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
Edwin Vanef901b712013-02-25 14:49:29 +00004144 templateSpecializationType()));
4145}
4146
Edwin Vaneb6eae142013-02-25 20:43:32 +00004147TEST(TypeMatching, MatchesRecordType) {
4148 EXPECT_TRUE(matches("class C{}; C c;", recordType()));
Manuel Klimek59b0af62013-02-27 11:56:58 +00004149 EXPECT_TRUE(matches("struct S{}; S s;",
4150 recordType(hasDeclaration(recordDecl(hasName("S"))))));
4151 EXPECT_TRUE(notMatches("int i;",
4152 recordType(hasDeclaration(recordDecl(hasName("S"))))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004153}
4154
4155TEST(TypeMatching, MatchesElaboratedType) {
4156 EXPECT_TRUE(matches(
4157 "namespace N {"
4158 " namespace M {"
4159 " class D {};"
4160 " }"
4161 "}"
4162 "N::M::D d;", elaboratedType()));
4163 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
4164 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
4165}
4166
4167TEST(ElaboratedTypeNarrowing, hasQualifier) {
4168 EXPECT_TRUE(matches(
4169 "namespace N {"
4170 " namespace M {"
4171 " class D {};"
4172 " }"
4173 "}"
4174 "N::M::D d;",
4175 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
4176 EXPECT_TRUE(notMatches(
4177 "namespace M {"
4178 " class D {};"
4179 "}"
4180 "M::D d;",
4181 elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
Edwin Vane6972f6d2013-03-04 17:51:00 +00004182 EXPECT_TRUE(notMatches(
4183 "struct D {"
4184 "} d;",
4185 elaboratedType(hasQualifier(nestedNameSpecifier()))));
Edwin Vaneb6eae142013-02-25 20:43:32 +00004186}
4187
4188TEST(ElaboratedTypeNarrowing, namesType) {
4189 EXPECT_TRUE(matches(
4190 "namespace N {"
4191 " namespace M {"
4192 " class D {};"
4193 " }"
4194 "}"
4195 "N::M::D d;",
4196 elaboratedType(elaboratedType(namesType(recordType(
4197 hasDeclaration(namedDecl(hasName("D")))))))));
4198 EXPECT_TRUE(notMatches(
4199 "namespace M {"
4200 " class D {};"
4201 "}"
4202 "M::D d;",
4203 elaboratedType(elaboratedType(namesType(typedefType())))));
4204}
4205
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004206TEST(NNS, MatchesNestedNameSpecifiers) {
4207 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
4208 nestedNameSpecifier()));
4209 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
4210 nestedNameSpecifier()));
4211 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
4212 nestedNameSpecifier()));
4213
4214 EXPECT_TRUE(matches(
4215 "struct A { static void f() {} }; void g() { A::f(); }",
4216 nestedNameSpecifier()));
4217 EXPECT_TRUE(notMatches(
4218 "struct A { static void f() {} }; void g(A* a) { a->f(); }",
4219 nestedNameSpecifier()));
4220}
4221
Daniel Jasper87c3d362012-09-20 14:12:57 +00004222TEST(NullStatement, SimpleCases) {
4223 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
4224 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
4225}
4226
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004227TEST(NNS, MatchesTypes) {
4228 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4229 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
4230 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
4231 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
4232 Matcher));
4233 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
4234}
4235
4236TEST(NNS, MatchesNamespaceDecls) {
4237 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
4238 specifiesNamespace(hasName("ns")));
4239 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
4240 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
4241 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
4242}
4243
4244TEST(NNS, BindsNestedNameSpecifiers) {
4245 EXPECT_TRUE(matchAndVerifyResultTrue(
4246 "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
4247 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
4248 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
4249}
4250
4251TEST(NNS, BindsNestedNameSpecifierLocs) {
4252 EXPECT_TRUE(matchAndVerifyResultTrue(
4253 "namespace ns { struct B {}; } ns::B b;",
4254 loc(nestedNameSpecifier()).bind("loc"),
4255 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
4256}
4257
4258TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
4259 EXPECT_TRUE(matches(
4260 "struct A { struct B { struct C {}; }; }; A::B::C c;",
4261 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
4262 EXPECT_TRUE(matches(
4263 "struct A { struct B { struct C {}; }; }; A::B::C c;",
Daniel Jasper516b02e2012-10-17 08:52:59 +00004264 nestedNameSpecifierLoc(hasPrefix(
4265 specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
Daniel Jaspera6bc1f62012-09-13 13:11:25 +00004266}
4267
Daniel Jasper6fc34332012-10-30 15:42:00 +00004268TEST(NNS, DescendantsOfNestedNameSpecifiers) {
4269 std::string Fragment =
4270 "namespace a { struct A { struct B { struct C {}; }; }; };"
4271 "void f() { a::A::B::C c; }";
4272 EXPECT_TRUE(matches(
4273 Fragment,
4274 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4275 hasDescendant(nestedNameSpecifier(
4276 specifiesNamespace(hasName("a")))))));
4277 EXPECT_TRUE(notMatches(
4278 Fragment,
4279 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4280 has(nestedNameSpecifier(
4281 specifiesNamespace(hasName("a")))))));
4282 EXPECT_TRUE(matches(
4283 Fragment,
4284 nestedNameSpecifier(specifiesType(asString("struct a::A")),
4285 has(nestedNameSpecifier(
4286 specifiesNamespace(hasName("a")))))));
4287
4288 // Not really useful because a NestedNameSpecifier can af at most one child,
4289 // but to complete the interface.
4290 EXPECT_TRUE(matchAndVerifyResultTrue(
4291 Fragment,
4292 nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
4293 forEach(nestedNameSpecifier().bind("x"))),
4294 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
4295}
4296
4297TEST(NNS, NestedNameSpecifiersAsDescendants) {
4298 std::string Fragment =
4299 "namespace a { struct A { struct B { struct C {}; }; }; };"
4300 "void f() { a::A::B::C c; }";
4301 EXPECT_TRUE(matches(
4302 Fragment,
4303 decl(hasDescendant(nestedNameSpecifier(specifiesType(
4304 asString("struct a::A")))))));
4305 EXPECT_TRUE(matchAndVerifyResultTrue(
4306 Fragment,
4307 functionDecl(hasName("f"),
4308 forEachDescendant(nestedNameSpecifier().bind("x"))),
4309 // Nested names: a, a::A and a::A::B.
4310 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
4311}
4312
4313TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
4314 std::string Fragment =
4315 "namespace a { struct A { struct B { struct C {}; }; }; };"
4316 "void f() { a::A::B::C c; }";
4317 EXPECT_TRUE(matches(
4318 Fragment,
4319 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4320 hasDescendant(loc(nestedNameSpecifier(
4321 specifiesNamespace(hasName("a"))))))));
4322 EXPECT_TRUE(notMatches(
4323 Fragment,
4324 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4325 has(loc(nestedNameSpecifier(
4326 specifiesNamespace(hasName("a"))))))));
4327 EXPECT_TRUE(matches(
4328 Fragment,
4329 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
4330 has(loc(nestedNameSpecifier(
4331 specifiesNamespace(hasName("a"))))))));
4332
4333 EXPECT_TRUE(matchAndVerifyResultTrue(
4334 Fragment,
4335 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
4336 forEach(nestedNameSpecifierLoc().bind("x"))),
4337 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
4338}
4339
4340TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
4341 std::string Fragment =
4342 "namespace a { struct A { struct B { struct C {}; }; }; };"
4343 "void f() { a::A::B::C c; }";
4344 EXPECT_TRUE(matches(
4345 Fragment,
4346 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
4347 asString("struct a::A"))))))));
4348 EXPECT_TRUE(matchAndVerifyResultTrue(
4349 Fragment,
4350 functionDecl(hasName("f"),
4351 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
4352 // Nested names: a, a::A and a::A::B.
4353 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
4354}
4355
Manuel Klimek191c0932013-02-01 13:41:35 +00004356template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
Manuel Klimekc2687452012-10-24 14:47:44 +00004357public:
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004358 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
4359 StringRef InnerId)
4360 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
Daniel Jaspere9aa6872012-10-29 10:48:25 +00004361 }
4362
Manuel Klimek191c0932013-02-01 13:41:35 +00004363 virtual bool run(const BoundNodes *Nodes) { return false; }
4364
Manuel Klimekc2687452012-10-24 14:47:44 +00004365 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4366 const T *Node = Nodes->getNodeAs<T>(Id);
Benjamin Kramer76645582014-07-23 11:41:44 +00004367 return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
4368 nullptr;
Manuel Klimekc2687452012-10-24 14:47:44 +00004369 }
4370private:
4371 std::string Id;
4372 internal::Matcher<T> InnerMatcher;
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004373 std::string InnerId;
Manuel Klimekc2687452012-10-24 14:47:44 +00004374};
4375
4376TEST(MatchFinder, CanMatchDeclarationsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004377 EXPECT_TRUE(matchAndVerifyResultTrue(
4378 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4379 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004380 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
4381 "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004382 EXPECT_TRUE(matchAndVerifyResultFalse(
4383 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4384 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004385 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
4386 "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004387}
4388
4389TEST(MatchFinder, CanMatchStatementsRecursively) {
Manuel Klimek191c0932013-02-01 13:41:35 +00004390 EXPECT_TRUE(matchAndVerifyResultTrue(
4391 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004392 new VerifyMatchOnNode<clang::Stmt>(
4393 "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004394 EXPECT_TRUE(matchAndVerifyResultFalse(
4395 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004396 new VerifyMatchOnNode<clang::Stmt>(
4397 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004398}
4399
4400TEST(MatchFinder, CanMatchSingleNodesRecursively) {
4401 EXPECT_TRUE(matchAndVerifyResultTrue(
4402 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4403 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004404 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
Manuel Klimek191c0932013-02-01 13:41:35 +00004405 EXPECT_TRUE(matchAndVerifyResultFalse(
4406 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
4407 new VerifyMatchOnNode<clang::Decl>(
Manuel Klimek2cff49e2013-02-06 10:33:21 +00004408 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
Manuel Klimekc2687452012-10-24 14:47:44 +00004409}
4410
Manuel Klimekbee08572013-02-07 12:42:10 +00004411template <typename T>
4412class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
4413public:
4414 virtual bool run(const BoundNodes *Nodes) { return false; }
4415
4416 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
4417 const T *Node = Nodes->getNodeAs<T>("");
4418 return verify(*Nodes, *Context, Node);
4419 }
4420
4421 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004422 // Use the original typed pointer to verify we can pass pointers to subtypes
4423 // to equalsNode.
4424 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004425 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004426 "", match(stmt(hasParent(
4427 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004428 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004429 }
4430 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004431 // Use the original typed pointer to verify we can pass pointers to subtypes
4432 // to equalsNode.
4433 const T *TypedNode = cast<T>(Node);
Benjamin Kramer76645582014-07-23 11:41:44 +00004434 return selectFirst<T>(
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004435 "", match(decl(hasParent(
4436 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
Craig Topper416fa342014-06-08 08:38:12 +00004437 *Node, Context)) != nullptr;
Manuel Klimekbee08572013-02-07 12:42:10 +00004438 }
4439};
4440
4441TEST(IsEqualTo, MatchesNodesByIdentity) {
4442 EXPECT_TRUE(matchAndVerifyResultTrue(
4443 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
Manuel Klimeka2c2a4f2014-05-27 12:31:10 +00004444 new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
4445 EXPECT_TRUE(matchAndVerifyResultTrue(
4446 "void f() { if (true) if(true) {} }", ifStmt().bind(""),
4447 new VerifyAncestorHasChildIsEqual<IfStmt>()));
Manuel Klimekbee08572013-02-07 12:42:10 +00004448}
4449
Samuel Benzaquen43dcf212014-10-22 20:31:05 +00004450TEST(MatchFinder, CheckProfiling) {
4451 MatchFinder::MatchFinderOptions Options;
4452 llvm::StringMap<llvm::TimeRecord> Records;
4453 Options.CheckProfiling.emplace(Records);
4454 MatchFinder Finder(std::move(Options));
4455
4456 struct NamedCallback : public MatchFinder::MatchCallback {
4457 void run(const MatchFinder::MatchResult &Result) override {}
4458 StringRef getID() const override { return "MyID"; }
4459 } Callback;
4460 Finder.addMatcher(decl(), &Callback);
4461 std::unique_ptr<FrontendActionFactory> Factory(
4462 newFrontendActionFactory(&Finder));
4463 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4464
4465 EXPECT_EQ(1u, Records.size());
4466 EXPECT_EQ("MyID", Records.begin()->getKey());
4467}
4468
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004469class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
4470public:
4471 VerifyStartOfTranslationUnit() : Called(false) {}
4472 virtual void run(const MatchFinder::MatchResult &Result) {
4473 EXPECT_TRUE(Called);
4474 }
4475 virtual void onStartOfTranslationUnit() {
4476 Called = true;
4477 }
4478 bool Called;
4479};
4480
4481TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
4482 MatchFinder Finder;
4483 VerifyStartOfTranslationUnit VerifyCallback;
4484 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004485 std::unique_ptr<FrontendActionFactory> Factory(
4486 newFrontendActionFactory(&Finder));
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004487 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4488 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004489
4490 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004491 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004492 ASSERT_TRUE(AST.get());
4493 Finder.matchAST(AST->getASTContext());
4494 EXPECT_TRUE(VerifyCallback.Called);
Manuel Klimekbd0e2b72012-11-02 01:31:03 +00004495}
4496
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004497class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
4498public:
4499 VerifyEndOfTranslationUnit() : Called(false) {}
4500 virtual void run(const MatchFinder::MatchResult &Result) {
4501 EXPECT_FALSE(Called);
4502 }
4503 virtual void onEndOfTranslationUnit() {
4504 Called = true;
4505 }
4506 bool Called;
4507};
4508
4509TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
4510 MatchFinder Finder;
4511 VerifyEndOfTranslationUnit VerifyCallback;
4512 Finder.addMatcher(decl(), &VerifyCallback);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004513 std::unique_ptr<FrontendActionFactory> Factory(
4514 newFrontendActionFactory(&Finder));
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004515 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
4516 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbournea2334162013-11-07 22:30:36 +00004517
4518 VerifyCallback.Called = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004519 std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
Peter Collingbournea2334162013-11-07 22:30:36 +00004520 ASSERT_TRUE(AST.get());
4521 Finder.matchAST(AST->getASTContext());
4522 EXPECT_TRUE(VerifyCallback.Called);
Peter Collingbourne6a55bb22013-05-28 19:21:51 +00004523}
4524
Manuel Klimekbbb75852013-06-20 14:06:32 +00004525TEST(EqualsBoundNodeMatcher, QualType) {
4526 EXPECT_TRUE(matches(
4527 "int i = 1;", varDecl(hasType(qualType().bind("type")),
4528 hasInitializer(ignoringParenImpCasts(
4529 hasType(qualType(equalsBoundNode("type"))))))));
4530 EXPECT_TRUE(notMatches("int i = 1.f;",
4531 varDecl(hasType(qualType().bind("type")),
4532 hasInitializer(ignoringParenImpCasts(hasType(
4533 qualType(equalsBoundNode("type"))))))));
4534}
4535
4536TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
4537 EXPECT_TRUE(notMatches(
4538 "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
4539 hasInitializer(ignoringParenImpCasts(
4540 hasType(qualType(equalsBoundNode("type"))))))));
4541}
4542
4543TEST(EqualsBoundNodeMatcher, Stmt) {
4544 EXPECT_TRUE(
4545 matches("void f() { if(true) {} }",
4546 stmt(allOf(ifStmt().bind("if"),
4547 hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
4548
4549 EXPECT_TRUE(notMatches(
4550 "void f() { if(true) { if (true) {} } }",
4551 stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
4552}
4553
4554TEST(EqualsBoundNodeMatcher, Decl) {
4555 EXPECT_TRUE(matches(
4556 "class X { class Y {}; };",
4557 decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
4558 hasParent(decl(has(decl(equalsBoundNode("record")))))))));
4559
4560 EXPECT_TRUE(notMatches("class X { class Y {}; };",
4561 decl(allOf(recordDecl(hasName("::X")).bind("record"),
4562 has(decl(equalsBoundNode("record")))))));
4563}
4564
4565TEST(EqualsBoundNodeMatcher, Type) {
4566 EXPECT_TRUE(matches(
4567 "class X { int a; int b; };",
4568 recordDecl(
4569 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4570 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4571
4572 EXPECT_TRUE(notMatches(
4573 "class X { int a; double b; };",
4574 recordDecl(
4575 has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4576 has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
4577}
4578
4579TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
Manuel Klimekbbb75852013-06-20 14:06:32 +00004580 EXPECT_TRUE(matchAndVerifyResultTrue(
4581 "int f() {"
4582 " if (1) {"
4583 " int i = 9;"
4584 " }"
4585 " int j = 10;"
4586 " {"
4587 " float k = 9.0;"
4588 " }"
4589 " return 0;"
4590 "}",
4591 // Look for variable declarations within functions whose type is the same
4592 // as the function return type.
4593 functionDecl(returns(qualType().bind("type")),
4594 forEachDescendant(varDecl(hasType(
4595 qualType(equalsBoundNode("type")))).bind("decl"))),
4596 // Only i and j should match, not k.
4597 new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
4598}
4599
4600TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
4601 EXPECT_TRUE(matchAndVerifyResultTrue(
4602 "void f() {"
4603 " int x;"
4604 " double d;"
4605 " x = d + x - d + x;"
4606 "}",
4607 functionDecl(
4608 hasName("f"), forEachDescendant(varDecl().bind("d")),
4609 forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
4610 new VerifyIdIsBoundTo<VarDecl>("d", 5)));
4611}
4612
Manuel Klimekce68f772014-03-25 14:39:26 +00004613TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
4614 EXPECT_TRUE(matchAndVerifyResultTrue(
4615 "struct StringRef { int size() const; const char* data() const; };"
4616 "void f(StringRef v) {"
4617 " v.data();"
4618 "}",
4619 memberCallExpr(
4620 callee(methodDecl(hasName("data"))),
4621 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4622 .bind("var")))),
4623 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4624 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4625 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4626 .bind("data"),
4627 new VerifyIdIsBoundTo<Expr>("data", 1)));
4628
4629 EXPECT_FALSE(matches(
4630 "struct StringRef { int size() const; const char* data() const; };"
4631 "void f(StringRef v) {"
4632 " v.data();"
4633 " v.size();"
4634 "}",
4635 memberCallExpr(
4636 callee(methodDecl(hasName("data"))),
4637 on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
4638 .bind("var")))),
4639 unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
4640 callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
4641 on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
4642 .bind("data")));
4643}
4644
Manuel Klimekd3aa1f42014-11-25 17:01:06 +00004645TEST(TypeDefDeclMatcher, Match) {
4646 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
4647 typedefDecl(hasName("typedefDeclTest"))));
4648}
4649
4650// FIXME: Figure out how to specify paths so the following tests pass on Windows.
4651#ifndef LLVM_ON_WIN32
4652
4653TEST(Matcher, IsExpansionInMainFileMatcher) {
4654 EXPECT_TRUE(matches("class X {};",
4655 recordDecl(hasName("X"), isExpansionInMainFile())));
4656 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
4657 FileContentMappings M;
4658 M.push_back(std::make_pair("/other", "class X {};"));
4659 EXPECT_TRUE(matchesConditionally("#include <other>\n",
4660 recordDecl(isExpansionInMainFile()), false,
4661 "-isystem/", M));
4662}
4663
4664TEST(Matcher, IsExpansionInSystemHeader) {
4665 FileContentMappings M;
4666 M.push_back(std::make_pair("/other", "class X {};"));
4667 EXPECT_TRUE(matchesConditionally(
4668 "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
4669 "-isystem/", M));
4670 EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
4671 recordDecl(isExpansionInSystemHeader()),
4672 false, "-I/", M));
4673 EXPECT_TRUE(notMatches("class X {};",
4674 recordDecl(isExpansionInSystemHeader())));
4675 EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
4676}
4677
4678TEST(Matcher, IsExpansionInFileMatching) {
4679 FileContentMappings M;
4680 M.push_back(std::make_pair("/foo", "class A {};"));
4681 M.push_back(std::make_pair("/bar", "class B {};"));
4682 EXPECT_TRUE(matchesConditionally(
4683 "#include <foo>\n"
4684 "#include <bar>\n"
4685 "class X {};",
4686 recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
4687 "-isystem/", M));
4688 EXPECT_TRUE(matchesConditionally(
4689 "#include <foo>\n"
4690 "#include <bar>\n"
4691 "class X {};",
4692 recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
4693 "-isystem/", M));
4694}
4695
4696#endif // LLVM_ON_WIN32
4697
Manuel Klimek04616e42012-07-06 05:48:52 +00004698} // end namespace ast_matchers
4699} // end namespace clang