1 // unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp - AST matcher unit tests//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ASTMatchersTest.h"
10 #include "clang/AST/PrettyPrinter.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Tooling/Tooling.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Support/Host.h"
16 #include "gtest/gtest.h"
17 
18 namespace clang {
19 namespace ast_matchers {
20 
21 
TEST(AllOf,AllOverloadsWork)22 TEST(AllOf, AllOverloadsWork) {
23   const char Program[] =
24       "struct T { };"
25       "int f(int, T*, int, int);"
26       "void g(int x) { T t; f(x, &t, 3, 4); }";
27   EXPECT_TRUE(matches(Program,
28       callExpr(allOf(callee(functionDecl(hasName("f"))),
29                      hasArgument(0, declRefExpr(to(varDecl())))))));
30   EXPECT_TRUE(matches(Program,
31       callExpr(allOf(callee(functionDecl(hasName("f"))),
32                      hasArgument(0, declRefExpr(to(varDecl()))),
33                      hasArgument(1, hasType(pointsTo(
34                                         recordDecl(hasName("T")))))))));
35   EXPECT_TRUE(matches(Program,
36       callExpr(allOf(callee(functionDecl(hasName("f"))),
37                      hasArgument(0, declRefExpr(to(varDecl()))),
38                      hasArgument(1, hasType(pointsTo(
39                                         recordDecl(hasName("T"))))),
40                      hasArgument(2, integerLiteral(equals(3)))))));
41   EXPECT_TRUE(matches(Program,
42       callExpr(allOf(callee(functionDecl(hasName("f"))),
43                      hasArgument(0, declRefExpr(to(varDecl()))),
44                      hasArgument(1, hasType(pointsTo(
45                                         recordDecl(hasName("T"))))),
46                      hasArgument(2, integerLiteral(equals(3))),
47                      hasArgument(3, integerLiteral(equals(4)))))));
48 }
49 
TEST(DeclarationMatcher,MatchHas)50 TEST(DeclarationMatcher, MatchHas) {
51   DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
52   EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
53   EXPECT_TRUE(matches("class X {};", HasClassX));
54 
55   DeclarationMatcher YHasClassX =
56     recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
57   EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
58   EXPECT_TRUE(notMatches("class X {};", YHasClassX));
59   EXPECT_TRUE(
60     notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
61 }
62 
TEST(DeclarationMatcher,MatchHasRecursiveAllOf)63 TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
64   DeclarationMatcher Recursive =
65     recordDecl(
66       has(recordDecl(
67         has(recordDecl(hasName("X"))),
68         has(recordDecl(hasName("Y"))),
69         hasName("Z"))),
70       has(recordDecl(
71         has(recordDecl(hasName("A"))),
72         has(recordDecl(hasName("B"))),
73         hasName("C"))),
74       hasName("F"));
75 
76   EXPECT_TRUE(matches(
77     "class F {"
78       "  class Z {"
79       "    class X {};"
80       "    class Y {};"
81       "  };"
82       "  class C {"
83       "    class A {};"
84       "    class B {};"
85       "  };"
86       "};", Recursive));
87 
88   EXPECT_TRUE(matches(
89     "class F {"
90       "  class Z {"
91       "    class A {};"
92       "    class X {};"
93       "    class Y {};"
94       "  };"
95       "  class C {"
96       "    class X {};"
97       "    class A {};"
98       "    class B {};"
99       "  };"
100       "};", Recursive));
101 
102   EXPECT_TRUE(matches(
103     "class O1 {"
104       "  class O2 {"
105       "    class F {"
106       "      class Z {"
107       "        class A {};"
108       "        class X {};"
109       "        class Y {};"
110       "      };"
111       "      class C {"
112       "        class X {};"
113       "        class A {};"
114       "        class B {};"
115       "      };"
116       "    };"
117       "  };"
118       "};", Recursive));
119 }
120 
TEST(DeclarationMatcher,MatchHasRecursiveAnyOf)121 TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
122   DeclarationMatcher Recursive =
123     recordDecl(
124       anyOf(
125         has(recordDecl(
126           anyOf(
127             has(recordDecl(
128               hasName("X"))),
129             has(recordDecl(
130               hasName("Y"))),
131             hasName("Z")))),
132         has(recordDecl(
133           anyOf(
134             hasName("C"),
135             has(recordDecl(
136               hasName("A"))),
137             has(recordDecl(
138               hasName("B")))))),
139         hasName("F")));
140 
141   EXPECT_TRUE(matches("class F {};", Recursive));
142   EXPECT_TRUE(matches("class Z {};", Recursive));
143   EXPECT_TRUE(matches("class C {};", Recursive));
144   EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
145   EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
146   EXPECT_TRUE(
147     matches("class O1 { class O2 {"
148               "  class M { class N { class B {}; }; }; "
149               "}; };", Recursive));
150 }
151 
TEST(DeclarationMatcher,MatchNot)152 TEST(DeclarationMatcher, MatchNot) {
153   DeclarationMatcher NotClassX =
154     cxxRecordDecl(
155       isDerivedFrom("Y"),
156       unless(hasName("X")));
157   EXPECT_TRUE(notMatches("", NotClassX));
158   EXPECT_TRUE(notMatches("class Y {};", NotClassX));
159   EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
160   EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
161   EXPECT_TRUE(
162     notMatches("class Y {}; class Z {}; class X : public Y {};",
163                NotClassX));
164 
165   DeclarationMatcher ClassXHasNotClassY =
166     recordDecl(
167       hasName("X"),
168       has(recordDecl(hasName("Z"))),
169       unless(
170         has(recordDecl(hasName("Y")))));
171   EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
172   EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
173                          ClassXHasNotClassY));
174 
175   DeclarationMatcher NamedNotRecord =
176     namedDecl(hasName("Foo"), unless(recordDecl()));
177   EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
178   EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
179 }
180 
TEST(CastExpression,HasCastKind)181 TEST(CastExpression, HasCastKind) {
182   EXPECT_TRUE(matches("char *p = 0;",
183               castExpr(hasCastKind(CK_NullToPointer))));
184   EXPECT_TRUE(notMatches("char *p = 0;",
185               castExpr(hasCastKind(CK_DerivedToBase))));
186   EXPECT_TRUE(matches("char *p = 0;",
187               implicitCastExpr(hasCastKind(CK_NullToPointer))));
188 }
189 
TEST(DeclarationMatcher,HasDescendant)190 TEST(DeclarationMatcher, HasDescendant) {
191   DeclarationMatcher ZDescendantClassX =
192     recordDecl(
193       hasDescendant(recordDecl(hasName("X"))),
194       hasName("Z"));
195   EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
196   EXPECT_TRUE(
197     matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
198   EXPECT_TRUE(
199     matches("class Z { class A { class Y { class X {}; }; }; };",
200             ZDescendantClassX));
201   EXPECT_TRUE(
202     matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
203             ZDescendantClassX));
204   EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
205 
206   DeclarationMatcher ZDescendantClassXHasClassY =
207     recordDecl(
208       hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
209                                hasName("X"))),
210       hasName("Z"));
211   EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
212                       ZDescendantClassXHasClassY));
213   EXPECT_TRUE(
214     matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
215             ZDescendantClassXHasClassY));
216   EXPECT_TRUE(notMatches(
217     "class Z {"
218       "  class A {"
219       "    class B {"
220       "      class X {"
221       "        class C {"
222       "          class Y {};"
223       "        };"
224       "      };"
225       "    }; "
226       "  };"
227       "};", ZDescendantClassXHasClassY));
228 
229   DeclarationMatcher ZDescendantClassXDescendantClassY =
230     recordDecl(
231       hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
232                                hasName("X"))),
233       hasName("Z"));
234   EXPECT_TRUE(
235     matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
236             ZDescendantClassXDescendantClassY));
237   EXPECT_TRUE(matches(
238     "class Z {"
239       "  class A {"
240       "    class X {"
241       "      class B {"
242       "        class Y {};"
243       "      };"
244       "      class Y {};"
245       "    };"
246       "  };"
247       "};", ZDescendantClassXDescendantClassY));
248 }
249 
TEST(DeclarationMatcher,HasDescendantMemoization)250 TEST(DeclarationMatcher, HasDescendantMemoization) {
251   DeclarationMatcher CannotMemoize =
252     decl(hasDescendant(typeLoc().bind("x")), has(decl()));
253   EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
254 }
255 
TEST(DeclarationMatcher,HasDescendantMemoizationUsesRestrictKind)256 TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
257   auto Name = hasName("i");
258   auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
259   auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
260   // Matching VD first should not make a cache hit for RD.
261   EXPECT_TRUE(notMatches("void f() { int i; }",
262                          decl(hasDescendant(VD), hasDescendant(RD))));
263   EXPECT_TRUE(notMatches("void f() { int i; }",
264                          decl(hasDescendant(RD), hasDescendant(VD))));
265   // Not matching RD first should not make a cache hit for VD either.
266   EXPECT_TRUE(matches("void f() { int i; }",
267                       decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
268 }
269 
TEST(DeclarationMatcher,HasAncestorMemoization)270 TEST(DeclarationMatcher, HasAncestorMemoization) {
271   // This triggers an hasAncestor with a TemplateArgument in the bound nodes.
272   // That node can't be memoized so we have to check for it before trying to put
273   // it on the cache.
274   DeclarationMatcher CannotMemoize = classTemplateSpecializationDecl(
275     hasAnyTemplateArgument(templateArgument().bind("targ")),
276     forEach(fieldDecl(hasAncestor(forStmt()))));
277 
278   EXPECT_TRUE(notMatches("template <typename T> struct S;"
279                            "template <> struct S<int>{ int i; int j; };",
280                          CannotMemoize));
281 }
282 
TEST(DeclarationMatcher,HasAttr)283 TEST(DeclarationMatcher, HasAttr) {
284   EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
285                       decl(hasAttr(clang::attr::WarnUnused))));
286   EXPECT_FALSE(matches("struct X {};",
287                        decl(hasAttr(clang::attr::WarnUnused))));
288 }
289 
290 
TEST(DeclarationMatcher,MatchAnyOf)291 TEST(DeclarationMatcher, MatchAnyOf) {
292   DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
293     anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
294   EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
295   EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
296   EXPECT_TRUE(
297     notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
298   EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
299 
300   DeclarationMatcher XOrYOrZOrU =
301     recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
302   EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
303   EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
304 
305   DeclarationMatcher XOrYOrZOrUOrV =
306     recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
307                      hasName("V")));
308   EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
309   EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
310   EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
311   EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
312   EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
313   EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
314 
315   StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
316   EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
317   EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
318   EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
319 
320   EXPECT_TRUE(
321     matches("void f() try { } catch (int) { } catch (...) { }",
322             cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
323 }
324 
TEST(DeclarationMatcher,ClassIsDerived)325 TEST(DeclarationMatcher, ClassIsDerived) {
326   DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
327 
328   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
329   EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
330   EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
331   EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
332   EXPECT_TRUE(notMatches("", IsDerivedFromX));
333 
334   DeclarationMatcher IsDirectlyDerivedFromX =
335       cxxRecordDecl(isDirectlyDerivedFrom("X"));
336 
337   EXPECT_TRUE(
338       matches("class X {}; class Y : public X {};", IsDirectlyDerivedFromX));
339   EXPECT_TRUE(notMatches("class X {};", IsDirectlyDerivedFromX));
340   EXPECT_TRUE(notMatches("class X;", IsDirectlyDerivedFromX));
341   EXPECT_TRUE(notMatches("class Y;", IsDirectlyDerivedFromX));
342   EXPECT_TRUE(notMatches("", IsDirectlyDerivedFromX));
343 
344   DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
345 
346   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
347   EXPECT_TRUE(matches("class X {};", IsAX));
348   EXPECT_TRUE(matches("class X;", IsAX));
349   EXPECT_TRUE(notMatches("class Y;", IsAX));
350   EXPECT_TRUE(notMatches("", IsAX));
351 
352   DeclarationMatcher ZIsDerivedFromX =
353     cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
354   DeclarationMatcher ZIsDirectlyDerivedFromX =
355       cxxRecordDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
356   EXPECT_TRUE(
357     matches("class X {}; class Y : public X {}; class Z : public Y {};",
358             ZIsDerivedFromX));
359   EXPECT_TRUE(
360       notMatches("class X {}; class Y : public X {}; class Z : public Y {};",
361                  ZIsDirectlyDerivedFromX));
362   EXPECT_TRUE(
363     matches("class X {};"
364               "template<class T> class Y : public X {};"
365               "class Z : public Y<int> {};", ZIsDerivedFromX));
366   EXPECT_TRUE(notMatches("class X {};"
367                          "template<class T> class Y : public X {};"
368                          "class Z : public Y<int> {};",
369                          ZIsDirectlyDerivedFromX));
370   EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
371                       ZIsDerivedFromX));
372   EXPECT_TRUE(
373     matches("template<class T> class X {}; "
374               "template<class T> class Z : public X<T> {};",
375             ZIsDerivedFromX));
376   EXPECT_TRUE(
377     matches("template<class T, class U=T> class X {}; "
378               "template<class T> class Z : public X<T> {};",
379             ZIsDerivedFromX));
380   EXPECT_TRUE(
381     notMatches("template<class X> class A { class Z : public X {}; };",
382                ZIsDerivedFromX));
383   EXPECT_TRUE(
384     matches("template<class X> class A { public: class Z : public X {}; }; "
385               "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
386   EXPECT_TRUE(
387     matches("template <class T> class X {}; "
388               "template<class Y> class A { class Z : public X<Y> {}; };",
389             ZIsDerivedFromX));
390   EXPECT_TRUE(
391     notMatches("template<template<class T> class X> class A { "
392                  "  class Z : public X<int> {}; };", ZIsDerivedFromX));
393   EXPECT_TRUE(
394     matches("template<template<class T> class X> class A { "
395               "  public: class Z : public X<int> {}; }; "
396               "template<class T> class X {}; void y() { A<X>::Z z; }",
397             ZIsDerivedFromX));
398   EXPECT_TRUE(
399     notMatches("template<class X> class A { class Z : public X::D {}; };",
400                ZIsDerivedFromX));
401   EXPECT_TRUE(
402     matches("template<class X> class A { public: "
403               "  class Z : public X::D {}; }; "
404               "class Y { public: class X {}; typedef X D; }; "
405               "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
406   EXPECT_TRUE(
407     matches("class X {}; typedef X Y; class Z : public Y {};",
408             ZIsDerivedFromX));
409   EXPECT_TRUE(
410     matches("template<class T> class Y { typedef typename T::U X; "
411               "  class Z : public X {}; };", ZIsDerivedFromX));
412   EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
413                       ZIsDerivedFromX));
414   EXPECT_TRUE(
415     notMatches("template<class T> class X {}; "
416                  "template<class T> class A { class Z : public X<T>::D {}; };",
417                ZIsDerivedFromX));
418   EXPECT_TRUE(
419     matches("template<class T> class X { public: typedef X<T> D; }; "
420               "template<class T> class A { public: "
421               "  class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
422             ZIsDerivedFromX));
423   EXPECT_TRUE(
424     notMatches("template<class X> class A { class Z : public X::D::E {}; };",
425                ZIsDerivedFromX));
426   EXPECT_TRUE(
427     matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
428             ZIsDerivedFromX));
429   EXPECT_TRUE(
430     matches("class X {}; class Y : public X {}; "
431               "typedef Y V; typedef V W; class Z : public W {};",
432             ZIsDerivedFromX));
433   EXPECT_TRUE(notMatches("class X {}; class Y : public X {}; "
434                          "typedef Y V; typedef V W; class Z : public W {};",
435                          ZIsDirectlyDerivedFromX));
436   EXPECT_TRUE(
437     matches("template<class T, class U> class X {}; "
438               "template<class T> class A { class Z : public X<T, int> {}; };",
439             ZIsDerivedFromX));
440   EXPECT_TRUE(
441     notMatches("template<class X> class D { typedef X A; typedef A B; "
442                  "  typedef B C; class Z : public C {}; };",
443                ZIsDerivedFromX));
444   EXPECT_TRUE(
445     matches("class X {}; typedef X A; typedef A B; "
446               "class Z : public B {};", ZIsDerivedFromX));
447   EXPECT_TRUE(
448     matches("class X {}; typedef X A; typedef A B; typedef B C; "
449               "class Z : public C {};", ZIsDerivedFromX));
450   EXPECT_TRUE(
451     matches("class U {}; typedef U X; typedef X V; "
452               "class Z : public V {};", ZIsDerivedFromX));
453   EXPECT_TRUE(
454     matches("class Base {}; typedef Base X; "
455               "class Z : public Base {};", ZIsDerivedFromX));
456   EXPECT_TRUE(
457     matches("class Base {}; typedef Base Base2; typedef Base2 X; "
458               "class Z : public Base {};", ZIsDerivedFromX));
459   EXPECT_TRUE(
460     notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
461                  "class Z : public Base {};", ZIsDerivedFromX));
462   EXPECT_TRUE(
463     matches("class A {}; typedef A X; typedef A Y; "
464               "class Z : public Y {};", ZIsDerivedFromX));
465   EXPECT_TRUE(
466     notMatches("template <typename T> class Z;"
467                  "template <> class Z<void> {};"
468                  "template <typename T> class Z : public Z<void> {};",
469                IsDerivedFromX));
470   EXPECT_TRUE(
471     matches("template <typename T> class X;"
472               "template <> class X<void> {};"
473               "template <typename T> class X : public X<void> {};",
474             IsDerivedFromX));
475   EXPECT_TRUE(matches(
476     "class X {};"
477       "template <typename T> class Z;"
478       "template <> class Z<void> {};"
479       "template <typename T> class Z : public Z<void>, public X {};",
480     ZIsDerivedFromX));
481   EXPECT_TRUE(
482     notMatches("template<int> struct X;"
483                  "template<int i> struct X : public X<i-1> {};",
484                cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
485   EXPECT_TRUE(matches(
486     "struct A {};"
487       "template<int> struct X;"
488       "template<int i> struct X : public X<i-1> {};"
489       "template<> struct X<0> : public A {};"
490       "struct B : public X<42> {};",
491     cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
492   EXPECT_TRUE(notMatches(
493       "struct A {};"
494       "template<int> struct X;"
495       "template<int i> struct X : public X<i-1> {};"
496       "template<> struct X<0> : public A {};"
497       "struct B : public X<42> {};",
498       cxxRecordDecl(hasName("B"),
499                     isDirectlyDerivedFrom(recordDecl(hasName("A"))))));
500 
501   // FIXME: Once we have better matchers for template type matching,
502   // get rid of the Variable(...) matching and match the right template
503   // declarations directly.
504   const char *RecursiveTemplateOneParameter =
505     "class Base1 {}; class Base2 {};"
506       "template <typename T> class Z;"
507       "template <> class Z<void> : public Base1 {};"
508       "template <> class Z<int> : public Base2 {};"
509       "template <> class Z<float> : public Z<void> {};"
510       "template <> class Z<double> : public Z<int> {};"
511       "template <typename T> class Z : public Z<float>, public Z<double> {};"
512       "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
513   EXPECT_TRUE(matches(
514     RecursiveTemplateOneParameter,
515     varDecl(hasName("z_float"),
516             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
517   EXPECT_TRUE(notMatches(
518     RecursiveTemplateOneParameter,
519     varDecl(hasName("z_float"),
520             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
521   EXPECT_TRUE(matches(
522     RecursiveTemplateOneParameter,
523     varDecl(hasName("z_char"),
524             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
525                                                  isDerivedFrom("Base2")))))));
526 
527   const char *RecursiveTemplateTwoParameters =
528     "class Base1 {}; class Base2 {};"
529       "template <typename T1, typename T2> class Z;"
530       "template <typename T> class Z<void, T> : public Base1 {};"
531       "template <typename T> class Z<int, T> : public Base2 {};"
532       "template <typename T> class Z<float, T> : public Z<void, T> {};"
533       "template <typename T> class Z<double, T> : public Z<int, T> {};"
534       "template <typename T1, typename T2> class Z : "
535       "    public Z<float, T2>, public Z<double, T2> {};"
536       "void f() { Z<float, void> z_float; Z<double, void> z_double; "
537       "           Z<char, void> z_char; }";
538   EXPECT_TRUE(matches(
539     RecursiveTemplateTwoParameters,
540     varDecl(hasName("z_float"),
541             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
542   EXPECT_TRUE(notMatches(
543     RecursiveTemplateTwoParameters,
544     varDecl(hasName("z_float"),
545             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
546   EXPECT_TRUE(matches(
547     RecursiveTemplateTwoParameters,
548     varDecl(hasName("z_char"),
549             hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
550                                                  isDerivedFrom("Base2")))))));
551   EXPECT_TRUE(matches(
552     "namespace ns { class X {}; class Y : public X {}; }",
553     cxxRecordDecl(isDerivedFrom("::ns::X"))));
554   EXPECT_TRUE(notMatches(
555     "class X {}; class Y : public X {};",
556     cxxRecordDecl(isDerivedFrom("::ns::X"))));
557 
558   EXPECT_TRUE(matches(
559     "class X {}; class Y : public X {};",
560     cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
561 
562   EXPECT_TRUE(matches(
563     "template<typename T> class X {};"
564       "template<typename T> using Z = X<T>;"
565       "template <typename T> class Y : Z<T> {};",
566     cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
567 }
568 
TEST(DeclarationMatcher,IsDerivedFromEmptyName)569 TEST(DeclarationMatcher, IsDerivedFromEmptyName) {
570   const char *const Code = "class X {}; class Y : public X {};";
571   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDerivedFrom(""))));
572   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isDirectlyDerivedFrom(""))));
573   EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isSameOrDerivedFrom(""))));
574 }
575 
TEST(DeclarationMatcher,ObjCClassIsDerived)576 TEST(DeclarationMatcher, ObjCClassIsDerived) {
577   DeclarationMatcher IsDerivedFromX = objcInterfaceDecl(isDerivedFrom("X"));
578   EXPECT_TRUE(
579       matchesObjC("@interface X @end @interface Y : X @end", IsDerivedFromX));
580   EXPECT_TRUE(matchesObjC(
581       "@interface X @end @interface Y<__covariant ObjectType> : X @end",
582       IsDerivedFromX));
583   EXPECT_TRUE(matchesObjC(
584       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
585       IsDerivedFromX));
586   EXPECT_TRUE(matchesObjC(
587       "@interface X @end typedef X Y; @interface Z : Y @end", IsDerivedFromX));
588   EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDerivedFromX));
589   EXPECT_TRUE(notMatchesObjC("@class X;", IsDerivedFromX));
590   EXPECT_TRUE(notMatchesObjC("@class Y;", IsDerivedFromX));
591   EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
592                              IsDerivedFromX));
593   EXPECT_TRUE(notMatchesObjC("@interface X @end typedef X Y;", IsDerivedFromX));
594 
595   DeclarationMatcher IsDirectlyDerivedFromX =
596       objcInterfaceDecl(isDirectlyDerivedFrom("X"));
597   EXPECT_TRUE(
598       matchesObjC("@interface X @end @interface Y : X @end", IsDirectlyDerivedFromX));
599   EXPECT_TRUE(matchesObjC(
600       "@interface X @end @interface Y<__covariant ObjectType> : X @end",
601       IsDirectlyDerivedFromX));
602   EXPECT_TRUE(matchesObjC(
603       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
604       IsDirectlyDerivedFromX));
605   EXPECT_TRUE(matchesObjC(
606       "@interface X @end typedef X Y; @interface Z : Y @end",
607       IsDirectlyDerivedFromX));
608   EXPECT_TRUE(notMatchesObjC("@interface X @end", IsDirectlyDerivedFromX));
609   EXPECT_TRUE(notMatchesObjC("@class X;", IsDirectlyDerivedFromX));
610   EXPECT_TRUE(notMatchesObjC("@class Y;", IsDirectlyDerivedFromX));
611   EXPECT_TRUE(notMatchesObjC("@interface X @end @compatibility_alias Y X;",
612                              IsDirectlyDerivedFromX));
613   EXPECT_TRUE(notMatchesObjC("@interface X @end typedef X Y;",
614                              IsDirectlyDerivedFromX));
615 
616   DeclarationMatcher IsAX = objcInterfaceDecl(isSameOrDerivedFrom("X"));
617   EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end", IsAX));
618   EXPECT_TRUE(matchesObjC("@interface X @end", IsAX));
619   EXPECT_TRUE(matchesObjC("@class X;", IsAX));
620   EXPECT_TRUE(notMatchesObjC("@interface Y @end", IsAX));
621   EXPECT_TRUE(notMatchesObjC("@class Y;", IsAX));
622 
623   DeclarationMatcher ZIsDerivedFromX =
624       objcInterfaceDecl(hasName("Z"), isDerivedFrom("X"));
625   DeclarationMatcher ZIsDirectlyDerivedFromX =
626       objcInterfaceDecl(hasName("Z"), isDirectlyDerivedFrom("X"));
627   EXPECT_TRUE(matchesObjC(
628       "@interface X @end @interface Y : X @end @interface Z : Y @end",
629       ZIsDerivedFromX));
630   EXPECT_TRUE(matchesObjC("@interface X @end @interface Y : X @end typedef Y "
631                           "V; typedef V W; @interface Z : W @end",
632                           ZIsDerivedFromX));
633   EXPECT_TRUE(matchesObjC(
634       "@interface X @end typedef X Y; @interface Z : Y @end", ZIsDerivedFromX));
635   EXPECT_TRUE(matchesObjC(
636       "@interface X @end typedef X Y; @interface Z : Y @end",
637       ZIsDirectlyDerivedFromX));
638   EXPECT_TRUE(matchesObjC(
639       "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
640       ZIsDerivedFromX));
641   EXPECT_TRUE(matchesObjC(
642       "@interface A @end typedef A X; typedef A Y; @interface Z : Y @end",
643       ZIsDirectlyDerivedFromX));
644   EXPECT_TRUE(matchesObjC(
645       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
646       ZIsDerivedFromX));
647   EXPECT_TRUE(matchesObjC(
648       "@interface X @end @compatibility_alias Y X; @interface Z : Y @end",
649       ZIsDirectlyDerivedFromX));
650   EXPECT_TRUE(matchesObjC(
651       "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
652       ZIsDerivedFromX));
653   EXPECT_TRUE(matchesObjC(
654       "@interface Y @end @compatibility_alias X Y; @interface Z : Y @end",
655       ZIsDirectlyDerivedFromX));
656   EXPECT_TRUE(matchesObjC(
657       "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
658       "@interface Z : Y @end", ZIsDerivedFromX));
659   EXPECT_TRUE(matchesObjC(
660       "@interface A @end @compatibility_alias X A; @compatibility_alias Y A;"
661       "@interface Z : Y @end", ZIsDirectlyDerivedFromX));
662   EXPECT_TRUE(matchesObjC(
663       "@interface Y @end typedef Y X; @interface Z : X @end", ZIsDerivedFromX));
664   EXPECT_TRUE(matchesObjC(
665       "@interface Y @end typedef Y X; @interface Z : X @end",
666       ZIsDirectlyDerivedFromX));
667   EXPECT_TRUE(matchesObjC(
668       "@interface A @end @compatibility_alias Y A; typedef Y X;"
669       "@interface Z : A @end", ZIsDerivedFromX));
670   EXPECT_TRUE(matchesObjC(
671       "@interface A @end @compatibility_alias Y A; typedef Y X;"
672       "@interface Z : A @end", ZIsDirectlyDerivedFromX));
673   EXPECT_TRUE(matchesObjC(
674       "@interface A @end typedef A Y; @compatibility_alias X Y;"
675       "@interface Z : A @end", ZIsDerivedFromX));
676   EXPECT_TRUE(matchesObjC(
677       "@interface A @end typedef A Y; @compatibility_alias X Y;"
678       "@interface Z : A @end", ZIsDirectlyDerivedFromX));
679 }
680 
TEST(DeclarationMatcher,IsLambda)681 TEST(DeclarationMatcher, IsLambda) {
682   const auto IsLambda = cxxMethodDecl(ofClass(cxxRecordDecl(isLambda())));
683   EXPECT_TRUE(matches("auto x = []{};", IsLambda));
684   EXPECT_TRUE(notMatches("struct S { void operator()() const; };", IsLambda));
685 }
686 
TEST(Matcher,BindMatchedNodes)687 TEST(Matcher, BindMatchedNodes) {
688   DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
689 
690   EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
691                                        ClassX, std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x")));
692 
693   EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
694                                         ClassX, std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("other-id")));
695 
696   TypeMatcher TypeAHasClassB = hasDeclaration(
697     recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
698 
699   EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
700                                        TypeAHasClassB,
701                                        std::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
702 
703   StatementMatcher MethodX =
704     callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
705 
706   EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
707                                        MethodX,
708                                        std::make_unique<VerifyIdIsBoundTo<CXXMemberCallExpr>>("x")));
709 }
710 
TEST(Matcher,BindTheSameNameInAlternatives)711 TEST(Matcher, BindTheSameNameInAlternatives) {
712   StatementMatcher matcher = anyOf(
713     binaryOperator(hasOperatorName("+"),
714                    hasLHS(expr().bind("x")),
715                    hasRHS(integerLiteral(equals(0)))),
716     binaryOperator(hasOperatorName("+"),
717                    hasLHS(integerLiteral(equals(0))),
718                    hasRHS(expr().bind("x"))));
719 
720   EXPECT_TRUE(matchAndVerifyResultTrue(
721     // The first branch of the matcher binds x to 0 but then fails.
722     // The second branch binds x to f() and succeeds.
723     "int f() { return 0 + f(); }",
724     matcher,
725     std::make_unique<VerifyIdIsBoundTo<CallExpr>>("x")));
726 }
727 
TEST(Matcher,BindsIDForMemoizedResults)728 TEST(Matcher, BindsIDForMemoizedResults) {
729   // Using the same matcher in two match expressions will make memoization
730   // kick in.
731   DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
732   EXPECT_TRUE(matchAndVerifyResultTrue(
733     "class A { class B { class X {}; }; };",
734     DeclarationMatcher(anyOf(
735       recordDecl(hasName("A"), hasDescendant(ClassX)),
736       recordDecl(hasName("B"), hasDescendant(ClassX)))),
737     std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 2)));
738 }
739 
TEST(HasType,MatchesAsString)740 TEST(HasType, MatchesAsString) {
741   EXPECT_TRUE(
742     matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
743             cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
744   EXPECT_TRUE(
745     matches("class X { void x(int x) {} };",
746             cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
747   EXPECT_TRUE(matches("namespace ns { struct A {}; }  struct B { ns::A a; };",
748                       fieldDecl(hasType(asString("ns::A")))));
749   EXPECT_TRUE(matches("namespace { struct A {}; }  struct B { A a; };",
750                       fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
751 }
752 
TEST(Matcher,HasOperatorNameForOverloadedOperatorCall)753 TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
754   StatementMatcher OpCallAndAnd =
755     cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
756   EXPECT_TRUE(matches("class Y { }; "
757                         "bool operator&&(Y x, Y y) { return true; }; "
758                         "Y a; Y b; bool c = a && b;", OpCallAndAnd));
759   StatementMatcher OpCallLessLess =
760     cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
761   EXPECT_TRUE(notMatches("class Y { }; "
762                            "bool operator&&(Y x, Y y) { return true; }; "
763                            "Y a; Y b; bool c = a && b;",
764                          OpCallLessLess));
765   StatementMatcher OpStarCall =
766     cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
767   EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
768                       OpStarCall));
769   DeclarationMatcher ClassWithOpStar =
770     cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
771   EXPECT_TRUE(matches("class Y { int operator*(); };",
772                       ClassWithOpStar));
773   EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
774                          ClassWithOpStar)) ;
775   DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
776   EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
777   EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
778 }
779 
780 
TEST(Matcher,NestedOverloadedOperatorCalls)781 TEST(Matcher, NestedOverloadedOperatorCalls) {
782   EXPECT_TRUE(matchAndVerifyResultTrue(
783     "class Y { }; "
784       "Y& operator&&(Y& x, Y& y) { return x; }; "
785       "Y a; Y b; Y c; Y d = a && b && c;",
786     cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
787     std::make_unique<VerifyIdIsBoundTo<CXXOperatorCallExpr>>("x", 2)));
788   EXPECT_TRUE(matches("class Y { }; "
789                         "Y& operator&&(Y& x, Y& y) { return x; }; "
790                         "Y a; Y b; Y c; Y d = a && b && c;",
791                       cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
792   EXPECT_TRUE(
793     matches("class Y { }; "
794               "Y& operator&&(Y& x, Y& y) { return x; }; "
795               "Y a; Y b; Y c; Y d = a && b && c;",
796             cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
797 }
798 
TEST(Matcher,VarDecl_Storage)799 TEST(Matcher, VarDecl_Storage) {
800   auto M = varDecl(hasName("X"), hasLocalStorage());
801   EXPECT_TRUE(matches("void f() { int X; }", M));
802   EXPECT_TRUE(notMatches("int X;", M));
803   EXPECT_TRUE(notMatches("void f() { static int X; }", M));
804 
805   M = varDecl(hasName("X"), hasGlobalStorage());
806   EXPECT_TRUE(notMatches("void f() { int X; }", M));
807   EXPECT_TRUE(matches("int X;", M));
808   EXPECT_TRUE(matches("void f() { static int X; }", M));
809 }
810 
TEST(Matcher,VarDecl_IsStaticLocal)811 TEST(Matcher, VarDecl_IsStaticLocal) {
812   auto M = varDecl(isStaticLocal());
813   EXPECT_TRUE(matches("void f() { static int X; }", M));
814   EXPECT_TRUE(notMatches("static int X;", M));
815   EXPECT_TRUE(notMatches("void f() { int X; }", M));
816   EXPECT_TRUE(notMatches("int X;", M));
817 }
818 
TEST(Matcher,VarDecl_StorageDuration)819 TEST(Matcher, VarDecl_StorageDuration) {
820   std::string T =
821     "void f() { int x; static int y; } int a;static int b;extern int c;";
822 
823   EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
824   EXPECT_TRUE(
825     notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
826   EXPECT_TRUE(
827     notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
828 
829   EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
830   EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
831   EXPECT_TRUE(matches(T, varDecl(hasName("b"), hasStaticStorageDuration())));
832   EXPECT_TRUE(matches(T, varDecl(hasName("c"), hasStaticStorageDuration())));
833   EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
834 
835   // FIXME: It is really hard to test with thread_local itself because not all
836   // targets support TLS, which causes this to be an error depending on what
837   // platform the test is being run on. We do not have access to the TargetInfo
838   // object to be able to test whether the platform supports TLS or not.
839   EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
840   EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
841   EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
842 }
843 
TEST(Matcher,FindsVarDeclInFunctionParameter)844 TEST(Matcher, FindsVarDeclInFunctionParameter) {
845   EXPECT_TRUE(matches(
846     "void f(int i) {}",
847     varDecl(hasName("i"))));
848 }
849 
TEST(UnaryExpressionOrTypeTraitExpression,MatchesCorrectType)850 TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
851   EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
852     hasArgumentOfType(asString("int")))));
853   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
854     hasArgumentOfType(asString("float")))));
855   EXPECT_TRUE(matches(
856     "struct A {}; void x() { A a; int b = sizeof(a); }",
857     sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
858   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
859     hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
860 }
861 
TEST(IsInteger,MatchesIntegers)862 TEST(IsInteger, MatchesIntegers) {
863   EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
864   EXPECT_TRUE(matches(
865     "long long i = 0; void f(long long) { }; void g() {f(i);}",
866     callExpr(hasArgument(0, declRefExpr(
867       to(varDecl(hasType(isInteger()))))))));
868 }
869 
TEST(IsInteger,ReportsNoFalsePositives)870 TEST(IsInteger, ReportsNoFalsePositives) {
871   EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
872   EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
873                          callExpr(hasArgument(0, declRefExpr(
874                            to(varDecl(hasType(isInteger()))))))));
875 }
876 
TEST(IsSignedInteger,MatchesSignedIntegers)877 TEST(IsSignedInteger, MatchesSignedIntegers) {
878   EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isSignedInteger()))));
879   EXPECT_TRUE(notMatches("unsigned i = 0;",
880                          varDecl(hasType(isSignedInteger()))));
881 }
882 
TEST(IsUnsignedInteger,MatchesUnsignedIntegers)883 TEST(IsUnsignedInteger, MatchesUnsignedIntegers) {
884   EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isUnsignedInteger()))));
885   EXPECT_TRUE(matches("unsigned i = 0;",
886                       varDecl(hasType(isUnsignedInteger()))));
887 }
888 
TEST(IsAnyPointer,MatchesPointers)889 TEST(IsAnyPointer, MatchesPointers) {
890   EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
891 }
892 
TEST(IsAnyPointer,MatchesObjcPointer)893 TEST(IsAnyPointer, MatchesObjcPointer) {
894   EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
895                           varDecl(hasType(isAnyPointer()))));
896 }
897 
TEST(IsAnyPointer,ReportsNoFalsePositives)898 TEST(IsAnyPointer, ReportsNoFalsePositives) {
899   EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
900 }
901 
TEST(IsAnyCharacter,MatchesCharacters)902 TEST(IsAnyCharacter, MatchesCharacters) {
903   EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
904 }
905 
TEST(IsAnyCharacter,ReportsNoFalsePositives)906 TEST(IsAnyCharacter, ReportsNoFalsePositives) {
907   EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
908 }
909 
TEST(IsArrow,MatchesMemberVariablesViaArrow)910 TEST(IsArrow, MatchesMemberVariablesViaArrow) {
911   EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
912                       memberExpr(isArrow())));
913   EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
914                       memberExpr(isArrow())));
915   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
916                          memberExpr(isArrow())));
917   EXPECT_TRUE(matches("template <class T> class Y { void x() { this->m; } };",
918                       cxxDependentScopeMemberExpr(isArrow())));
919   EXPECT_TRUE(
920       notMatches("template <class T> class Y { void x() { (*this).m; } };",
921                  cxxDependentScopeMemberExpr(isArrow())));
922 }
923 
TEST(IsArrow,MatchesStaticMemberVariablesViaArrow)924 TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
925   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
926                       memberExpr(isArrow())));
927   EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
928                          memberExpr(isArrow())));
929   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
930                          memberExpr(isArrow())));
931 }
932 
TEST(IsArrow,MatchesMemberCallsViaArrow)933 TEST(IsArrow, MatchesMemberCallsViaArrow) {
934   EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
935                       memberExpr(isArrow())));
936   EXPECT_TRUE(matches("class Y { void x() { x(); } };",
937                       memberExpr(isArrow())));
938   EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
939                          memberExpr(isArrow())));
940   EXPECT_TRUE(
941       matches("class Y { template <class T> void x() { this->x<T>(); } };",
942               unresolvedMemberExpr(isArrow())));
943   EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
944                       unresolvedMemberExpr(isArrow())));
945   EXPECT_TRUE(
946       notMatches("class Y { template <class T> void x() { (*this).x<T>(); } };",
947                  unresolvedMemberExpr(isArrow())));
948 }
949 
TEST(ConversionDeclaration,IsExplicit)950 TEST(ConversionDeclaration, IsExplicit) {
951   EXPECT_TRUE(matches("struct S { explicit operator int(); };",
952                       cxxConversionDecl(isExplicit())));
953   EXPECT_TRUE(notMatches("struct S { operator int(); };",
954                          cxxConversionDecl(isExplicit())));
955   EXPECT_TRUE(matchesConditionally(
956       "template<bool b> struct S { explicit(b) operator int(); };",
957       cxxConversionDecl(isExplicit()), false, "-std=c++2a"));
958   EXPECT_TRUE(matchesConditionally(
959       "struct S { explicit(true) operator int(); };",
960       cxxConversionDecl(isExplicit()), true, "-std=c++2a"));
961   EXPECT_TRUE(matchesConditionally(
962       "struct S { explicit(false) operator int(); };",
963       cxxConversionDecl(isExplicit()), false, "-std=c++2a"));
964 }
965 
TEST(Matcher,ArgumentCount)966 TEST(Matcher, ArgumentCount) {
967   StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
968 
969   EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
970   EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
971   EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
972 }
973 
TEST(Matcher,ParameterCount)974 TEST(Matcher, ParameterCount) {
975   DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
976   EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
977   EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
978   EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
979   EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
980   EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
981 }
982 
TEST(Matcher,References)983 TEST(Matcher, References) {
984   DeclarationMatcher ReferenceClassX = varDecl(
985     hasType(references(recordDecl(hasName("X")))));
986   EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
987                       ReferenceClassX));
988   EXPECT_TRUE(
989     matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
990   // The match here is on the implicit copy constructor code for
991   // class X, not on code 'X x = y'.
992   EXPECT_TRUE(
993     matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
994   EXPECT_TRUE(
995     notMatches("class X {}; extern X x;", ReferenceClassX));
996   EXPECT_TRUE(
997     notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
998 }
999 
TEST(QualType,hasLocalQualifiers)1000 TEST(QualType, hasLocalQualifiers) {
1001   EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
1002                          varDecl(hasType(hasLocalQualifiers()))));
1003   EXPECT_TRUE(matches("int *const j = nullptr;",
1004                       varDecl(hasType(hasLocalQualifiers()))));
1005   EXPECT_TRUE(matches("int *volatile k;",
1006                       varDecl(hasType(hasLocalQualifiers()))));
1007   EXPECT_TRUE(notMatches("int m;",
1008                          varDecl(hasType(hasLocalQualifiers()))));
1009 }
1010 
TEST(IsExternC,MatchesExternCFunctionDeclarations)1011 TEST(IsExternC, MatchesExternCFunctionDeclarations) {
1012   EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
1013   EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
1014                       functionDecl(isExternC())));
1015   EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
1016 }
1017 
TEST(IsExternC,MatchesExternCVariableDeclarations)1018 TEST(IsExternC, MatchesExternCVariableDeclarations) {
1019   EXPECT_TRUE(matches("extern \"C\" int i;", varDecl(isExternC())));
1020   EXPECT_TRUE(matches("extern \"C\" { int i; }", varDecl(isExternC())));
1021   EXPECT_TRUE(notMatches("int i;", varDecl(isExternC())));
1022 }
1023 
TEST(IsStaticStorageClass,MatchesStaticDeclarations)1024 TEST(IsStaticStorageClass, MatchesStaticDeclarations) {
1025   EXPECT_TRUE(
1026       matches("static void f() {}", functionDecl(isStaticStorageClass())));
1027   EXPECT_TRUE(matches("static int i = 1;", varDecl(isStaticStorageClass())));
1028   EXPECT_TRUE(notMatches("int i = 1;", varDecl(isStaticStorageClass())));
1029   EXPECT_TRUE(notMatches("extern int i;", varDecl(isStaticStorageClass())));
1030   EXPECT_TRUE(notMatches("void f() {}", functionDecl(isStaticStorageClass())));
1031 }
1032 
TEST(IsDefaulted,MatchesDefaultedFunctionDeclarations)1033 TEST(IsDefaulted, MatchesDefaultedFunctionDeclarations) {
1034   EXPECT_TRUE(notMatches("class A { ~A(); };",
1035                          functionDecl(hasName("~A"), isDefaulted())));
1036   EXPECT_TRUE(matches("class B { ~B() = default; };",
1037                       functionDecl(hasName("~B"), isDefaulted())));
1038 }
1039 
TEST(IsDeleted,MatchesDeletedFunctionDeclarations)1040 TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
1041   EXPECT_TRUE(
1042     notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
1043   EXPECT_TRUE(matches("void Func() = delete;",
1044                       functionDecl(hasName("Func"), isDeleted())));
1045 }
1046 
TEST(IsNoThrow,MatchesNoThrowFunctionDeclarations)1047 TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
1048   EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
1049   EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
1050   EXPECT_TRUE(
1051     notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
1052   EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
1053   EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
1054 
1055   EXPECT_TRUE(notMatches("void f();", functionProtoType(isNoThrow())));
1056   EXPECT_TRUE(notMatches("void f() throw(int);", functionProtoType(isNoThrow())));
1057   EXPECT_TRUE(
1058     notMatches("void f() noexcept(false);", functionProtoType(isNoThrow())));
1059   EXPECT_TRUE(matches("void f() throw();", functionProtoType(isNoThrow())));
1060   EXPECT_TRUE(matches("void f() noexcept;", functionProtoType(isNoThrow())));
1061 }
1062 
TEST(isConstexpr,MatchesConstexprDeclarations)1063 TEST(isConstexpr, MatchesConstexprDeclarations) {
1064   EXPECT_TRUE(matches("constexpr int foo = 42;",
1065                       varDecl(hasName("foo"), isConstexpr())));
1066   EXPECT_TRUE(matches("constexpr int bar();",
1067                       functionDecl(hasName("bar"), isConstexpr())));
1068   EXPECT_TRUE(matches("void baz() { if constexpr(1 > 0) {} }",
1069                       ifStmt(isConstexpr()), LanguageMode::Cxx17OrLater));
1070   EXPECT_TRUE(notMatches("void baz() { if (1 > 0) {} }", ifStmt(isConstexpr()),
1071                          LanguageMode::Cxx17OrLater));
1072 }
1073 
TEST(hasInitStatement,MatchesSelectionInitializers)1074 TEST(hasInitStatement, MatchesSelectionInitializers) {
1075   EXPECT_TRUE(matches("void baz() { if (int i = 1; i > 0) {} }",
1076                       ifStmt(hasInitStatement(anything())),
1077                       LanguageMode::Cxx17OrLater));
1078   EXPECT_TRUE(notMatches("void baz() { if (int i = 1) {} }",
1079                          ifStmt(hasInitStatement(anything()))));
1080   EXPECT_TRUE(notMatches("void baz() { if (1 > 0) {} }",
1081                          ifStmt(hasInitStatement(anything()))));
1082   EXPECT_TRUE(matches(
1083       "void baz(int i) { switch (int j = i; j) { default: break; } }",
1084       switchStmt(hasInitStatement(anything())), LanguageMode::Cxx17OrLater));
1085   EXPECT_TRUE(notMatches("void baz(int i) { switch (i) { default: break; } }",
1086                          switchStmt(hasInitStatement(anything()))));
1087 }
1088 
TEST(hasInitStatement,MatchesRangeForInitializers)1089 TEST(hasInitStatement, MatchesRangeForInitializers) {
1090   EXPECT_TRUE(matches("void baz() {"
1091                       "int items[] = {};"
1092                       "for (auto &arr = items; auto &item : arr) {}"
1093                       "}",
1094                       cxxForRangeStmt(hasInitStatement(anything())),
1095                       LanguageMode::Cxx2aOrLater));
1096   EXPECT_TRUE(notMatches("void baz() {"
1097                          "int items[] = {};"
1098                          "for (auto &item : items) {}"
1099                          "}",
1100                          cxxForRangeStmt(hasInitStatement(anything()))));
1101 }
1102 
TEST(TemplateArgumentCountIs,Matches)1103 TEST(TemplateArgumentCountIs, Matches) {
1104   EXPECT_TRUE(
1105     matches("template<typename T> struct C {}; C<int> c;",
1106             classTemplateSpecializationDecl(templateArgumentCountIs(1))));
1107   EXPECT_TRUE(
1108     notMatches("template<typename T> struct C {}; C<int> c;",
1109                classTemplateSpecializationDecl(templateArgumentCountIs(2))));
1110 
1111   EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
1112                       templateSpecializationType(templateArgumentCountIs(1))));
1113   EXPECT_TRUE(
1114     notMatches("template<typename T> struct C {}; C<int> c;",
1115                templateSpecializationType(templateArgumentCountIs(2))));
1116 }
1117 
TEST(IsIntegral,Matches)1118 TEST(IsIntegral, Matches) {
1119   EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1120                       classTemplateSpecializationDecl(
1121                         hasAnyTemplateArgument(isIntegral()))));
1122   EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
1123                          classTemplateSpecializationDecl(hasAnyTemplateArgument(
1124                            templateArgument(isIntegral())))));
1125 }
1126 
TEST(EqualsIntegralValue,Matches)1127 TEST(EqualsIntegralValue, Matches) {
1128   EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
1129                       classTemplateSpecializationDecl(
1130                         hasAnyTemplateArgument(equalsIntegralValue("42")))));
1131   EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
1132                       classTemplateSpecializationDecl(
1133                         hasAnyTemplateArgument(equalsIntegralValue("-42")))));
1134   EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
1135                       classTemplateSpecializationDecl(
1136                         hasAnyTemplateArgument(equalsIntegralValue("-34")))));
1137   EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
1138                          classTemplateSpecializationDecl(hasAnyTemplateArgument(
1139                            equalsIntegralValue("0042")))));
1140 }
1141 
TEST(Matcher,MatchesAccessSpecDecls)1142 TEST(Matcher, MatchesAccessSpecDecls) {
1143   EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
1144   EXPECT_TRUE(
1145       matches("class C { public: int i; };", accessSpecDecl(isPublic())));
1146   EXPECT_TRUE(
1147       notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
1148   EXPECT_TRUE(
1149       notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
1150 
1151   EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
1152 }
1153 
TEST(Matcher,MatchesFinal)1154 TEST(Matcher, MatchesFinal) {
1155   EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
1156   EXPECT_TRUE(matches("class X { virtual void f() final; };",
1157                       cxxMethodDecl(isFinal())));
1158   EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
1159   EXPECT_TRUE(
1160     notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
1161 }
1162 
TEST(Matcher,MatchesVirtualMethod)1163 TEST(Matcher, MatchesVirtualMethod) {
1164   EXPECT_TRUE(matches("class X { virtual int f(); };",
1165                       cxxMethodDecl(isVirtual(), hasName("::X::f"))));
1166   EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
1167 }
1168 
TEST(Matcher,MatchesVirtualAsWrittenMethod)1169 TEST(Matcher, MatchesVirtualAsWrittenMethod) {
1170   EXPECT_TRUE(matches("class A { virtual int f(); };"
1171                         "class B : public A { int f(); };",
1172                       cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
1173   EXPECT_TRUE(
1174     notMatches("class A { virtual int f(); };"
1175                  "class B : public A { int f(); };",
1176                cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
1177 }
1178 
TEST(Matcher,MatchesPureMethod)1179 TEST(Matcher, MatchesPureMethod) {
1180   EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
1181                       cxxMethodDecl(isPure(), hasName("::X::f"))));
1182   EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
1183 }
1184 
TEST(Matcher,MatchesCopyAssignmentOperator)1185 TEST(Matcher, MatchesCopyAssignmentOperator) {
1186   EXPECT_TRUE(matches("class X { X &operator=(X); };",
1187                       cxxMethodDecl(isCopyAssignmentOperator())));
1188   EXPECT_TRUE(matches("class X { X &operator=(X &); };",
1189                       cxxMethodDecl(isCopyAssignmentOperator())));
1190   EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
1191                       cxxMethodDecl(isCopyAssignmentOperator())));
1192   EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
1193                       cxxMethodDecl(isCopyAssignmentOperator())));
1194   EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
1195                       cxxMethodDecl(isCopyAssignmentOperator())));
1196   EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
1197                          cxxMethodDecl(isCopyAssignmentOperator())));
1198 }
1199 
TEST(Matcher,MatchesMoveAssignmentOperator)1200 TEST(Matcher, MatchesMoveAssignmentOperator) {
1201   EXPECT_TRUE(notMatches("class X { X &operator=(X); };",
1202                          cxxMethodDecl(isMoveAssignmentOperator())));
1203   EXPECT_TRUE(matches("class X { X &operator=(X &&); };",
1204                       cxxMethodDecl(isMoveAssignmentOperator())));
1205   EXPECT_TRUE(matches("class X { X &operator=(const X &&); };",
1206                       cxxMethodDecl(isMoveAssignmentOperator())));
1207   EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };",
1208                       cxxMethodDecl(isMoveAssignmentOperator())));
1209   EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
1210                       cxxMethodDecl(isMoveAssignmentOperator())));
1211   EXPECT_TRUE(notMatches("class X { X &operator=(X &); };",
1212                          cxxMethodDecl(isMoveAssignmentOperator())));
1213 }
1214 
TEST(Matcher,MatchesConstMethod)1215 TEST(Matcher, MatchesConstMethod) {
1216   EXPECT_TRUE(
1217     matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
1218   EXPECT_TRUE(
1219     notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
1220 }
1221 
TEST(Matcher,MatchesOverridingMethod)1222 TEST(Matcher, MatchesOverridingMethod) {
1223   EXPECT_TRUE(matches("class X { virtual int f(); }; "
1224                         "class Y : public X { int f(); };",
1225                       cxxMethodDecl(isOverride(), hasName("::Y::f"))));
1226   EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
1227                            "class Y : public X { int f(); };",
1228                          cxxMethodDecl(isOverride(), hasName("::X::f"))));
1229   EXPECT_TRUE(notMatches("class X { int f(); }; "
1230                            "class Y : public X { int f(); };",
1231                          cxxMethodDecl(isOverride())));
1232   EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
1233                          cxxMethodDecl(isOverride())));
1234   EXPECT_TRUE(
1235     matches("template <typename Base> struct Y : Base { void f() override;};",
1236             cxxMethodDecl(isOverride(), hasName("::Y::f"))));
1237 }
1238 
TEST(Matcher,ConstructorArgument)1239 TEST(Matcher, ConstructorArgument) {
1240   StatementMatcher Constructor = cxxConstructExpr(
1241     hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
1242 
1243   EXPECT_TRUE(
1244     matches("class X { public: X(int); }; void x() { int y; X x(y); }",
1245             Constructor));
1246   EXPECT_TRUE(
1247     matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
1248             Constructor));
1249   EXPECT_TRUE(
1250     matches("class X { public: X(int); }; void x() { int y; X x = y; }",
1251             Constructor));
1252   EXPECT_TRUE(
1253     notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
1254                Constructor));
1255 
1256   StatementMatcher WrongIndex = cxxConstructExpr(
1257     hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
1258   EXPECT_TRUE(
1259     notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
1260                WrongIndex));
1261 }
1262 
TEST(Matcher,ConstructorArgumentCount)1263 TEST(Matcher, ConstructorArgumentCount) {
1264   StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
1265 
1266   EXPECT_TRUE(
1267     matches("class X { public: X(int); }; void x() { X x(0); }",
1268             Constructor1Arg));
1269   EXPECT_TRUE(
1270     matches("class X { public: X(int); }; void x() { X x = X(0); }",
1271             Constructor1Arg));
1272   EXPECT_TRUE(
1273     matches("class X { public: X(int); }; void x() { X x = 0; }",
1274             Constructor1Arg));
1275   EXPECT_TRUE(
1276     notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
1277                Constructor1Arg));
1278 }
1279 
TEST(Matcher,ConstructorListInitialization)1280 TEST(Matcher, ConstructorListInitialization) {
1281   StatementMatcher ConstructorListInit =
1282     cxxConstructExpr(isListInitialization());
1283 
1284   EXPECT_TRUE(
1285     matches("class X { public: X(int); }; void x() { X x{0}; }",
1286             ConstructorListInit));
1287   EXPECT_FALSE(
1288     matches("class X { public: X(int); }; void x() { X x(0); }",
1289             ConstructorListInit));
1290 }
1291 
TEST(ConstructorDeclaration,IsImplicit)1292 TEST(ConstructorDeclaration, IsImplicit) {
1293   // This one doesn't match because the constructor is not added by the
1294   // compiler (it is not needed).
1295   EXPECT_TRUE(notMatches("class Foo { };",
1296                          cxxConstructorDecl(isImplicit())));
1297   // The compiler added the implicit default constructor.
1298   EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
1299                       cxxConstructorDecl(isImplicit())));
1300   EXPECT_TRUE(matches("class Foo { Foo(){} };",
1301                       cxxConstructorDecl(unless(isImplicit()))));
1302   // The compiler added an implicit assignment operator.
1303   EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
1304                       cxxMethodDecl(isImplicit(), hasName("operator="))));
1305 }
1306 
TEST(ConstructorDeclaration,IsExplicit)1307 TEST(ConstructorDeclaration, IsExplicit) {
1308   EXPECT_TRUE(matches("struct S { explicit S(int); };",
1309                       cxxConstructorDecl(isExplicit())));
1310   EXPECT_TRUE(notMatches("struct S { S(int); };",
1311                          cxxConstructorDecl(isExplicit())));
1312   EXPECT_TRUE(matchesConditionally(
1313       "template<bool b> struct S { explicit(b) S(int);};",
1314       cxxConstructorDecl(isExplicit()), false, "-std=c++2a"));
1315   EXPECT_TRUE(matchesConditionally("struct S { explicit(true) S(int);};",
1316                                    cxxConstructorDecl(isExplicit()), true,
1317                                    "-std=c++2a"));
1318   EXPECT_TRUE(matchesConditionally("struct S { explicit(false) S(int);};",
1319                                    cxxConstructorDecl(isExplicit()), false,
1320                                    "-std=c++2a"));
1321 }
1322 
TEST(DeductionGuideDeclaration,IsExplicit)1323 TEST(DeductionGuideDeclaration, IsExplicit) {
1324   EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int);};"
1325                                    "S(int) -> S<int>;",
1326                                    cxxDeductionGuideDecl(isExplicit()), false,
1327                                    "-std=c++17"));
1328   EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int);};"
1329                                    "explicit S(int) -> S<int>;",
1330                                    cxxDeductionGuideDecl(isExplicit()), true,
1331                                    "-std=c++17"));
1332   EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int);};"
1333                                    "explicit(true) S(int) -> S<int>;",
1334                                    cxxDeductionGuideDecl(isExplicit()), true,
1335                                    "-std=c++2a"));
1336   EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int);};"
1337                                    "explicit(false) S(int) -> S<int>;",
1338                                    cxxDeductionGuideDecl(isExplicit()), false,
1339                                    "-std=c++2a"));
1340   EXPECT_TRUE(matchesConditionally(
1341       "template<typename T> struct S { S(int);};"
1342       "template<bool b = true> explicit(b) S(int) -> S<int>;",
1343       cxxDeductionGuideDecl(isExplicit()), false, "-std=c++2a"));
1344 }
1345 
TEST(ConstructorDeclaration,Kinds)1346 TEST(ConstructorDeclaration, Kinds) {
1347   EXPECT_TRUE(matches(
1348       "struct S { S(); };",
1349       cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
1350   EXPECT_TRUE(notMatches(
1351       "struct S { S(); };",
1352       cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
1353   EXPECT_TRUE(notMatches(
1354       "struct S { S(); };",
1355       cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
1356 
1357   EXPECT_TRUE(notMatches(
1358       "struct S { S(const S&); };",
1359       cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
1360   EXPECT_TRUE(matches(
1361       "struct S { S(const S&); };",
1362       cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
1363   EXPECT_TRUE(notMatches(
1364       "struct S { S(const S&); };",
1365       cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
1366 
1367   EXPECT_TRUE(notMatches(
1368       "struct S { S(S&&); };",
1369       cxxConstructorDecl(isDefaultConstructor(), unless(isImplicit()))));
1370   EXPECT_TRUE(notMatches(
1371       "struct S { S(S&&); };",
1372       cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))));
1373   EXPECT_TRUE(matches(
1374       "struct S { S(S&&); };",
1375       cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))));
1376 }
1377 
TEST(ConstructorDeclaration,IsUserProvided)1378 TEST(ConstructorDeclaration, IsUserProvided) {
1379   EXPECT_TRUE(notMatches("struct S { int X = 0; };",
1380                          cxxConstructorDecl(isUserProvided())));
1381   EXPECT_TRUE(notMatches("struct S { S() = default; };",
1382                          cxxConstructorDecl(isUserProvided())));
1383   EXPECT_TRUE(notMatches("struct S { S() = delete; };",
1384                          cxxConstructorDecl(isUserProvided())));
1385   EXPECT_TRUE(
1386     matches("struct S { S(); };", cxxConstructorDecl(isUserProvided())));
1387   EXPECT_TRUE(matches("struct S { S(); }; S::S(){}",
1388                       cxxConstructorDecl(isUserProvided())));
1389 }
1390 
TEST(ConstructorDeclaration,IsDelegatingConstructor)1391 TEST(ConstructorDeclaration, IsDelegatingConstructor) {
1392   EXPECT_TRUE(notMatches("struct S { S(); S(int); int X; };",
1393                          cxxConstructorDecl(isDelegatingConstructor())));
1394   EXPECT_TRUE(notMatches("struct S { S(){} S(int X) : X(X) {} int X; };",
1395                          cxxConstructorDecl(isDelegatingConstructor())));
1396   EXPECT_TRUE(matches(
1397     "struct S { S() : S(0) {} S(int X) : X(X) {} int X; };",
1398     cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(0))));
1399   EXPECT_TRUE(matches(
1400     "struct S { S(); S(int X); int X; }; S::S(int X) : S() {}",
1401     cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1))));
1402 }
1403 
TEST(StringLiteral,HasSize)1404 TEST(StringLiteral, HasSize) {
1405   StatementMatcher Literal = stringLiteral(hasSize(4));
1406   EXPECT_TRUE(matches("const char *s = \"abcd\";", Literal));
1407   // wide string
1408   EXPECT_TRUE(matches("const wchar_t *s = L\"abcd\";", Literal));
1409   // with escaped characters
1410   EXPECT_TRUE(matches("const char *s = \"\x05\x06\x07\x08\";", Literal));
1411   // no matching, too small
1412   EXPECT_TRUE(notMatches("const char *s = \"ab\";", Literal));
1413 }
1414 
TEST(Matcher,HasNameSupportsNamespaces)1415 TEST(Matcher, HasNameSupportsNamespaces) {
1416   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1417                       recordDecl(hasName("a::b::C"))));
1418   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1419                       recordDecl(hasName("::a::b::C"))));
1420   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1421                       recordDecl(hasName("b::C"))));
1422   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
1423                       recordDecl(hasName("C"))));
1424   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1425                          recordDecl(hasName("c::b::C"))));
1426   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1427                          recordDecl(hasName("a::c::C"))));
1428   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1429                          recordDecl(hasName("a::b::A"))));
1430   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1431                          recordDecl(hasName("::C"))));
1432   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1433                          recordDecl(hasName("::b::C"))));
1434   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1435                          recordDecl(hasName("z::a::b::C"))));
1436   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
1437                          recordDecl(hasName("a+b::C"))));
1438   EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
1439                          recordDecl(hasName("C"))));
1440 }
1441 
TEST(Matcher,HasNameSupportsOuterClasses)1442 TEST(Matcher, HasNameSupportsOuterClasses) {
1443   EXPECT_TRUE(
1444     matches("class A { class B { class C; }; };",
1445             recordDecl(hasName("A::B::C"))));
1446   EXPECT_TRUE(
1447     matches("class A { class B { class C; }; };",
1448             recordDecl(hasName("::A::B::C"))));
1449   EXPECT_TRUE(
1450     matches("class A { class B { class C; }; };",
1451             recordDecl(hasName("B::C"))));
1452   EXPECT_TRUE(
1453     matches("class A { class B { class C; }; };",
1454             recordDecl(hasName("C"))));
1455   EXPECT_TRUE(
1456     notMatches("class A { class B { class C; }; };",
1457                recordDecl(hasName("c::B::C"))));
1458   EXPECT_TRUE(
1459     notMatches("class A { class B { class C; }; };",
1460                recordDecl(hasName("A::c::C"))));
1461   EXPECT_TRUE(
1462     notMatches("class A { class B { class C; }; };",
1463                recordDecl(hasName("A::B::A"))));
1464   EXPECT_TRUE(
1465     notMatches("class A { class B { class C; }; };",
1466                recordDecl(hasName("::C"))));
1467   EXPECT_TRUE(
1468     notMatches("class A { class B { class C; }; };",
1469                recordDecl(hasName("::B::C"))));
1470   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
1471                          recordDecl(hasName("z::A::B::C"))));
1472   EXPECT_TRUE(
1473     notMatches("class A { class B { class C; }; };",
1474                recordDecl(hasName("A+B::C"))));
1475 }
1476 
TEST(Matcher,HasNameSupportsInlinedNamespaces)1477 TEST(Matcher, HasNameSupportsInlinedNamespaces) {
1478   std::string code = "namespace a { inline namespace b { class C; } }";
1479   EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
1480   EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
1481   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
1482   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
1483 }
1484 
TEST(Matcher,HasNameSupportsAnonymousNamespaces)1485 TEST(Matcher, HasNameSupportsAnonymousNamespaces) {
1486   std::string code = "namespace a { namespace { class C; } }";
1487   EXPECT_TRUE(
1488     matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
1489   EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
1490   EXPECT_TRUE(
1491     matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
1492   EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
1493 }
1494 
TEST(Matcher,HasNameSupportsAnonymousOuterClasses)1495 TEST(Matcher, HasNameSupportsAnonymousOuterClasses) {
1496   EXPECT_TRUE(matches("class A { class { class C; } x; };",
1497                       recordDecl(hasName("A::(anonymous class)::C"))));
1498   EXPECT_TRUE(matches("class A { class { class C; } x; };",
1499                       recordDecl(hasName("::A::(anonymous class)::C"))));
1500   EXPECT_FALSE(matches("class A { class { class C; } x; };",
1501                        recordDecl(hasName("::A::C"))));
1502   EXPECT_TRUE(matches("class A { struct { class C; } x; };",
1503                       recordDecl(hasName("A::(anonymous struct)::C"))));
1504   EXPECT_TRUE(matches("class A { struct { class C; } x; };",
1505                       recordDecl(hasName("::A::(anonymous struct)::C"))));
1506   EXPECT_FALSE(matches("class A { struct { class C; } x; };",
1507                        recordDecl(hasName("::A::C"))));
1508 }
1509 
TEST(Matcher,HasNameSupportsFunctionScope)1510 TEST(Matcher, HasNameSupportsFunctionScope) {
1511   std::string code =
1512     "namespace a { void F(int a) { struct S { int m; }; int i; } }";
1513   EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
1514   EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
1515 
1516   EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
1517   EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
1518   EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
1519   EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
1520   EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
1521 }
1522 
TEST(Matcher,HasNameQualifiedSupportsLinkage)1523 TEST(Matcher, HasNameQualifiedSupportsLinkage) {
1524   // https://bugs.llvm.org/show_bug.cgi?id=42193
1525   std::string code = R"cpp(namespace foo { extern "C" void test(); })cpp";
1526   EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
1527   EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
1528   EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
1529   EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
1530 
1531   code = R"cpp(namespace foo { extern "C" { void test(); } })cpp";
1532   EXPECT_TRUE(matches(code, functionDecl(hasName("test"))));
1533   EXPECT_TRUE(matches(code, functionDecl(hasName("foo::test"))));
1534   EXPECT_TRUE(matches(code, functionDecl(hasName("::foo::test"))));
1535   EXPECT_TRUE(notMatches(code, functionDecl(hasName("::test"))));
1536 }
1537 
TEST(Matcher,HasAnyName)1538 TEST(Matcher, HasAnyName) {
1539   const std::string Code = "namespace a { namespace b { class C; } }";
1540 
1541   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
1542   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
1543   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
1544   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
1545 
1546   EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
1547   EXPECT_TRUE(
1548     matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
1549 
1550   std::vector<StringRef> Names = {"::C", "::b::C", "::a::b::C"};
1551   EXPECT_TRUE(matches(Code, recordDecl(hasAnyName(Names))));
1552 }
1553 
TEST(Matcher,IsDefinition)1554 TEST(Matcher, IsDefinition) {
1555   DeclarationMatcher DefinitionOfClassA =
1556     recordDecl(hasName("A"), isDefinition());
1557   EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
1558   EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
1559 
1560   DeclarationMatcher DefinitionOfVariableA =
1561     varDecl(hasName("a"), isDefinition());
1562   EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
1563   EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
1564 
1565   DeclarationMatcher DefinitionOfMethodA =
1566     cxxMethodDecl(hasName("a"), isDefinition());
1567   EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
1568   EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
1569 
1570   DeclarationMatcher DefinitionOfObjCMethodA =
1571     objcMethodDecl(hasName("a"), isDefinition());
1572   EXPECT_TRUE(matchesObjC("@interface A @end "
1573                           "@implementation A; -(void)a {} @end",
1574                           DefinitionOfObjCMethodA));
1575   EXPECT_TRUE(notMatchesObjC("@interface A; - (void)a; @end",
1576                              DefinitionOfObjCMethodA));
1577 }
1578 
TEST(Matcher,HandlesNullQualTypes)1579 TEST(Matcher, HandlesNullQualTypes) {
1580   // FIXME: Add a Type matcher so we can replace uses of this
1581   // variable with Type(True())
1582   const TypeMatcher AnyType = anything();
1583 
1584   // We don't really care whether this matcher succeeds; we're testing that
1585   // it completes without crashing.
1586   EXPECT_TRUE(matches(
1587     "struct A { };"
1588       "template <typename T>"
1589       "void f(T t) {"
1590       "  T local_t(t /* this becomes a null QualType in the AST */);"
1591       "}"
1592       "void g() {"
1593       "  f(0);"
1594       "}",
1595     expr(hasType(TypeMatcher(
1596       anyOf(
1597         TypeMatcher(hasDeclaration(anything())),
1598         pointsTo(AnyType),
1599         references(AnyType)
1600         // Other QualType matchers should go here.
1601       ))))));
1602 }
1603 
TEST(ObjCIvarRefExprMatcher,IvarExpr)1604 TEST(ObjCIvarRefExprMatcher, IvarExpr) {
1605   std::string ObjCString =
1606     "@interface A @end "
1607     "@implementation A { A *x; } - (void) func { x = 0; } @end";
1608   EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr()));
1609   EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr(
1610         hasDeclaration(namedDecl(hasName("x"))))));
1611   EXPECT_FALSE(matchesObjC(ObjCString, objcIvarRefExpr(
1612         hasDeclaration(namedDecl(hasName("y"))))));
1613 }
1614 
TEST(BlockExprMatcher,BlockExpr)1615 TEST(BlockExprMatcher, BlockExpr) {
1616   EXPECT_TRUE(matchesObjC("void f() { ^{}(); }", blockExpr()));
1617 }
1618 
TEST(StatementCountIs,FindsNoStatementsInAnEmptyCompoundStatement)1619 TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
1620   EXPECT_TRUE(matches("void f() { }",
1621                       compoundStmt(statementCountIs(0))));
1622   EXPECT_TRUE(notMatches("void f() {}",
1623                          compoundStmt(statementCountIs(1))));
1624 }
1625 
TEST(StatementCountIs,AppearsToMatchOnlyOneCount)1626 TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
1627   EXPECT_TRUE(matches("void f() { 1; }",
1628                       compoundStmt(statementCountIs(1))));
1629   EXPECT_TRUE(notMatches("void f() { 1; }",
1630                          compoundStmt(statementCountIs(0))));
1631   EXPECT_TRUE(notMatches("void f() { 1; }",
1632                          compoundStmt(statementCountIs(2))));
1633 }
1634 
TEST(StatementCountIs,WorksWithMultipleStatements)1635 TEST(StatementCountIs, WorksWithMultipleStatements) {
1636   EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
1637                       compoundStmt(statementCountIs(3))));
1638 }
1639 
TEST(StatementCountIs,WorksWithNestedCompoundStatements)1640 TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
1641   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1642                       compoundStmt(statementCountIs(1))));
1643   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1644                       compoundStmt(statementCountIs(2))));
1645   EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
1646                          compoundStmt(statementCountIs(3))));
1647   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
1648                       compoundStmt(statementCountIs(4))));
1649 }
1650 
TEST(Member,WorksInSimplestCase)1651 TEST(Member, WorksInSimplestCase) {
1652   EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
1653                       memberExpr(member(hasName("first")))));
1654 }
1655 
TEST(Member,DoesNotMatchTheBaseExpression)1656 TEST(Member, DoesNotMatchTheBaseExpression) {
1657   // Don't pick out the wrong part of the member expression, this should
1658   // be checking the member (name) only.
1659   EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
1660                          memberExpr(member(hasName("first")))));
1661 }
1662 
TEST(Member,MatchesInMemberFunctionCall)1663 TEST(Member, MatchesInMemberFunctionCall) {
1664   EXPECT_TRUE(matches("void f() {"
1665                         "  struct { void first() {}; } s;"
1666                         "  s.first();"
1667                         "};",
1668                       memberExpr(member(hasName("first")))));
1669 }
1670 
TEST(Member,MatchesMember)1671 TEST(Member, MatchesMember) {
1672   EXPECT_TRUE(matches(
1673     "struct A { int i; }; void f() { A a; a.i = 2; }",
1674     memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
1675   EXPECT_TRUE(notMatches(
1676     "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
1677     memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
1678 }
1679 
TEST(Member,BitFields)1680 TEST(Member, BitFields) {
1681   EXPECT_TRUE(matches("class C { int a : 2; int b; };",
1682                       fieldDecl(isBitField(), hasName("a"))));
1683   EXPECT_TRUE(notMatches("class C { int a : 2; int b; };",
1684                          fieldDecl(isBitField(), hasName("b"))));
1685   EXPECT_TRUE(matches("class C { int a : 2; int b : 4; };",
1686                       fieldDecl(isBitField(), hasBitWidth(2), hasName("a"))));
1687 }
1688 
TEST(Member,InClassInitializer)1689 TEST(Member, InClassInitializer) {
1690   EXPECT_TRUE(
1691       matches("class C { int a = 2; int b; };",
1692               fieldDecl(hasInClassInitializer(integerLiteral(equals(2))),
1693                         hasName("a"))));
1694   EXPECT_TRUE(
1695       notMatches("class C { int a = 2; int b; };",
1696                  fieldDecl(hasInClassInitializer(anything()), hasName("b"))));
1697 }
1698 
TEST(Member,UnderstandsAccess)1699 TEST(Member, UnderstandsAccess) {
1700   EXPECT_TRUE(matches(
1701     "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
1702   EXPECT_TRUE(notMatches(
1703     "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
1704   EXPECT_TRUE(notMatches(
1705     "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
1706 
1707   EXPECT_TRUE(notMatches(
1708     "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
1709   EXPECT_TRUE(notMatches(
1710     "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
1711   EXPECT_TRUE(matches(
1712     "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
1713 
1714   EXPECT_TRUE(notMatches(
1715     "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
1716   EXPECT_TRUE(matches("class A { protected: int i; };",
1717                       fieldDecl(isProtected(), hasName("i"))));
1718   EXPECT_TRUE(notMatches(
1719     "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
1720 
1721   // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
1722   EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
1723   EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
1724   EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
1725 }
1726 
TEST(hasDynamicExceptionSpec,MatchesDynamicExceptionSpecifications)1727 TEST(hasDynamicExceptionSpec, MatchesDynamicExceptionSpecifications) {
1728   EXPECT_TRUE(notMatches("void f();", functionDecl(hasDynamicExceptionSpec())));
1729   EXPECT_TRUE(notMatches("void g() noexcept;",
1730                          functionDecl(hasDynamicExceptionSpec())));
1731   EXPECT_TRUE(notMatches("void h() noexcept(true);",
1732                          functionDecl(hasDynamicExceptionSpec())));
1733   EXPECT_TRUE(notMatches("void i() noexcept(false);",
1734                          functionDecl(hasDynamicExceptionSpec())));
1735   EXPECT_TRUE(
1736       matches("void j() throw();", functionDecl(hasDynamicExceptionSpec())));
1737   EXPECT_TRUE(
1738       matches("void k() throw(int);", functionDecl(hasDynamicExceptionSpec())));
1739   EXPECT_TRUE(
1740       matches("void l() throw(...);", functionDecl(hasDynamicExceptionSpec())));
1741 
1742   EXPECT_TRUE(notMatches("void f();", functionProtoType(hasDynamicExceptionSpec())));
1743   EXPECT_TRUE(notMatches("void g() noexcept;",
1744                          functionProtoType(hasDynamicExceptionSpec())));
1745   EXPECT_TRUE(notMatches("void h() noexcept(true);",
1746                          functionProtoType(hasDynamicExceptionSpec())));
1747   EXPECT_TRUE(notMatches("void i() noexcept(false);",
1748                          functionProtoType(hasDynamicExceptionSpec())));
1749   EXPECT_TRUE(
1750       matches("void j() throw();", functionProtoType(hasDynamicExceptionSpec())));
1751   EXPECT_TRUE(
1752       matches("void k() throw(int);", functionProtoType(hasDynamicExceptionSpec())));
1753   EXPECT_TRUE(
1754       matches("void l() throw(...);", functionProtoType(hasDynamicExceptionSpec())));
1755 }
1756 
TEST(HasObjectExpression,DoesNotMatchMember)1757 TEST(HasObjectExpression, DoesNotMatchMember) {
1758   EXPECT_TRUE(notMatches(
1759     "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
1760     memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
1761 }
1762 
TEST(HasObjectExpression,MatchesBaseOfVariable)1763 TEST(HasObjectExpression, MatchesBaseOfVariable) {
1764   EXPECT_TRUE(matches(
1765     "struct X { int m; }; void f(X x) { x.m; }",
1766     memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
1767   EXPECT_TRUE(matches(
1768     "struct X { int m; }; void f(X* x) { x->m; }",
1769     memberExpr(hasObjectExpression(
1770       hasType(pointsTo(recordDecl(hasName("X"))))))));
1771   EXPECT_TRUE(matches("template <class T> struct X { void f() { T t; t.m; } };",
1772                       cxxDependentScopeMemberExpr(hasObjectExpression(
1773                           declRefExpr(to(namedDecl(hasName("t"))))))));
1774   EXPECT_TRUE(
1775       matches("template <class T> struct X { void f() { T t; t->m; } };",
1776               cxxDependentScopeMemberExpr(hasObjectExpression(
1777                   declRefExpr(to(namedDecl(hasName("t"))))))));
1778 }
1779 
TEST(HasObjectExpression,MatchesBaseOfMemberFunc)1780 TEST(HasObjectExpression, MatchesBaseOfMemberFunc) {
1781   EXPECT_TRUE(matches(
1782       "struct X { void f(); }; void g(X x) { x.f(); }",
1783       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
1784   EXPECT_TRUE(matches("struct X { template <class T> void f(); };"
1785                       "template <class T> void g(X x) { x.f<T>(); }",
1786                       unresolvedMemberExpr(hasObjectExpression(
1787                           hasType(recordDecl(hasName("X")))))));
1788   EXPECT_TRUE(matches("template <class T> void f(T t) { t.g(); }",
1789                       cxxDependentScopeMemberExpr(hasObjectExpression(
1790                           declRefExpr(to(namedDecl(hasName("t"))))))));
1791 }
1792 
TEST(HasObjectExpression,MatchesObjectExpressionOfImplicitlyFormedMemberExpression)1793 TEST(HasObjectExpression,
1794      MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
1795   EXPECT_TRUE(matches(
1796     "class X {}; struct S { X m; void f() { this->m; } };",
1797     memberExpr(hasObjectExpression(
1798       hasType(pointsTo(recordDecl(hasName("S"))))))));
1799   EXPECT_TRUE(matches(
1800     "class X {}; struct S { X m; void f() { m; } };",
1801     memberExpr(hasObjectExpression(
1802       hasType(pointsTo(recordDecl(hasName("S"))))))));
1803 }
1804 
TEST(Field,DoesNotMatchNonFieldMembers)1805 TEST(Field, DoesNotMatchNonFieldMembers) {
1806   EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
1807   EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
1808   EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
1809   EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
1810 }
1811 
TEST(Field,MatchesField)1812 TEST(Field, MatchesField) {
1813   EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
1814 }
1815 
TEST(IsVolatileQualified,QualifiersMatch)1816 TEST(IsVolatileQualified, QualifiersMatch) {
1817   EXPECT_TRUE(matches("volatile int i = 42;",
1818                       varDecl(hasType(isVolatileQualified()))));
1819   EXPECT_TRUE(notMatches("volatile int *i;",
1820                          varDecl(hasType(isVolatileQualified()))));
1821   EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
1822                       varDecl(hasType(isVolatileQualified()))));
1823 }
1824 
TEST(IsConstQualified,MatchesConstInt)1825 TEST(IsConstQualified, MatchesConstInt) {
1826   EXPECT_TRUE(matches("const int i = 42;",
1827                       varDecl(hasType(isConstQualified()))));
1828 }
1829 
TEST(IsConstQualified,MatchesConstPointer)1830 TEST(IsConstQualified, MatchesConstPointer) {
1831   EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
1832                       varDecl(hasType(isConstQualified()))));
1833 }
1834 
TEST(IsConstQualified,MatchesThroughTypedef)1835 TEST(IsConstQualified, MatchesThroughTypedef) {
1836   EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
1837                       varDecl(hasType(isConstQualified()))));
1838   EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
1839                       varDecl(hasType(isConstQualified()))));
1840 }
1841 
TEST(IsConstQualified,DoesNotMatchInappropriately)1842 TEST(IsConstQualified, DoesNotMatchInappropriately) {
1843   EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
1844                          varDecl(hasType(isConstQualified()))));
1845   EXPECT_TRUE(notMatches("int const* p;",
1846                          varDecl(hasType(isConstQualified()))));
1847 }
1848 
TEST(DeclCount,DeclCountIsCorrect)1849 TEST(DeclCount, DeclCountIsCorrect) {
1850   EXPECT_TRUE(matches("void f() {int i,j;}",
1851                       declStmt(declCountIs(2))));
1852   EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
1853                          declStmt(declCountIs(3))));
1854   EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
1855                          declStmt(declCountIs(3))));
1856 }
1857 
1858 
TEST(EachOf,TriggersForEachMatch)1859 TEST(EachOf, TriggersForEachMatch) {
1860   EXPECT_TRUE(matchAndVerifyResultTrue(
1861     "class A { int a; int b; };",
1862     recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1863                       has(fieldDecl(hasName("b")).bind("v")))),
1864     std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
1865 }
1866 
TEST(EachOf,BehavesLikeAnyOfUnlessBothMatch)1867 TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
1868   EXPECT_TRUE(matchAndVerifyResultTrue(
1869     "class A { int a; int c; };",
1870     recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1871                       has(fieldDecl(hasName("b")).bind("v")))),
1872     std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
1873   EXPECT_TRUE(matchAndVerifyResultTrue(
1874     "class A { int c; int b; };",
1875     recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1876                       has(fieldDecl(hasName("b")).bind("v")))),
1877     std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
1878   EXPECT_TRUE(notMatches(
1879     "class A { int c; int d; };",
1880     recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1881                       has(fieldDecl(hasName("b")).bind("v"))))));
1882 }
1883 
TEST(Optionally,SubmatchersDoNotMatch)1884 TEST(Optionally, SubmatchersDoNotMatch) {
1885   EXPECT_TRUE(matchAndVerifyResultFalse(
1886       "class A { int a; int b; };",
1887       recordDecl(optionally(has(fieldDecl(hasName("c")).bind("v")),
1888                             has(fieldDecl(hasName("d")).bind("v")))),
1889       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v")));
1890 }
1891 
TEST(Optionally,SubmatchersMatch)1892 TEST(Optionally, SubmatchersMatch) {
1893   EXPECT_TRUE(matchAndVerifyResultTrue(
1894       "class A { int a; int c; };",
1895       recordDecl(optionally(has(fieldDecl(hasName("a")).bind("v")),
1896                             has(fieldDecl(hasName("b")).bind("v")))),
1897       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
1898   EXPECT_TRUE(matchAndVerifyResultTrue(
1899       "class A { int c; int b; };",
1900       recordDecl(optionally(has(fieldDecl(hasName("c")).bind("v")),
1901                             has(fieldDecl(hasName("b")).bind("v")))),
1902       std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
1903 }
1904 
TEST(IsTemplateInstantiation,MatchesImplicitClassTemplateInstantiation)1905 TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
1906   // Make sure that we can both match the class by name (::X) and by the type
1907   // the template was instantiated with (via a field).
1908 
1909   EXPECT_TRUE(matches(
1910     "template <typename T> class X {}; class A {}; X<A> x;",
1911     cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1912 
1913   EXPECT_TRUE(matches(
1914     "template <typename T> class X { T t; }; class A {}; X<A> x;",
1915     cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
1916       fieldDecl(hasType(recordDecl(hasName("A"))))))));
1917 }
1918 
TEST(IsTemplateInstantiation,MatchesImplicitFunctionTemplateInstantiation)1919 TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
1920   EXPECT_TRUE(matches(
1921     "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
1922     functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
1923                  isTemplateInstantiation())));
1924 }
1925 
TEST(IsTemplateInstantiation,MatchesExplicitClassTemplateInstantiation)1926 TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
1927   EXPECT_TRUE(matches(
1928     "template <typename T> class X { T t; }; class A {};"
1929       "template class X<A>;",
1930     cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
1931       fieldDecl(hasType(recordDecl(hasName("A"))))))));
1932 
1933   // Make sure that we match the instantiation instead of the template
1934   // definition by checking whether the member function is present.
1935   EXPECT_TRUE(
1936       matches("template <typename T> class X { void f() { T t; } };"
1937               "extern template class X<int>;",
1938               cxxRecordDecl(isTemplateInstantiation(),
1939                             unless(hasDescendant(varDecl(hasName("t")))))));
1940 }
1941 
TEST(IsTemplateInstantiation,MatchesInstantiationOfPartiallySpecializedClassTemplate)1942 TEST(IsTemplateInstantiation,
1943      MatchesInstantiationOfPartiallySpecializedClassTemplate) {
1944   EXPECT_TRUE(matches(
1945     "template <typename T> class X {};"
1946       "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
1947     cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1948 }
1949 
TEST(IsTemplateInstantiation,MatchesInstantiationOfClassTemplateNestedInNonTemplate)1950 TEST(IsTemplateInstantiation,
1951      MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
1952   EXPECT_TRUE(matches(
1953     "class A {};"
1954       "class X {"
1955       "  template <typename U> class Y { U u; };"
1956       "  Y<A> y;"
1957       "};",
1958     cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
1959 }
1960 
TEST(IsTemplateInstantiation,DoesNotMatchInstantiationsInsideOfInstantiation)1961 TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
1962   // FIXME: Figure out whether this makes sense. It doesn't affect the
1963   // normal use case as long as the uppermost instantiation always is marked
1964   // as template instantiation, but it might be confusing as a predicate.
1965   EXPECT_TRUE(matches(
1966     "class A {};"
1967       "template <typename T> class X {"
1968       "  template <typename U> class Y { U u; };"
1969       "  Y<T> y;"
1970       "}; X<A> x;",
1971     cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
1972 }
1973 
TEST(IsTemplateInstantiation,DoesNotMatchExplicitClassTemplateSpecialization)1974 TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
1975   EXPECT_TRUE(notMatches(
1976     "template <typename T> class X {}; class A {};"
1977       "template <> class X<A> {}; X<A> x;",
1978     cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
1979 }
1980 
TEST(IsTemplateInstantiation,DoesNotMatchNonTemplate)1981 TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
1982   EXPECT_TRUE(notMatches(
1983     "class A {}; class Y { A a; };",
1984     cxxRecordDecl(isTemplateInstantiation())));
1985 }
1986 
TEST(IsInstantiated,MatchesInstantiation)1987 TEST(IsInstantiated, MatchesInstantiation) {
1988   EXPECT_TRUE(
1989     matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
1990             cxxRecordDecl(isInstantiated())));
1991 }
1992 
TEST(IsInstantiated,NotMatchesDefinition)1993 TEST(IsInstantiated, NotMatchesDefinition) {
1994   EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
1995                          cxxRecordDecl(isInstantiated())));
1996 }
1997 
TEST(IsInTemplateInstantiation,MatchesInstantiationStmt)1998 TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
1999   EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
2000                         "class Y { A<int> a; }; Y y;",
2001                       declStmt(isInTemplateInstantiation())));
2002 }
2003 
TEST(IsInTemplateInstantiation,NotMatchesDefinitionStmt)2004 TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
2005   EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
2006                          declStmt(isInTemplateInstantiation())));
2007 }
2008 
TEST(IsInstantiated,MatchesFunctionInstantiation)2009 TEST(IsInstantiated, MatchesFunctionInstantiation) {
2010   EXPECT_TRUE(
2011     matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
2012             functionDecl(isInstantiated())));
2013 }
2014 
TEST(IsInstantiated,NotMatchesFunctionDefinition)2015 TEST(IsInstantiated, NotMatchesFunctionDefinition) {
2016   EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
2017                          varDecl(isInstantiated())));
2018 }
2019 
TEST(IsInTemplateInstantiation,MatchesFunctionInstantiationStmt)2020 TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
2021   EXPECT_TRUE(
2022     matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
2023             declStmt(isInTemplateInstantiation())));
2024 }
2025 
TEST(IsInTemplateInstantiation,NotMatchesFunctionDefinitionStmt)2026 TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
2027   EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
2028                          declStmt(isInTemplateInstantiation())));
2029 }
2030 
TEST(IsInTemplateInstantiation,Sharing)2031 TEST(IsInTemplateInstantiation, Sharing) {
2032   auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
2033   // FIXME: Node sharing is an implementation detail, exposing it is ugly
2034   // and makes the matcher behave in non-obvious ways.
2035   EXPECT_TRUE(notMatches(
2036     "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
2037     Matcher));
2038   EXPECT_TRUE(matches(
2039     "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
2040     Matcher));
2041 }
2042 
TEST(IsInstantiationDependent,MatchesNonValueTypeDependent)2043 TEST(IsInstantiationDependent, MatchesNonValueTypeDependent) {
2044   EXPECT_TRUE(matches(
2045       "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
2046       expr(isInstantiationDependent())));
2047 }
2048 
TEST(IsInstantiationDependent,MatchesValueDependent)2049 TEST(IsInstantiationDependent, MatchesValueDependent) {
2050   EXPECT_TRUE(matches("template<int T> int f() { return T; }",
2051                       expr(isInstantiationDependent())));
2052 }
2053 
TEST(IsInstantiationDependent,MatchesTypeDependent)2054 TEST(IsInstantiationDependent, MatchesTypeDependent) {
2055   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
2056                       expr(isInstantiationDependent())));
2057 }
2058 
TEST(IsTypeDependent,MatchesTypeDependent)2059 TEST(IsTypeDependent, MatchesTypeDependent) {
2060   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
2061                       expr(isTypeDependent())));
2062 }
2063 
TEST(IsTypeDependent,NotMatchesValueDependent)2064 TEST(IsTypeDependent, NotMatchesValueDependent) {
2065   EXPECT_TRUE(notMatches("template<int T> int f() { return T; }",
2066                          expr(isTypeDependent())));
2067 }
2068 
TEST(IsValueDependent,MatchesValueDependent)2069 TEST(IsValueDependent, MatchesValueDependent) {
2070   EXPECT_TRUE(matches("template<int T> int f() { return T; }",
2071                       expr(isValueDependent())));
2072 }
2073 
TEST(IsValueDependent,MatchesTypeDependent)2074 TEST(IsValueDependent, MatchesTypeDependent) {
2075   EXPECT_TRUE(matches("template<typename T> T f() { return T(); }",
2076                       expr(isValueDependent())));
2077 }
2078 
TEST(IsValueDependent,MatchesInstantiationDependent)2079 TEST(IsValueDependent, MatchesInstantiationDependent) {
2080   EXPECT_TRUE(matches(
2081       "template<typename T> void f() { (void) sizeof(sizeof(T() + T())); }",
2082       expr(isValueDependent())));
2083 }
2084 
TEST(IsExplicitTemplateSpecialization,DoesNotMatchPrimaryTemplate)2085 TEST(IsExplicitTemplateSpecialization,
2086      DoesNotMatchPrimaryTemplate) {
2087   EXPECT_TRUE(notMatches(
2088     "template <typename T> class X {};",
2089     cxxRecordDecl(isExplicitTemplateSpecialization())));
2090   EXPECT_TRUE(notMatches(
2091     "template <typename T> void f(T t);",
2092     functionDecl(isExplicitTemplateSpecialization())));
2093 }
2094 
TEST(IsExplicitTemplateSpecialization,DoesNotMatchExplicitTemplateInstantiations)2095 TEST(IsExplicitTemplateSpecialization,
2096      DoesNotMatchExplicitTemplateInstantiations) {
2097   EXPECT_TRUE(notMatches(
2098     "template <typename T> class X {};"
2099       "template class X<int>; extern template class X<long>;",
2100     cxxRecordDecl(isExplicitTemplateSpecialization())));
2101   EXPECT_TRUE(notMatches(
2102     "template <typename T> void f(T t) {}"
2103       "template void f(int t); extern template void f(long t);",
2104     functionDecl(isExplicitTemplateSpecialization())));
2105 }
2106 
TEST(IsExplicitTemplateSpecialization,DoesNotMatchImplicitTemplateInstantiations)2107 TEST(IsExplicitTemplateSpecialization,
2108      DoesNotMatchImplicitTemplateInstantiations) {
2109   EXPECT_TRUE(notMatches(
2110     "template <typename T> class X {}; X<int> x;",
2111     cxxRecordDecl(isExplicitTemplateSpecialization())));
2112   EXPECT_TRUE(notMatches(
2113     "template <typename T> void f(T t); void g() { f(10); }",
2114     functionDecl(isExplicitTemplateSpecialization())));
2115 }
2116 
TEST(IsExplicitTemplateSpecialization,MatchesExplicitTemplateSpecializations)2117 TEST(IsExplicitTemplateSpecialization,
2118      MatchesExplicitTemplateSpecializations) {
2119   EXPECT_TRUE(matches(
2120     "template <typename T> class X {};"
2121       "template<> class X<int> {};",
2122     cxxRecordDecl(isExplicitTemplateSpecialization())));
2123   EXPECT_TRUE(matches(
2124     "template <typename T> void f(T t) {}"
2125       "template<> void f(int t) {}",
2126     functionDecl(isExplicitTemplateSpecialization())));
2127 }
2128 
TEST(TypeMatching,MatchesNoReturn)2129 TEST(TypeMatching, MatchesNoReturn) {
2130   EXPECT_TRUE(notMatches("void func();", functionDecl(isNoReturn())));
2131   EXPECT_TRUE(notMatches("void func() {}", functionDecl(isNoReturn())));
2132 
2133   EXPECT_TRUE(notMatchesC("void func();", functionDecl(isNoReturn())));
2134   EXPECT_TRUE(notMatchesC("void func() {}", functionDecl(isNoReturn())));
2135 
2136   EXPECT_TRUE(
2137       notMatches("struct S { void func(); };", functionDecl(isNoReturn())));
2138   EXPECT_TRUE(
2139       notMatches("struct S { void func() {} };", functionDecl(isNoReturn())));
2140 
2141   EXPECT_TRUE(notMatches("struct S { static void func(); };",
2142                          functionDecl(isNoReturn())));
2143   EXPECT_TRUE(notMatches("struct S { static void func() {} };",
2144                          functionDecl(isNoReturn())));
2145 
2146   EXPECT_TRUE(notMatches("struct S { S(); };", functionDecl(isNoReturn())));
2147   EXPECT_TRUE(notMatches("struct S { S() {} };", functionDecl(isNoReturn())));
2148 
2149   // ---
2150 
2151   EXPECT_TRUE(matches("[[noreturn]] void func();", functionDecl(isNoReturn())));
2152   EXPECT_TRUE(
2153       matches("[[noreturn]] void func() {}", functionDecl(isNoReturn())));
2154 
2155   EXPECT_TRUE(matches("struct S { [[noreturn]] void func(); };",
2156                       functionDecl(isNoReturn())));
2157   EXPECT_TRUE(matches("struct S { [[noreturn]] void func() {} };",
2158                       functionDecl(isNoReturn())));
2159 
2160   EXPECT_TRUE(matches("struct S { [[noreturn]] static void func(); };",
2161                       functionDecl(isNoReturn())));
2162   EXPECT_TRUE(matches("struct S { [[noreturn]] static void func() {} };",
2163                       functionDecl(isNoReturn())));
2164 
2165   EXPECT_TRUE(
2166       matches("struct S { [[noreturn]] S(); };", functionDecl(isNoReturn())));
2167   EXPECT_TRUE(matches("struct S { [[noreturn]] S() {} };",
2168                       functionDecl(isNoReturn())));
2169 
2170   // ---
2171 
2172   EXPECT_TRUE(matches("__attribute__((noreturn)) void func();",
2173                       functionDecl(isNoReturn())));
2174   EXPECT_TRUE(matches("__attribute__((noreturn)) void func() {}",
2175                       functionDecl(isNoReturn())));
2176 
2177   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func(); };",
2178                       functionDecl(isNoReturn())));
2179   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func() {} };",
2180                       functionDecl(isNoReturn())));
2181 
2182   EXPECT_TRUE(
2183       matches("struct S { __attribute__((noreturn)) static void func(); };",
2184               functionDecl(isNoReturn())));
2185   EXPECT_TRUE(
2186       matches("struct S { __attribute__((noreturn)) static void func() {} };",
2187               functionDecl(isNoReturn())));
2188 
2189   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S(); };",
2190                       functionDecl(isNoReturn())));
2191   EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S() {} };",
2192                       functionDecl(isNoReturn())));
2193 
2194   // ---
2195 
2196   EXPECT_TRUE(matchesC("__attribute__((noreturn)) void func();",
2197                       functionDecl(isNoReturn())));
2198   EXPECT_TRUE(matchesC("__attribute__((noreturn)) void func() {}",
2199                       functionDecl(isNoReturn())));
2200 
2201   EXPECT_TRUE(matchesC("_Noreturn void func();",
2202                       functionDecl(isNoReturn())));
2203   EXPECT_TRUE(matchesC("_Noreturn void func() {}",
2204                       functionDecl(isNoReturn())));
2205 }
2206 
TEST(TypeMatching,MatchesBool)2207 TEST(TypeMatching, MatchesBool) {
2208   EXPECT_TRUE(matches("struct S { bool func(); };",
2209                       cxxMethodDecl(returns(booleanType()))));
2210   EXPECT_TRUE(notMatches("struct S { void func(); };",
2211                          cxxMethodDecl(returns(booleanType()))));
2212 }
2213 
TEST(TypeMatching,MatchesVoid)2214 TEST(TypeMatching, MatchesVoid) {
2215   EXPECT_TRUE(matches("struct S { void func(); };",
2216                       cxxMethodDecl(returns(voidType()))));
2217 }
2218 
TEST(TypeMatching,MatchesRealFloats)2219 TEST(TypeMatching, MatchesRealFloats) {
2220   EXPECT_TRUE(matches("struct S { float func(); };",
2221                       cxxMethodDecl(returns(realFloatingPointType()))));
2222   EXPECT_TRUE(notMatches("struct S { int func(); };",
2223                          cxxMethodDecl(returns(realFloatingPointType()))));
2224   EXPECT_TRUE(matches("struct S { long double func(); };",
2225                       cxxMethodDecl(returns(realFloatingPointType()))));
2226 }
2227 
TEST(TypeMatching,MatchesArrayTypes)2228 TEST(TypeMatching, MatchesArrayTypes) {
2229   EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
2230   EXPECT_TRUE(matches("int a[42];", arrayType()));
2231   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
2232 
2233   EXPECT_TRUE(notMatches("struct A {}; A a[7];",
2234                          arrayType(hasElementType(builtinType()))));
2235 
2236   EXPECT_TRUE(matches(
2237     "int const a[] = { 2, 3 };",
2238     qualType(arrayType(hasElementType(builtinType())))));
2239   EXPECT_TRUE(matches(
2240     "int const a[] = { 2, 3 };",
2241     qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
2242   EXPECT_TRUE(matches(
2243     "typedef const int T; T x[] = { 1, 2 };",
2244     qualType(isConstQualified(), arrayType())));
2245 
2246   EXPECT_TRUE(notMatches(
2247     "int a[] = { 2, 3 };",
2248     qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
2249   EXPECT_TRUE(notMatches(
2250     "int a[] = { 2, 3 };",
2251     qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
2252   EXPECT_TRUE(notMatches(
2253     "int const a[] = { 2, 3 };",
2254     qualType(arrayType(hasElementType(builtinType())),
2255              unless(isConstQualified()))));
2256 
2257   EXPECT_TRUE(matches("int a[2];",
2258                       constantArrayType(hasElementType(builtinType()))));
2259   EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
2260 }
2261 
TEST(TypeMatching,DecayedType)2262 TEST(TypeMatching, DecayedType) {
2263   EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
2264   EXPECT_TRUE(notMatches("int i[7];", decayedType()));
2265 }
2266 
TEST(TypeMatching,MatchesComplexTypes)2267 TEST(TypeMatching, MatchesComplexTypes) {
2268   EXPECT_TRUE(matches("_Complex float f;", complexType()));
2269   EXPECT_TRUE(matches(
2270     "_Complex float f;",
2271     complexType(hasElementType(builtinType()))));
2272   EXPECT_TRUE(notMatches(
2273     "_Complex float f;",
2274     complexType(hasElementType(isInteger()))));
2275 }
2276 
TEST(NS,Anonymous)2277 TEST(NS, Anonymous) {
2278   EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
2279   EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
2280 }
2281 
TEST(DeclarationMatcher,InStdNamespace)2282 TEST(DeclarationMatcher, InStdNamespace) {
2283   EXPECT_TRUE(notMatches("class vector {};"
2284                          "namespace foo {"
2285                          "  class vector {};"
2286                          "}"
2287                          "namespace foo {"
2288                          "  namespace std {"
2289                          "    class vector {};"
2290                          "  }"
2291                          "}",
2292                          cxxRecordDecl(hasName("vector"), isInStdNamespace())));
2293 
2294   EXPECT_TRUE(matches("namespace std {"
2295                       "  class vector {};"
2296                       "}",
2297                       cxxRecordDecl(hasName("vector"), isInStdNamespace())));
2298   EXPECT_TRUE(matches("namespace std {"
2299                       "  inline namespace __1 {"
2300                       "    class vector {};"
2301                       "  }"
2302                       "}",
2303                       cxxRecordDecl(hasName("vector"), isInStdNamespace())));
2304   EXPECT_TRUE(notMatches("namespace std {"
2305                          "  inline namespace __1 {"
2306                          "    inline namespace __fs {"
2307                          "      namespace filesystem {"
2308                          "        inline namespace v1 {"
2309                          "          class path {};"
2310                          "        }"
2311                          "      }"
2312                          "    }"
2313                          "  }"
2314                          "}",
2315                          cxxRecordDecl(hasName("path"), isInStdNamespace())));
2316   EXPECT_TRUE(
2317       matches("namespace std {"
2318               "  inline namespace __1 {"
2319               "    inline namespace __fs {"
2320               "      namespace filesystem {"
2321               "        inline namespace v1 {"
2322               "          class path {};"
2323               "        }"
2324               "      }"
2325               "    }"
2326               "  }"
2327               "}",
2328               cxxRecordDecl(hasName("path"),
2329                             hasAncestor(namespaceDecl(hasName("filesystem"),
2330                                                       isInStdNamespace())))));
2331 }
2332 
TEST(EqualsBoundNodeMatcher,QualType)2333 TEST(EqualsBoundNodeMatcher, QualType) {
2334   EXPECT_TRUE(matches(
2335     "int i = 1;", varDecl(hasType(qualType().bind("type")),
2336                           hasInitializer(ignoringParenImpCasts(
2337                             hasType(qualType(equalsBoundNode("type"))))))));
2338   EXPECT_TRUE(notMatches("int i = 1.f;",
2339                          varDecl(hasType(qualType().bind("type")),
2340                                  hasInitializer(ignoringParenImpCasts(hasType(
2341                                    qualType(equalsBoundNode("type"))))))));
2342 }
2343 
TEST(EqualsBoundNodeMatcher,NonMatchingTypes)2344 TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
2345   EXPECT_TRUE(notMatches(
2346     "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
2347                           hasInitializer(ignoringParenImpCasts(
2348                             hasType(qualType(equalsBoundNode("type"))))))));
2349 }
2350 
TEST(EqualsBoundNodeMatcher,Stmt)2351 TEST(EqualsBoundNodeMatcher, Stmt) {
2352   EXPECT_TRUE(
2353     matches("void f() { if(true) {} }",
2354             stmt(allOf(ifStmt().bind("if"),
2355                        hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
2356 
2357   EXPECT_TRUE(notMatches(
2358     "void f() { if(true) { if (true) {} } }",
2359     stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
2360 }
2361 
TEST(EqualsBoundNodeMatcher,Decl)2362 TEST(EqualsBoundNodeMatcher, Decl) {
2363   EXPECT_TRUE(matches(
2364     "class X { class Y {}; };",
2365     decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
2366                hasParent(decl(has(decl(equalsBoundNode("record")))))))));
2367 
2368   EXPECT_TRUE(notMatches("class X { class Y {}; };",
2369                          decl(allOf(recordDecl(hasName("::X")).bind("record"),
2370                                     has(decl(equalsBoundNode("record")))))));
2371 }
2372 
TEST(EqualsBoundNodeMatcher,Type)2373 TEST(EqualsBoundNodeMatcher, Type) {
2374   EXPECT_TRUE(matches(
2375     "class X { int a; int b; };",
2376     recordDecl(
2377       has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2378       has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
2379 
2380   EXPECT_TRUE(notMatches(
2381     "class X { int a; double b; };",
2382     recordDecl(
2383       has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2384       has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
2385 }
2386 
TEST(EqualsBoundNodeMatcher,UsingForEachDescendant)2387 TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
2388   EXPECT_TRUE(matchAndVerifyResultTrue(
2389     "int f() {"
2390       "  if (1) {"
2391       "    int i = 9;"
2392       "  }"
2393       "  int j = 10;"
2394       "  {"
2395       "    float k = 9.0;"
2396       "  }"
2397       "  return 0;"
2398       "}",
2399     // Look for variable declarations within functions whose type is the same
2400     // as the function return type.
2401     functionDecl(returns(qualType().bind("type")),
2402                  forEachDescendant(varDecl(hasType(
2403                    qualType(equalsBoundNode("type")))).bind("decl"))),
2404     // Only i and j should match, not k.
2405     std::make_unique<VerifyIdIsBoundTo<VarDecl>>("decl", 2)));
2406 }
2407 
TEST(EqualsBoundNodeMatcher,FiltersMatchedCombinations)2408 TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
2409   EXPECT_TRUE(matchAndVerifyResultTrue(
2410     "void f() {"
2411       "  int x;"
2412       "  double d;"
2413       "  x = d + x - d + x;"
2414       "}",
2415     functionDecl(
2416       hasName("f"), forEachDescendant(varDecl().bind("d")),
2417       forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
2418     std::make_unique<VerifyIdIsBoundTo<VarDecl>>("d", 5)));
2419 }
2420 
TEST(EqualsBoundNodeMatcher,UnlessDescendantsOfAncestorsMatch)2421 TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
2422   EXPECT_TRUE(matchAndVerifyResultTrue(
2423     "struct StringRef { int size() const; const char* data() const; };"
2424       "void f(StringRef v) {"
2425       "  v.data();"
2426       "}",
2427     cxxMemberCallExpr(
2428       callee(cxxMethodDecl(hasName("data"))),
2429       on(declRefExpr(to(
2430         varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
2431       unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
2432         callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
2433         on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
2434       .bind("data"),
2435     std::make_unique<VerifyIdIsBoundTo<Expr>>("data", 1)));
2436 
2437   EXPECT_FALSE(matches(
2438     "struct StringRef { int size() const; const char* data() const; };"
2439       "void f(StringRef v) {"
2440       "  v.data();"
2441       "  v.size();"
2442       "}",
2443     cxxMemberCallExpr(
2444       callee(cxxMethodDecl(hasName("data"))),
2445       on(declRefExpr(to(
2446         varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
2447       unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
2448         callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
2449         on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
2450       .bind("data")));
2451 }
2452 
TEST(NullPointerConstants,Basic)2453 TEST(NullPointerConstants, Basic) {
2454   EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
2455                         "void *v1 = NULL;", expr(nullPointerConstant())));
2456   EXPECT_TRUE(matches("void *v2 = nullptr;", expr(nullPointerConstant())));
2457   EXPECT_TRUE(matches("void *v3 = __null;", expr(nullPointerConstant())));
2458   EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
2459   EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
2460   EXPECT_TRUE(matches("int i = 0;", expr(nullPointerConstant())));
2461 }
2462 
TEST(HasExternalFormalLinkage,Basic)2463 TEST(HasExternalFormalLinkage, Basic) {
2464   EXPECT_TRUE(matches("int a = 0;", namedDecl(hasExternalFormalLinkage())));
2465   EXPECT_TRUE(
2466       notMatches("static int a = 0;", namedDecl(hasExternalFormalLinkage())));
2467   EXPECT_TRUE(notMatches("static void f(void) { int a = 0; }",
2468                          namedDecl(hasExternalFormalLinkage())));
2469   EXPECT_TRUE(matches("void f(void) { int a = 0; }",
2470                       namedDecl(hasExternalFormalLinkage())));
2471 
2472   // Despite having internal semantic linkage, the anonymous namespace member
2473   // has external linkage because the member has a unique name in all
2474   // translation units.
2475   EXPECT_TRUE(matches("namespace { int a = 0; }",
2476                       namedDecl(hasExternalFormalLinkage())));
2477 }
2478 
TEST(HasDefaultArgument,Basic)2479 TEST(HasDefaultArgument, Basic) {
2480   EXPECT_TRUE(matches("void x(int val = 0) {}",
2481                       parmVarDecl(hasDefaultArgument())));
2482   EXPECT_TRUE(notMatches("void x(int val) {}",
2483                       parmVarDecl(hasDefaultArgument())));
2484 }
2485 
TEST(IsArray,Basic)2486 TEST(IsArray, Basic) {
2487   EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
2488                       cxxNewExpr(isArray())));
2489 }
2490 
TEST(HasArraySize,Basic)2491 TEST(HasArraySize, Basic) {
2492   EXPECT_TRUE(matches("struct MyClass {}; MyClass *p1 = new MyClass[10];",
2493                       cxxNewExpr(hasArraySize(integerLiteral(equals(10))))));
2494 }
2495 
TEST(HasDefinition,MatchesStructDefinition)2496 TEST(HasDefinition, MatchesStructDefinition) {
2497   EXPECT_TRUE(matches("struct x {};",
2498                       cxxRecordDecl(hasDefinition())));
2499   EXPECT_TRUE(notMatches("struct x;",
2500                       cxxRecordDecl(hasDefinition())));
2501 }
2502 
TEST(HasDefinition,MatchesClassDefinition)2503 TEST(HasDefinition, MatchesClassDefinition) {
2504   EXPECT_TRUE(matches("class x {};",
2505                       cxxRecordDecl(hasDefinition())));
2506   EXPECT_TRUE(notMatches("class x;",
2507                       cxxRecordDecl(hasDefinition())));
2508 }
2509 
TEST(HasDefinition,MatchesUnionDefinition)2510 TEST(HasDefinition, MatchesUnionDefinition) {
2511   EXPECT_TRUE(matches("union x {};",
2512                       cxxRecordDecl(hasDefinition())));
2513   EXPECT_TRUE(notMatches("union x;",
2514                       cxxRecordDecl(hasDefinition())));
2515 }
2516 
TEST(IsScopedEnum,MatchesScopedEnum)2517 TEST(IsScopedEnum, MatchesScopedEnum) {
2518   EXPECT_TRUE(matches("enum class X {};", enumDecl(isScoped())));
2519   EXPECT_TRUE(notMatches("enum X {};", enumDecl(isScoped())));
2520 }
2521 
TEST(HasTrailingReturn,MatchesTrailingReturn)2522 TEST(HasTrailingReturn, MatchesTrailingReturn) {
2523   EXPECT_TRUE(matches("auto Y() -> int { return 0; }",
2524                       functionDecl(hasTrailingReturn())));
2525   EXPECT_TRUE(matches("auto X() -> int;", functionDecl(hasTrailingReturn())));
2526   EXPECT_TRUE(notMatches("int X() { return 0; }",
2527                       functionDecl(hasTrailingReturn())));
2528   EXPECT_TRUE(notMatches("int X();", functionDecl(hasTrailingReturn())));
2529   EXPECT_TRUE(notMatchesC("void X();", functionDecl(hasTrailingReturn())));
2530 }
2531 
TEST(HasTrailingReturn,MatchesLambdaTrailingReturn)2532 TEST(HasTrailingReturn, MatchesLambdaTrailingReturn) {
2533   EXPECT_TRUE(matches(
2534           "auto lambda2 = [](double x, double y) -> double {return x + y;};",
2535           functionDecl(hasTrailingReturn())));
2536   EXPECT_TRUE(notMatches(
2537           "auto lambda2 = [](double x, double y) {return x + y;};",
2538           functionDecl(hasTrailingReturn())));
2539 }
2540 
TEST(IsAssignmentOperator,Basic)2541 TEST(IsAssignmentOperator, Basic) {
2542   StatementMatcher BinAsgmtOperator = binaryOperator(isAssignmentOperator());
2543   StatementMatcher CXXAsgmtOperator =
2544       cxxOperatorCallExpr(isAssignmentOperator());
2545 
2546   EXPECT_TRUE(matches("void x() { int a; a += 1; }", BinAsgmtOperator));
2547   EXPECT_TRUE(matches("void x() { int a; a = 2; }", BinAsgmtOperator));
2548   EXPECT_TRUE(matches("void x() { int a; a &= 3; }", BinAsgmtOperator));
2549   EXPECT_TRUE(matches("struct S { S& operator=(const S&); };"
2550                       "void x() { S s1, s2; s1 = s2; }",
2551                       CXXAsgmtOperator));
2552   EXPECT_TRUE(
2553       notMatches("void x() { int a; if(a == 0) return; }", BinAsgmtOperator));
2554 }
2555 
TEST(HasInit,Basic)2556 TEST(HasInit, Basic) {
2557   EXPECT_TRUE(
2558     matches("int x{0};",
2559             initListExpr(hasInit(0, expr()))));
2560   EXPECT_FALSE(
2561     matches("int x{0};",
2562             initListExpr(hasInit(1, expr()))));
2563   EXPECT_FALSE(
2564     matches("int x;",
2565             initListExpr(hasInit(0, expr()))));
2566 }
2567 
TEST(Matcher,isMain)2568 TEST(Matcher, isMain) {
2569   EXPECT_TRUE(
2570     matches("int main() {}", functionDecl(isMain())));
2571 
2572   EXPECT_TRUE(
2573     notMatches("int main2() {}", functionDecl(isMain())));
2574 }
2575 
TEST(OMPExecutableDirective,isStandaloneDirective)2576 TEST(OMPExecutableDirective, isStandaloneDirective) {
2577   auto Matcher = ompExecutableDirective(isStandaloneDirective());
2578 
2579   const std::string Source0 = R"(
2580 void x() {
2581 #pragma omp parallel
2582 ;
2583 })";
2584   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2585 
2586   const std::string Source1 = R"(
2587 void x() {
2588 #pragma omp taskyield
2589 })";
2590   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2591 }
2592 
TEST(Stmt,isOMPStructuredBlock)2593 TEST(Stmt, isOMPStructuredBlock) {
2594   const std::string Source0 = R"(
2595 void x() {
2596 #pragma omp parallel
2597 ;
2598 })";
2599   EXPECT_TRUE(
2600       matchesWithOpenMP(Source0, stmt(nullStmt(), isOMPStructuredBlock())));
2601 
2602   const std::string Source1 = R"(
2603 void x() {
2604 #pragma omp parallel
2605 {;}
2606 })";
2607   EXPECT_TRUE(
2608       notMatchesWithOpenMP(Source1, stmt(nullStmt(), isOMPStructuredBlock())));
2609   EXPECT_TRUE(
2610       matchesWithOpenMP(Source1, stmt(compoundStmt(), isOMPStructuredBlock())));
2611 }
2612 
TEST(OMPExecutableDirective,hasStructuredBlock)2613 TEST(OMPExecutableDirective, hasStructuredBlock) {
2614   const std::string Source0 = R"(
2615 void x() {
2616 #pragma omp parallel
2617 ;
2618 })";
2619   EXPECT_TRUE(matchesWithOpenMP(
2620       Source0, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
2621 
2622   const std::string Source1 = R"(
2623 void x() {
2624 #pragma omp parallel
2625 {;}
2626 })";
2627   EXPECT_TRUE(notMatchesWithOpenMP(
2628       Source1, ompExecutableDirective(hasStructuredBlock(nullStmt()))));
2629   EXPECT_TRUE(matchesWithOpenMP(
2630       Source1, ompExecutableDirective(hasStructuredBlock(compoundStmt()))));
2631 
2632   const std::string Source2 = R"(
2633 void x() {
2634 #pragma omp taskyield
2635 {;}
2636 })";
2637   EXPECT_TRUE(notMatchesWithOpenMP(
2638       Source2, ompExecutableDirective(hasStructuredBlock(anything()))));
2639 }
2640 
TEST(OMPExecutableDirective,hasClause)2641 TEST(OMPExecutableDirective, hasClause) {
2642   auto Matcher = ompExecutableDirective(hasAnyClause(anything()));
2643 
2644   const std::string Source0 = R"(
2645 void x() {
2646 ;
2647 })";
2648   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2649 
2650   const std::string Source1 = R"(
2651 void x() {
2652 #pragma omp parallel
2653 ;
2654 })";
2655   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2656 
2657   const std::string Source2 = R"(
2658 void x() {
2659 #pragma omp parallel default(none)
2660 ;
2661 })";
2662   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2663 
2664   const std::string Source3 = R"(
2665 void x() {
2666 #pragma omp parallel default(shared)
2667 ;
2668 })";
2669   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2670 
2671   const std::string Source4 = R"(
2672 void x(int x) {
2673 #pragma omp parallel num_threads(x)
2674 ;
2675 })";
2676   EXPECT_TRUE(matchesWithOpenMP(Source4, Matcher));
2677 }
2678 
TEST(OMPDefaultClause,isNoneKind)2679 TEST(OMPDefaultClause, isNoneKind) {
2680   auto Matcher =
2681       ompExecutableDirective(hasAnyClause(ompDefaultClause(isNoneKind())));
2682 
2683   const std::string Source0 = R"(
2684 void x() {
2685 ;
2686 })";
2687   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2688 
2689   const std::string Source1 = R"(
2690 void x() {
2691 #pragma omp parallel
2692 ;
2693 })";
2694   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2695 
2696   const std::string Source2 = R"(
2697 void x() {
2698 #pragma omp parallel default(none)
2699 ;
2700 })";
2701   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2702 
2703   const std::string Source3 = R"(
2704 void x() {
2705 #pragma omp parallel default(shared)
2706 ;
2707 })";
2708   EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
2709 
2710   const std::string Source4 = R"(
2711 void x(int x) {
2712 #pragma omp parallel num_threads(x)
2713 ;
2714 })";
2715   EXPECT_TRUE(notMatchesWithOpenMP(Source4, Matcher));
2716 }
2717 
TEST(OMPDefaultClause,isSharedKind)2718 TEST(OMPDefaultClause, isSharedKind) {
2719   auto Matcher =
2720       ompExecutableDirective(hasAnyClause(ompDefaultClause(isSharedKind())));
2721 
2722   const std::string Source0 = R"(
2723 void x() {
2724 ;
2725 })";
2726   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2727 
2728   const std::string Source1 = R"(
2729 void x() {
2730 #pragma omp parallel
2731 ;
2732 })";
2733   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2734 
2735   const std::string Source2 = R"(
2736 void x() {
2737 #pragma omp parallel default(shared)
2738 ;
2739 })";
2740   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2741 
2742   const std::string Source3 = R"(
2743 void x() {
2744 #pragma omp parallel default(none)
2745 ;
2746 })";
2747   EXPECT_TRUE(notMatchesWithOpenMP(Source3, Matcher));
2748 
2749   const std::string Source4 = R"(
2750 void x(int x) {
2751 #pragma omp parallel num_threads(x)
2752 ;
2753 })";
2754   EXPECT_TRUE(notMatchesWithOpenMP(Source4, Matcher));
2755 }
2756 
TEST(OMPExecutableDirective,isAllowedToContainClauseKind)2757 TEST(OMPExecutableDirective, isAllowedToContainClauseKind) {
2758   auto Matcher =
2759       ompExecutableDirective(isAllowedToContainClauseKind(OMPC_default));
2760 
2761   const std::string Source0 = R"(
2762 void x() {
2763 ;
2764 })";
2765   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2766 
2767   const std::string Source1 = R"(
2768 void x() {
2769 #pragma omp parallel
2770 ;
2771 })";
2772   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2773 
2774   const std::string Source2 = R"(
2775 void x() {
2776 #pragma omp parallel default(none)
2777 ;
2778 })";
2779   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2780 
2781   const std::string Source3 = R"(
2782 void x() {
2783 #pragma omp parallel default(shared)
2784 ;
2785 })";
2786   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2787 
2788   const std::string Source4 = R"(
2789 void x(int x) {
2790 #pragma omp parallel num_threads(x)
2791 ;
2792 })";
2793   EXPECT_TRUE(matchesWithOpenMP(Source4, Matcher));
2794 
2795   const std::string Source5 = R"(
2796 void x() {
2797 #pragma omp taskyield
2798 })";
2799   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
2800 
2801   const std::string Source6 = R"(
2802 void x() {
2803 #pragma omp task
2804 ;
2805 })";
2806   EXPECT_TRUE(matchesWithOpenMP(Source6, Matcher));
2807 }
2808 
2809 } // namespace ast_matchers
2810 } // namespace clang
2811