ASTMatchersTest.cpp revision 1b354b868c1aa227619d81e299fe6e384e1999b7
1//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "ASTMatchersTest.h" 11#include "clang/AST/PrettyPrinter.h" 12#include "clang/ASTMatchers/ASTMatchFinder.h" 13#include "clang/ASTMatchers/ASTMatchers.h" 14#include "clang/Tooling/Tooling.h" 15#include "gtest/gtest.h" 16 17namespace clang { 18namespace ast_matchers { 19 20#if GTEST_HAS_DEATH_TEST 21TEST(HasNameDeathTest, DiesOnEmptyName) { 22 ASSERT_DEBUG_DEATH({ 23 DeclarationMatcher HasEmptyName = recordDecl(hasName("")); 24 EXPECT_TRUE(notMatches("class X {};", HasEmptyName)); 25 }, ""); 26} 27 28TEST(HasNameDeathTest, DiesOnEmptyPattern) { 29 ASSERT_DEBUG_DEATH({ 30 DeclarationMatcher HasEmptyName = recordDecl(matchesName("")); 31 EXPECT_TRUE(notMatches("class X {};", HasEmptyName)); 32 }, ""); 33} 34 35TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) { 36 ASSERT_DEBUG_DEATH({ 37 DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom("")); 38 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty)); 39 }, ""); 40} 41#endif 42 43TEST(Decl, MatchesDeclarations) { 44 EXPECT_TRUE(notMatches("", decl(usingDecl()))); 45 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;", 46 decl(usingDecl()))); 47} 48 49TEST(NameableDeclaration, MatchesVariousDecls) { 50 DeclarationMatcher NamedX = namedDecl(hasName("X")); 51 EXPECT_TRUE(matches("typedef int X;", NamedX)); 52 EXPECT_TRUE(matches("int X;", NamedX)); 53 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX)); 54 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX)); 55 EXPECT_TRUE(matches("void foo() { int X; }", NamedX)); 56 EXPECT_TRUE(matches("namespace X { }", NamedX)); 57 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX)); 58 59 EXPECT_TRUE(notMatches("#define X 1", NamedX)); 60} 61 62TEST(NameableDeclaration, REMatchesVariousDecls) { 63 DeclarationMatcher NamedX = namedDecl(matchesName("::X")); 64 EXPECT_TRUE(matches("typedef int Xa;", NamedX)); 65 EXPECT_TRUE(matches("int Xb;", NamedX)); 66 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX)); 67 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX)); 68 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX)); 69 EXPECT_TRUE(matches("namespace Xij { }", NamedX)); 70 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX)); 71 72 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX)); 73 74 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no")); 75 EXPECT_TRUE(matches("int no_foo;", StartsWithNo)); 76 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo)); 77 78 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c")); 79 EXPECT_TRUE(matches("int abc;", Abc)); 80 EXPECT_TRUE(matches("int aFOObBARc;", Abc)); 81 EXPECT_TRUE(notMatches("int cab;", Abc)); 82 EXPECT_TRUE(matches("int cabc;", Abc)); 83 84 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$")); 85 EXPECT_TRUE(matches("int k;", StartsWithK)); 86 EXPECT_TRUE(matches("int kAbc;", StartsWithK)); 87 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK)); 88 EXPECT_TRUE(matches("class C { int k; };", StartsWithK)); 89 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK)); 90} 91 92TEST(DeclarationMatcher, MatchClass) { 93 DeclarationMatcher ClassMatcher(recordDecl()); 94#if !defined(_MSC_VER) 95 EXPECT_FALSE(matches("", ClassMatcher)); 96#else 97 // Matches class type_info. 98 EXPECT_TRUE(matches("", ClassMatcher)); 99#endif 100 101 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X"))); 102 EXPECT_TRUE(matches("class X;", ClassX)); 103 EXPECT_TRUE(matches("class X {};", ClassX)); 104 EXPECT_TRUE(matches("template<class T> class X {};", ClassX)); 105 EXPECT_TRUE(notMatches("", ClassX)); 106} 107 108TEST(DeclarationMatcher, ClassIsDerived) { 109 DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X")); 110 111 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX)); 112 EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX)); 113 EXPECT_TRUE(notMatches("class X;", IsDerivedFromX)); 114 EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX)); 115 EXPECT_TRUE(notMatches("", IsDerivedFromX)); 116 117 DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X")); 118 119 EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX)); 120 EXPECT_TRUE(matches("class X {};", IsAX)); 121 EXPECT_TRUE(matches("class X;", IsAX)); 122 EXPECT_TRUE(notMatches("class Y;", IsAX)); 123 EXPECT_TRUE(notMatches("", IsAX)); 124 125 DeclarationMatcher ZIsDerivedFromX = 126 recordDecl(hasName("Z"), isDerivedFrom("X")); 127 EXPECT_TRUE( 128 matches("class X {}; class Y : public X {}; class Z : public Y {};", 129 ZIsDerivedFromX)); 130 EXPECT_TRUE( 131 matches("class X {};" 132 "template<class T> class Y : public X {};" 133 "class Z : public Y<int> {};", ZIsDerivedFromX)); 134 EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};", 135 ZIsDerivedFromX)); 136 EXPECT_TRUE( 137 matches("template<class T> class X {}; " 138 "template<class T> class Z : public X<T> {};", 139 ZIsDerivedFromX)); 140 EXPECT_TRUE( 141 matches("template<class T, class U=T> class X {}; " 142 "template<class T> class Z : public X<T> {};", 143 ZIsDerivedFromX)); 144 EXPECT_TRUE( 145 notMatches("template<class X> class A { class Z : public X {}; };", 146 ZIsDerivedFromX)); 147 EXPECT_TRUE( 148 matches("template<class X> class A { public: class Z : public X {}; }; " 149 "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX)); 150 EXPECT_TRUE( 151 matches("template <class T> class X {}; " 152 "template<class Y> class A { class Z : public X<Y> {}; };", 153 ZIsDerivedFromX)); 154 EXPECT_TRUE( 155 notMatches("template<template<class T> class X> class A { " 156 " class Z : public X<int> {}; };", ZIsDerivedFromX)); 157 EXPECT_TRUE( 158 matches("template<template<class T> class X> class A { " 159 " public: class Z : public X<int> {}; }; " 160 "template<class T> class X {}; void y() { A<X>::Z z; }", 161 ZIsDerivedFromX)); 162 EXPECT_TRUE( 163 notMatches("template<class X> class A { class Z : public X::D {}; };", 164 ZIsDerivedFromX)); 165 EXPECT_TRUE( 166 matches("template<class X> class A { public: " 167 " class Z : public X::D {}; }; " 168 "class Y { public: class X {}; typedef X D; }; " 169 "void y() { A<Y>::Z z; }", ZIsDerivedFromX)); 170 EXPECT_TRUE( 171 matches("class X {}; typedef X Y; class Z : public Y {};", 172 ZIsDerivedFromX)); 173 EXPECT_TRUE( 174 matches("template<class T> class Y { typedef typename T::U X; " 175 " class Z : public X {}; };", ZIsDerivedFromX)); 176 EXPECT_TRUE(matches("class X {}; class Z : public ::X {};", 177 ZIsDerivedFromX)); 178 EXPECT_TRUE( 179 notMatches("template<class T> class X {}; " 180 "template<class T> class A { class Z : public X<T>::D {}; };", 181 ZIsDerivedFromX)); 182 EXPECT_TRUE( 183 matches("template<class T> class X { public: typedef X<T> D; }; " 184 "template<class T> class A { public: " 185 " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }", 186 ZIsDerivedFromX)); 187 EXPECT_TRUE( 188 notMatches("template<class X> class A { class Z : public X::D::E {}; };", 189 ZIsDerivedFromX)); 190 EXPECT_TRUE( 191 matches("class X {}; typedef X V; typedef V W; class Z : public W {};", 192 ZIsDerivedFromX)); 193 EXPECT_TRUE( 194 matches("class X {}; class Y : public X {}; " 195 "typedef Y V; typedef V W; class Z : public W {};", 196 ZIsDerivedFromX)); 197 EXPECT_TRUE( 198 matches("template<class T, class U> class X {}; " 199 "template<class T> class A { class Z : public X<T, int> {}; };", 200 ZIsDerivedFromX)); 201 EXPECT_TRUE( 202 notMatches("template<class X> class D { typedef X A; typedef A B; " 203 " typedef B C; class Z : public C {}; };", 204 ZIsDerivedFromX)); 205 EXPECT_TRUE( 206 matches("class X {}; typedef X A; typedef A B; " 207 "class Z : public B {};", ZIsDerivedFromX)); 208 EXPECT_TRUE( 209 matches("class X {}; typedef X A; typedef A B; typedef B C; " 210 "class Z : public C {};", ZIsDerivedFromX)); 211 EXPECT_TRUE( 212 matches("class U {}; typedef U X; typedef X V; " 213 "class Z : public V {};", ZIsDerivedFromX)); 214 EXPECT_TRUE( 215 matches("class Base {}; typedef Base X; " 216 "class Z : public Base {};", ZIsDerivedFromX)); 217 EXPECT_TRUE( 218 matches("class Base {}; typedef Base Base2; typedef Base2 X; " 219 "class Z : public Base {};", ZIsDerivedFromX)); 220 EXPECT_TRUE( 221 notMatches("class Base {}; class Base2 {}; typedef Base2 X; " 222 "class Z : public Base {};", ZIsDerivedFromX)); 223 EXPECT_TRUE( 224 matches("class A {}; typedef A X; typedef A Y; " 225 "class Z : public Y {};", ZIsDerivedFromX)); 226 EXPECT_TRUE( 227 notMatches("template <typename T> class Z;" 228 "template <> class Z<void> {};" 229 "template <typename T> class Z : public Z<void> {};", 230 IsDerivedFromX)); 231 EXPECT_TRUE( 232 matches("template <typename T> class X;" 233 "template <> class X<void> {};" 234 "template <typename T> class X : public X<void> {};", 235 IsDerivedFromX)); 236 EXPECT_TRUE(matches( 237 "class X {};" 238 "template <typename T> class Z;" 239 "template <> class Z<void> {};" 240 "template <typename T> class Z : public Z<void>, public X {};", 241 ZIsDerivedFromX)); 242 EXPECT_TRUE( 243 notMatches("template<int> struct X;" 244 "template<int i> struct X : public X<i-1> {};", 245 recordDecl(isDerivedFrom(recordDecl(hasName("Some")))))); 246 EXPECT_TRUE(matches( 247 "struct A {};" 248 "template<int> struct X;" 249 "template<int i> struct X : public X<i-1> {};" 250 "template<> struct X<0> : public A {};" 251 "struct B : public X<42> {};", 252 recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A")))))); 253 254 // FIXME: Once we have better matchers for template type matching, 255 // get rid of the Variable(...) matching and match the right template 256 // declarations directly. 257 const char *RecursiveTemplateOneParameter = 258 "class Base1 {}; class Base2 {};" 259 "template <typename T> class Z;" 260 "template <> class Z<void> : public Base1 {};" 261 "template <> class Z<int> : public Base2 {};" 262 "template <> class Z<float> : public Z<void> {};" 263 "template <> class Z<double> : public Z<int> {};" 264 "template <typename T> class Z : public Z<float>, public Z<double> {};" 265 "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }"; 266 EXPECT_TRUE(matches( 267 RecursiveTemplateOneParameter, 268 varDecl(hasName("z_float"), 269 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"))))))); 270 EXPECT_TRUE(notMatches( 271 RecursiveTemplateOneParameter, 272 varDecl(hasName("z_float"), 273 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2"))))))); 274 EXPECT_TRUE(matches( 275 RecursiveTemplateOneParameter, 276 varDecl(hasName("z_char"), 277 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"), 278 isDerivedFrom("Base2"))))))); 279 280 const char *RecursiveTemplateTwoParameters = 281 "class Base1 {}; class Base2 {};" 282 "template <typename T1, typename T2> class Z;" 283 "template <typename T> class Z<void, T> : public Base1 {};" 284 "template <typename T> class Z<int, T> : public Base2 {};" 285 "template <typename T> class Z<float, T> : public Z<void, T> {};" 286 "template <typename T> class Z<double, T> : public Z<int, T> {};" 287 "template <typename T1, typename T2> class Z : " 288 " public Z<float, T2>, public Z<double, T2> {};" 289 "void f() { Z<float, void> z_float; Z<double, void> z_double; " 290 " Z<char, void> z_char; }"; 291 EXPECT_TRUE(matches( 292 RecursiveTemplateTwoParameters, 293 varDecl(hasName("z_float"), 294 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"))))))); 295 EXPECT_TRUE(notMatches( 296 RecursiveTemplateTwoParameters, 297 varDecl(hasName("z_float"), 298 hasInitializer(hasType(recordDecl(isDerivedFrom("Base2"))))))); 299 EXPECT_TRUE(matches( 300 RecursiveTemplateTwoParameters, 301 varDecl(hasName("z_char"), 302 hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"), 303 isDerivedFrom("Base2"))))))); 304 EXPECT_TRUE(matches( 305 "namespace ns { class X {}; class Y : public X {}; }", 306 recordDecl(isDerivedFrom("::ns::X")))); 307 EXPECT_TRUE(notMatches( 308 "class X {}; class Y : public X {};", 309 recordDecl(isDerivedFrom("::ns::X")))); 310 311 EXPECT_TRUE(matches( 312 "class X {}; class Y : public X {};", 313 recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test"))))); 314} 315 316TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) { 317 EXPECT_TRUE(matches( 318 "template <typename T> struct A {" 319 " template <typename T2> struct F {};" 320 "};" 321 "template <typename T> struct B : A<T>::template F<T> {};" 322 "B<int> b;", 323 recordDecl(hasName("B"), isDerivedFrom(recordDecl())))); 324} 325 326TEST(ClassTemplate, DoesNotMatchClass) { 327 DeclarationMatcher ClassX = classTemplateDecl(hasName("X")); 328 EXPECT_TRUE(notMatches("class X;", ClassX)); 329 EXPECT_TRUE(notMatches("class X {};", ClassX)); 330} 331 332TEST(ClassTemplate, MatchesClassTemplate) { 333 DeclarationMatcher ClassX = classTemplateDecl(hasName("X")); 334 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX)); 335 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX)); 336} 337 338TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) { 339 EXPECT_TRUE(notMatches("template<typename T> class X { };" 340 "template<> class X<int> { int a; };", 341 classTemplateDecl(hasName("X"), 342 hasDescendant(fieldDecl(hasName("a")))))); 343} 344 345TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) { 346 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };" 347 "template<typename T> class X<T, int> { int a; };", 348 classTemplateDecl(hasName("X"), 349 hasDescendant(fieldDecl(hasName("a")))))); 350} 351 352TEST(AllOf, AllOverloadsWork) { 353 const char Program[] = 354 "struct T { };" 355 "int f(int, T*, int, int);" 356 "void g(int x) { T t; f(x, &t, 3, 4); }"; 357 EXPECT_TRUE(matches(Program, 358 callExpr(allOf(callee(functionDecl(hasName("f"))), 359 hasArgument(0, declRefExpr(to(varDecl()))))))); 360 EXPECT_TRUE(matches(Program, 361 callExpr(allOf(callee(functionDecl(hasName("f"))), 362 hasArgument(0, declRefExpr(to(varDecl()))), 363 hasArgument(1, hasType(pointsTo( 364 recordDecl(hasName("T"))))))))); 365 EXPECT_TRUE(matches(Program, 366 callExpr(allOf(callee(functionDecl(hasName("f"))), 367 hasArgument(0, declRefExpr(to(varDecl()))), 368 hasArgument(1, hasType(pointsTo( 369 recordDecl(hasName("T"))))), 370 hasArgument(2, integerLiteral(equals(3))))))); 371 EXPECT_TRUE(matches(Program, 372 callExpr(allOf(callee(functionDecl(hasName("f"))), 373 hasArgument(0, declRefExpr(to(varDecl()))), 374 hasArgument(1, hasType(pointsTo( 375 recordDecl(hasName("T"))))), 376 hasArgument(2, integerLiteral(equals(3))), 377 hasArgument(3, integerLiteral(equals(4))))))); 378} 379 380TEST(DeclarationMatcher, MatchAnyOf) { 381 DeclarationMatcher YOrZDerivedFromX = 382 recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z")))); 383 EXPECT_TRUE( 384 matches("class X {}; class Z : public X {};", YOrZDerivedFromX)); 385 EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX)); 386 EXPECT_TRUE( 387 notMatches("class X {}; class W : public X {};", YOrZDerivedFromX)); 388 EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX)); 389 390 DeclarationMatcher XOrYOrZOrU = 391 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"))); 392 EXPECT_TRUE(matches("class X {};", XOrYOrZOrU)); 393 EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU)); 394 395 DeclarationMatcher XOrYOrZOrUOrV = 396 recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"), 397 hasName("V"))); 398 EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV)); 399 EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV)); 400 EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV)); 401 EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV)); 402 EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV)); 403 EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV)); 404} 405 406TEST(DeclarationMatcher, MatchHas) { 407 DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X")))); 408 EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX)); 409 EXPECT_TRUE(matches("class X {};", HasClassX)); 410 411 DeclarationMatcher YHasClassX = 412 recordDecl(hasName("Y"), has(recordDecl(hasName("X")))); 413 EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX)); 414 EXPECT_TRUE(notMatches("class X {};", YHasClassX)); 415 EXPECT_TRUE( 416 notMatches("class Y { class Z { class X {}; }; };", YHasClassX)); 417} 418 419TEST(DeclarationMatcher, MatchHasRecursiveAllOf) { 420 DeclarationMatcher Recursive = 421 recordDecl( 422 has(recordDecl( 423 has(recordDecl(hasName("X"))), 424 has(recordDecl(hasName("Y"))), 425 hasName("Z"))), 426 has(recordDecl( 427 has(recordDecl(hasName("A"))), 428 has(recordDecl(hasName("B"))), 429 hasName("C"))), 430 hasName("F")); 431 432 EXPECT_TRUE(matches( 433 "class F {" 434 " class Z {" 435 " class X {};" 436 " class Y {};" 437 " };" 438 " class C {" 439 " class A {};" 440 " class B {};" 441 " };" 442 "};", Recursive)); 443 444 EXPECT_TRUE(matches( 445 "class F {" 446 " class Z {" 447 " class A {};" 448 " class X {};" 449 " class Y {};" 450 " };" 451 " class C {" 452 " class X {};" 453 " class A {};" 454 " class B {};" 455 " };" 456 "};", Recursive)); 457 458 EXPECT_TRUE(matches( 459 "class O1 {" 460 " class O2 {" 461 " class F {" 462 " class Z {" 463 " class A {};" 464 " class X {};" 465 " class Y {};" 466 " };" 467 " class C {" 468 " class X {};" 469 " class A {};" 470 " class B {};" 471 " };" 472 " };" 473 " };" 474 "};", Recursive)); 475} 476 477TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) { 478 DeclarationMatcher Recursive = 479 recordDecl( 480 anyOf( 481 has(recordDecl( 482 anyOf( 483 has(recordDecl( 484 hasName("X"))), 485 has(recordDecl( 486 hasName("Y"))), 487 hasName("Z")))), 488 has(recordDecl( 489 anyOf( 490 hasName("C"), 491 has(recordDecl( 492 hasName("A"))), 493 has(recordDecl( 494 hasName("B")))))), 495 hasName("F"))); 496 497 EXPECT_TRUE(matches("class F {};", Recursive)); 498 EXPECT_TRUE(matches("class Z {};", Recursive)); 499 EXPECT_TRUE(matches("class C {};", Recursive)); 500 EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive)); 501 EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive)); 502 EXPECT_TRUE( 503 matches("class O1 { class O2 {" 504 " class M { class N { class B {}; }; }; " 505 "}; };", Recursive)); 506} 507 508TEST(DeclarationMatcher, MatchNot) { 509 DeclarationMatcher NotClassX = 510 recordDecl( 511 isDerivedFrom("Y"), 512 unless(hasName("X"))); 513 EXPECT_TRUE(notMatches("", NotClassX)); 514 EXPECT_TRUE(notMatches("class Y {};", NotClassX)); 515 EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX)); 516 EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX)); 517 EXPECT_TRUE( 518 notMatches("class Y {}; class Z {}; class X : public Y {};", 519 NotClassX)); 520 521 DeclarationMatcher ClassXHasNotClassY = 522 recordDecl( 523 hasName("X"), 524 has(recordDecl(hasName("Z"))), 525 unless( 526 has(recordDecl(hasName("Y"))))); 527 EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY)); 528 EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };", 529 ClassXHasNotClassY)); 530} 531 532TEST(DeclarationMatcher, HasDescendant) { 533 DeclarationMatcher ZDescendantClassX = 534 recordDecl( 535 hasDescendant(recordDecl(hasName("X"))), 536 hasName("Z")); 537 EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX)); 538 EXPECT_TRUE( 539 matches("class Z { class Y { class X {}; }; };", ZDescendantClassX)); 540 EXPECT_TRUE( 541 matches("class Z { class A { class Y { class X {}; }; }; };", 542 ZDescendantClassX)); 543 EXPECT_TRUE( 544 matches("class Z { class A { class B { class Y { class X {}; }; }; }; };", 545 ZDescendantClassX)); 546 EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX)); 547 548 DeclarationMatcher ZDescendantClassXHasClassY = 549 recordDecl( 550 hasDescendant(recordDecl(has(recordDecl(hasName("Y"))), 551 hasName("X"))), 552 hasName("Z")); 553 EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };", 554 ZDescendantClassXHasClassY)); 555 EXPECT_TRUE( 556 matches("class Z { class A { class B { class X { class Y {}; }; }; }; };", 557 ZDescendantClassXHasClassY)); 558 EXPECT_TRUE(notMatches( 559 "class Z {" 560 " class A {" 561 " class B {" 562 " class X {" 563 " class C {" 564 " class Y {};" 565 " };" 566 " };" 567 " }; " 568 " };" 569 "};", ZDescendantClassXHasClassY)); 570 571 DeclarationMatcher ZDescendantClassXDescendantClassY = 572 recordDecl( 573 hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))), 574 hasName("X"))), 575 hasName("Z")); 576 EXPECT_TRUE( 577 matches("class Z { class A { class X { class B { class Y {}; }; }; }; };", 578 ZDescendantClassXDescendantClassY)); 579 EXPECT_TRUE(matches( 580 "class Z {" 581 " class A {" 582 " class X {" 583 " class B {" 584 " class Y {};" 585 " };" 586 " class Y {};" 587 " };" 588 " };" 589 "};", ZDescendantClassXDescendantClassY)); 590} 591 592// Implements a run method that returns whether BoundNodes contains a 593// Decl bound to Id that can be dynamically cast to T. 594// Optionally checks that the check succeeded a specific number of times. 595template <typename T> 596class VerifyIdIsBoundTo : public BoundNodesCallback { 597public: 598 // Create an object that checks that a node of type \c T was bound to \c Id. 599 // Does not check for a certain number of matches. 600 explicit VerifyIdIsBoundTo(llvm::StringRef Id) 601 : Id(Id), ExpectedCount(-1), Count(0) {} 602 603 // Create an object that checks that a node of type \c T was bound to \c Id. 604 // Checks that there were exactly \c ExpectedCount matches. 605 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount) 606 : Id(Id), ExpectedCount(ExpectedCount), Count(0) {} 607 608 // Create an object that checks that a node of type \c T was bound to \c Id. 609 // Checks that there was exactly one match with the name \c ExpectedName. 610 // Note that \c T must be a NamedDecl for this to work. 611 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName) 612 : Id(Id), ExpectedCount(1), Count(0), ExpectedName(ExpectedName) {} 613 614 ~VerifyIdIsBoundTo() { 615 if (ExpectedCount != -1) 616 EXPECT_EQ(ExpectedCount, Count); 617 if (!ExpectedName.empty()) 618 EXPECT_EQ(ExpectedName, Name); 619 } 620 621 virtual bool run(const BoundNodes *Nodes) { 622 if (Nodes->getNodeAs<T>(Id)) { 623 ++Count; 624 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) { 625 Name = Named->getNameAsString(); 626 } else if (const NestedNameSpecifier *NNS = 627 Nodes->getNodeAs<NestedNameSpecifier>(Id)) { 628 llvm::raw_string_ostream OS(Name); 629 NNS->print(OS, PrintingPolicy(LangOptions())); 630 } 631 return true; 632 } 633 return false; 634 } 635 636 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) { 637 return run(Nodes); 638 } 639 640private: 641 const std::string Id; 642 const int ExpectedCount; 643 int Count; 644 const std::string ExpectedName; 645 std::string Name; 646}; 647 648TEST(HasDescendant, MatchesDescendantTypes) { 649 EXPECT_TRUE(matches("void f() { int i = 3; }", 650 decl(hasDescendant(loc(builtinType()))))); 651 EXPECT_TRUE(matches("void f() { int i = 3; }", 652 stmt(hasDescendant(builtinType())))); 653 654 EXPECT_TRUE(matches("void f() { int i = 3; }", 655 stmt(hasDescendant(loc(builtinType()))))); 656 EXPECT_TRUE(matches("void f() { int i = 3; }", 657 stmt(hasDescendant(qualType(builtinType()))))); 658 659 EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }", 660 stmt(hasDescendant(isInteger())))); 661 662 EXPECT_TRUE(matchAndVerifyResultTrue( 663 "void f() { int a; float c; int d; int e; }", 664 functionDecl(forEachDescendant( 665 varDecl(hasDescendant(isInteger())).bind("x"))), 666 new VerifyIdIsBoundTo<Decl>("x", 3))); 667} 668 669TEST(HasDescendant, MatchesDescendantsOfTypes) { 670 EXPECT_TRUE(matches("void f() { int*** i; }", 671 qualType(hasDescendant(builtinType())))); 672 EXPECT_TRUE(matches("void f() { int*** i; }", 673 qualType(hasDescendant( 674 pointerType(pointee(builtinType())))))); 675 EXPECT_TRUE(matches("void f() { int*** i; }", 676 typeLoc(hasDescendant(loc(builtinType()))))); 677 678 EXPECT_TRUE(matchAndVerifyResultTrue( 679 "void f() { int*** i; }", 680 qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))), 681 new VerifyIdIsBoundTo<Type>("x", 2))); 682} 683 684TEST(Has, MatchesChildrenOfTypes) { 685 EXPECT_TRUE(matches("int i;", 686 varDecl(hasName("i"), has(isInteger())))); 687 EXPECT_TRUE(notMatches("int** i;", 688 varDecl(hasName("i"), has(isInteger())))); 689 EXPECT_TRUE(matchAndVerifyResultTrue( 690 "int (*f)(float, int);", 691 qualType(functionType(), forEach(qualType(isInteger()).bind("x"))), 692 new VerifyIdIsBoundTo<QualType>("x", 2))); 693} 694 695TEST(Has, MatchesChildTypes) { 696 EXPECT_TRUE(matches( 697 "int* i;", 698 varDecl(hasName("i"), hasType(qualType(has(builtinType())))))); 699 EXPECT_TRUE(notMatches( 700 "int* i;", 701 varDecl(hasName("i"), hasType(qualType(has(pointerType())))))); 702} 703 704TEST(Enum, DoesNotMatchClasses) { 705 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X")))); 706} 707 708TEST(Enum, MatchesEnums) { 709 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X")))); 710} 711 712TEST(EnumConstant, Matches) { 713 DeclarationMatcher Matcher = enumConstantDecl(hasName("A")); 714 EXPECT_TRUE(matches("enum X{ A };", Matcher)); 715 EXPECT_TRUE(notMatches("enum X{ B };", Matcher)); 716 EXPECT_TRUE(notMatches("enum X {};", Matcher)); 717} 718 719TEST(StatementMatcher, Has) { 720 StatementMatcher HasVariableI = 721 expr(hasType(pointsTo(recordDecl(hasName("X")))), 722 has(declRefExpr(to(varDecl(hasName("i")))))); 723 724 EXPECT_TRUE(matches( 725 "class X; X *x(int); void c() { int i; x(i); }", HasVariableI)); 726 EXPECT_TRUE(notMatches( 727 "class X; X *x(int); void c() { int i; x(42); }", HasVariableI)); 728} 729 730TEST(StatementMatcher, HasDescendant) { 731 StatementMatcher HasDescendantVariableI = 732 expr(hasType(pointsTo(recordDecl(hasName("X")))), 733 hasDescendant(declRefExpr(to(varDecl(hasName("i")))))); 734 735 EXPECT_TRUE(matches( 736 "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }", 737 HasDescendantVariableI)); 738 EXPECT_TRUE(notMatches( 739 "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }", 740 HasDescendantVariableI)); 741} 742 743TEST(TypeMatcher, MatchesClassType) { 744 TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A"))); 745 746 EXPECT_TRUE(matches("class A { public: A *a; };", TypeA)); 747 EXPECT_TRUE(notMatches("class A {};", TypeA)); 748 749 TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A"))); 750 751 EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };", 752 TypeDerivedFromA)); 753 EXPECT_TRUE(notMatches("class A {};", TypeA)); 754 755 TypeMatcher TypeAHasClassB = hasDeclaration( 756 recordDecl(hasName("A"), has(recordDecl(hasName("B"))))); 757 758 EXPECT_TRUE( 759 matches("class A { public: A *a; class B {}; };", TypeAHasClassB)); 760} 761 762TEST(Matcher, BindMatchedNodes) { 763 DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x")); 764 765 EXPECT_TRUE(matchAndVerifyResultTrue("class X {};", 766 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x"))); 767 768 EXPECT_TRUE(matchAndVerifyResultFalse("class X {};", 769 ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id"))); 770 771 TypeMatcher TypeAHasClassB = hasDeclaration( 772 recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b")))); 773 774 EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };", 775 TypeAHasClassB, 776 new VerifyIdIsBoundTo<Decl>("b"))); 777 778 StatementMatcher MethodX = 779 callExpr(callee(methodDecl(hasName("x")))).bind("x"); 780 781 EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };", 782 MethodX, 783 new VerifyIdIsBoundTo<CXXMemberCallExpr>("x"))); 784} 785 786TEST(Matcher, BindTheSameNameInAlternatives) { 787 StatementMatcher matcher = anyOf( 788 binaryOperator(hasOperatorName("+"), 789 hasLHS(expr().bind("x")), 790 hasRHS(integerLiteral(equals(0)))), 791 binaryOperator(hasOperatorName("+"), 792 hasLHS(integerLiteral(equals(0))), 793 hasRHS(expr().bind("x")))); 794 795 EXPECT_TRUE(matchAndVerifyResultTrue( 796 // The first branch of the matcher binds x to 0 but then fails. 797 // The second branch binds x to f() and succeeds. 798 "int f() { return 0 + f(); }", 799 matcher, 800 new VerifyIdIsBoundTo<CallExpr>("x"))); 801} 802 803TEST(Matcher, BindsIDForMemoizedResults) { 804 // Using the same matcher in two match expressions will make memoization 805 // kick in. 806 DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x"); 807 EXPECT_TRUE(matchAndVerifyResultTrue( 808 "class A { class B { class X {}; }; };", 809 DeclarationMatcher(anyOf( 810 recordDecl(hasName("A"), hasDescendant(ClassX)), 811 recordDecl(hasName("B"), hasDescendant(ClassX)))), 812 new VerifyIdIsBoundTo<Decl>("x", 2))); 813} 814 815TEST(HasDeclaration, HasDeclarationOfEnumType) { 816 EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }", 817 expr(hasType(pointsTo( 818 qualType(hasDeclaration(enumDecl(hasName("X"))))))))); 819} 820 821TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) { 822 EXPECT_TRUE(matches("typedef int X; X a;", 823 varDecl(hasName("a"), 824 hasType(typedefType(hasDeclaration(decl())))))); 825 826 // FIXME: Add tests for other types with getDecl() (e.g. RecordType) 827} 828 829TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) { 830 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X"))); 831 EXPECT_TRUE( 832 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX)))); 833 EXPECT_TRUE( 834 notMatches("class X {}; void y(X *x) { x; }", 835 expr(hasType(ClassX)))); 836 EXPECT_TRUE( 837 matches("class X {}; void y(X *x) { x; }", 838 expr(hasType(pointsTo(ClassX))))); 839} 840 841TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) { 842 TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X"))); 843 EXPECT_TRUE( 844 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX)))); 845 EXPECT_TRUE( 846 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX)))); 847 EXPECT_TRUE( 848 matches("class X {}; void y() { X *x; }", 849 varDecl(hasType(pointsTo(ClassX))))); 850} 851 852TEST(HasType, TakesDeclMatcherAndMatchesExpr) { 853 DeclarationMatcher ClassX = recordDecl(hasName("X")); 854 EXPECT_TRUE( 855 matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX)))); 856 EXPECT_TRUE( 857 notMatches("class X {}; void y(X *x) { x; }", 858 expr(hasType(ClassX)))); 859} 860 861TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) { 862 DeclarationMatcher ClassX = recordDecl(hasName("X")); 863 EXPECT_TRUE( 864 matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX)))); 865 EXPECT_TRUE( 866 notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX)))); 867} 868 869TEST(Matcher, Call) { 870 // FIXME: Do we want to overload Call() to directly take 871 // Matcher<Decl>, too? 872 StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x")))); 873 874 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX)); 875 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX)); 876 877 StatementMatcher MethodOnY = 878 memberCallExpr(on(hasType(recordDecl(hasName("Y"))))); 879 880 EXPECT_TRUE( 881 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 882 MethodOnY)); 883 EXPECT_TRUE( 884 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 885 MethodOnY)); 886 EXPECT_TRUE( 887 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 888 MethodOnY)); 889 EXPECT_TRUE( 890 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 891 MethodOnY)); 892 EXPECT_TRUE( 893 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 894 MethodOnY)); 895 896 StatementMatcher MethodOnYPointer = 897 memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))); 898 899 EXPECT_TRUE( 900 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 901 MethodOnYPointer)); 902 EXPECT_TRUE( 903 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 904 MethodOnYPointer)); 905 EXPECT_TRUE( 906 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 907 MethodOnYPointer)); 908 EXPECT_TRUE( 909 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 910 MethodOnYPointer)); 911 EXPECT_TRUE( 912 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 913 MethodOnYPointer)); 914} 915 916TEST(Matcher, Lambda) { 917 EXPECT_TRUE(matches("auto f = [&] (int i) { return i; };", 918 lambdaExpr())); 919} 920 921TEST(Matcher, ForRange) { 922 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };" 923 "void f() { for (auto &a : as); }", 924 forRangeStmt())); 925 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }", 926 forRangeStmt())); 927} 928 929TEST(Matcher, UserDefinedLiteral) { 930 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {" 931 " return i + 1;" 932 "}" 933 "char c = 'a'_inc;", 934 userDefinedLiteral())); 935} 936 937TEST(Matcher, FlowControl) { 938 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt())); 939 EXPECT_TRUE(matches("void f() { while(true) { continue; } }", 940 continueStmt())); 941 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt())); 942 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt())); 943 EXPECT_TRUE(matches("void f() { return; }", returnStmt())); 944} 945 946TEST(HasType, MatchesAsString) { 947 EXPECT_TRUE( 948 matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }", 949 memberCallExpr(on(hasType(asString("class Y *")))))); 950 EXPECT_TRUE(matches("class X { void x(int x) {} };", 951 methodDecl(hasParameter(0, hasType(asString("int")))))); 952 EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };", 953 fieldDecl(hasType(asString("ns::A"))))); 954 EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };", 955 fieldDecl(hasType(asString("struct <anonymous>::A"))))); 956} 957 958TEST(Matcher, OverloadedOperatorCall) { 959 StatementMatcher OpCall = operatorCallExpr(); 960 // Unary operator 961 EXPECT_TRUE(matches("class Y { }; " 962 "bool operator!(Y x) { return false; }; " 963 "Y y; bool c = !y;", OpCall)); 964 // No match -- special operators like "new", "delete" 965 // FIXME: operator new takes size_t, for which we need stddef.h, for which 966 // we need to figure out include paths in the test. 967 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n" 968 // "class Y { }; " 969 // "void *operator new(size_t size) { return 0; } " 970 // "Y *y = new Y;", OpCall)); 971 EXPECT_TRUE(notMatches("class Y { }; " 972 "void operator delete(void *p) { } " 973 "void a() {Y *y = new Y; delete y;}", OpCall)); 974 // Binary operator 975 EXPECT_TRUE(matches("class Y { }; " 976 "bool operator&&(Y x, Y y) { return true; }; " 977 "Y a; Y b; bool c = a && b;", 978 OpCall)); 979 // No match -- normal operator, not an overloaded one. 980 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall)); 981 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall)); 982} 983 984TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) { 985 StatementMatcher OpCallAndAnd = 986 operatorCallExpr(hasOverloadedOperatorName("&&")); 987 EXPECT_TRUE(matches("class Y { }; " 988 "bool operator&&(Y x, Y y) { return true; }; " 989 "Y a; Y b; bool c = a && b;", OpCallAndAnd)); 990 StatementMatcher OpCallLessLess = 991 operatorCallExpr(hasOverloadedOperatorName("<<")); 992 EXPECT_TRUE(notMatches("class Y { }; " 993 "bool operator&&(Y x, Y y) { return true; }; " 994 "Y a; Y b; bool c = a && b;", 995 OpCallLessLess)); 996} 997 998TEST(Matcher, NestedOverloadedOperatorCalls) { 999 EXPECT_TRUE(matchAndVerifyResultTrue( 1000 "class Y { }; " 1001 "Y& operator&&(Y& x, Y& y) { return x; }; " 1002 "Y a; Y b; Y c; Y d = a && b && c;", 1003 operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"), 1004 new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2))); 1005 EXPECT_TRUE(matches( 1006 "class Y { }; " 1007 "Y& operator&&(Y& x, Y& y) { return x; }; " 1008 "Y a; Y b; Y c; Y d = a && b && c;", 1009 operatorCallExpr(hasParent(operatorCallExpr())))); 1010 EXPECT_TRUE(matches( 1011 "class Y { }; " 1012 "Y& operator&&(Y& x, Y& y) { return x; }; " 1013 "Y a; Y b; Y c; Y d = a && b && c;", 1014 operatorCallExpr(hasDescendant(operatorCallExpr())))); 1015} 1016 1017TEST(Matcher, ThisPointerType) { 1018 StatementMatcher MethodOnY = 1019 memberCallExpr(thisPointerType(recordDecl(hasName("Y")))); 1020 1021 EXPECT_TRUE( 1022 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 1023 MethodOnY)); 1024 EXPECT_TRUE( 1025 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 1026 MethodOnY)); 1027 EXPECT_TRUE( 1028 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 1029 MethodOnY)); 1030 EXPECT_TRUE( 1031 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 1032 MethodOnY)); 1033 EXPECT_TRUE( 1034 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 1035 MethodOnY)); 1036 1037 EXPECT_TRUE(matches( 1038 "class Y {" 1039 " public: virtual void x();" 1040 "};" 1041 "class X : public Y {" 1042 " public: virtual void x();" 1043 "};" 1044 "void z() { X *x; x->Y::x(); }", MethodOnY)); 1045} 1046 1047TEST(Matcher, VariableUsage) { 1048 StatementMatcher Reference = 1049 declRefExpr(to( 1050 varDecl(hasInitializer( 1051 memberCallExpr(thisPointerType(recordDecl(hasName("Y")))))))); 1052 1053 EXPECT_TRUE(matches( 1054 "class Y {" 1055 " public:" 1056 " bool x() const;" 1057 "};" 1058 "void z(const Y &y) {" 1059 " bool b = y.x();" 1060 " if (b) {}" 1061 "}", Reference)); 1062 1063 EXPECT_TRUE(notMatches( 1064 "class Y {" 1065 " public:" 1066 " bool x() const;" 1067 "};" 1068 "void z(const Y &y) {" 1069 " bool b = y.x();" 1070 "}", Reference)); 1071} 1072 1073TEST(Matcher, FindsVarDeclInFunctionParameter) { 1074 EXPECT_TRUE(matches( 1075 "void f(int i) {}", 1076 varDecl(hasName("i")))); 1077} 1078 1079TEST(Matcher, CalledVariable) { 1080 StatementMatcher CallOnVariableY = 1081 memberCallExpr(on(declRefExpr(to(varDecl(hasName("y")))))); 1082 1083 EXPECT_TRUE(matches( 1084 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY)); 1085 EXPECT_TRUE(matches( 1086 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY)); 1087 EXPECT_TRUE(matches( 1088 "class Y { public: void x(); };" 1089 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY)); 1090 EXPECT_TRUE(matches( 1091 "class Y { public: void x(); };" 1092 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY)); 1093 EXPECT_TRUE(notMatches( 1094 "class Y { public: void x(); };" 1095 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };", 1096 CallOnVariableY)); 1097} 1098 1099TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) { 1100 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", 1101 unaryExprOrTypeTraitExpr())); 1102 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", 1103 alignOfExpr(anything()))); 1104 // FIXME: Uncomment once alignof is enabled. 1105 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }", 1106 // unaryExprOrTypeTraitExpr())); 1107 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }", 1108 // sizeOfExpr())); 1109} 1110 1111TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) { 1112 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr( 1113 hasArgumentOfType(asString("int"))))); 1114 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr( 1115 hasArgumentOfType(asString("float"))))); 1116 EXPECT_TRUE(matches( 1117 "struct A {}; void x() { A a; int b = sizeof(a); }", 1118 sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A"))))))); 1119 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr( 1120 hasArgumentOfType(hasDeclaration(recordDecl(hasName("string"))))))); 1121} 1122 1123TEST(MemberExpression, DoesNotMatchClasses) { 1124 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr())); 1125} 1126 1127TEST(MemberExpression, MatchesMemberFunctionCall) { 1128 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr())); 1129} 1130 1131TEST(MemberExpression, MatchesVariable) { 1132 EXPECT_TRUE( 1133 matches("class Y { void x() { this->y; } int y; };", memberExpr())); 1134 EXPECT_TRUE( 1135 matches("class Y { void x() { y; } int y; };", memberExpr())); 1136 EXPECT_TRUE( 1137 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr())); 1138} 1139 1140TEST(MemberExpression, MatchesStaticVariable) { 1141 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };", 1142 memberExpr())); 1143 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };", 1144 memberExpr())); 1145 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };", 1146 memberExpr())); 1147} 1148 1149TEST(IsInteger, MatchesIntegers) { 1150 EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger())))); 1151 EXPECT_TRUE(matches( 1152 "long long i = 0; void f(long long) { }; void g() {f(i);}", 1153 callExpr(hasArgument(0, declRefExpr( 1154 to(varDecl(hasType(isInteger())))))))); 1155} 1156 1157TEST(IsInteger, ReportsNoFalsePositives) { 1158 EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger())))); 1159 EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}", 1160 callExpr(hasArgument(0, declRefExpr( 1161 to(varDecl(hasType(isInteger())))))))); 1162} 1163 1164TEST(IsArrow, MatchesMemberVariablesViaArrow) { 1165 EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };", 1166 memberExpr(isArrow()))); 1167 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", 1168 memberExpr(isArrow()))); 1169 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };", 1170 memberExpr(isArrow()))); 1171} 1172 1173TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) { 1174 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };", 1175 memberExpr(isArrow()))); 1176 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };", 1177 memberExpr(isArrow()))); 1178 EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };", 1179 memberExpr(isArrow()))); 1180} 1181 1182TEST(IsArrow, MatchesMemberCallsViaArrow) { 1183 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };", 1184 memberExpr(isArrow()))); 1185 EXPECT_TRUE(matches("class Y { void x() { x(); } };", 1186 memberExpr(isArrow()))); 1187 EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };", 1188 memberExpr(isArrow()))); 1189} 1190 1191TEST(Callee, MatchesDeclarations) { 1192 StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x")))); 1193 1194 EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX)); 1195 EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX)); 1196} 1197 1198TEST(Callee, MatchesMemberExpressions) { 1199 EXPECT_TRUE(matches("class Y { void x() { this->x(); } };", 1200 callExpr(callee(memberExpr())))); 1201 EXPECT_TRUE( 1202 notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr())))); 1203} 1204 1205TEST(Function, MatchesFunctionDeclarations) { 1206 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f")))); 1207 1208 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF)); 1209 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF)); 1210 1211#if !defined(_MSC_VER) 1212 // FIXME: Make this work for MSVC. 1213 // Dependent contexts, but a non-dependent call. 1214 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }", 1215 CallFunctionF)); 1216 EXPECT_TRUE( 1217 matches("void f(); template <int N> struct S { void g() { f(); } };", 1218 CallFunctionF)); 1219#endif 1220 1221 // Depedent calls don't match. 1222 EXPECT_TRUE( 1223 notMatches("void f(int); template <typename T> void g(T t) { f(t); }", 1224 CallFunctionF)); 1225 EXPECT_TRUE( 1226 notMatches("void f(int);" 1227 "template <typename T> struct S { void g(T t) { f(t); } };", 1228 CallFunctionF)); 1229} 1230 1231TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) { 1232 EXPECT_TRUE( 1233 matches("template <typename T> void f(T t) {}", 1234 functionTemplateDecl(hasName("f")))); 1235} 1236 1237TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) { 1238 EXPECT_TRUE( 1239 notMatches("void f(double d); void f(int t) {}", 1240 functionTemplateDecl(hasName("f")))); 1241} 1242 1243TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) { 1244 EXPECT_TRUE( 1245 notMatches("void g(); template <typename T> void f(T t) {}" 1246 "template <> void f(int t) { g(); }", 1247 functionTemplateDecl(hasName("f"), 1248 hasDescendant(declRefExpr(to( 1249 functionDecl(hasName("g")))))))); 1250} 1251 1252TEST(Matcher, Argument) { 1253 StatementMatcher CallArgumentY = callExpr( 1254 hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))); 1255 1256 EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY)); 1257 EXPECT_TRUE( 1258 matches("class X { void x(int) { int y; x(y); } };", CallArgumentY)); 1259 EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY)); 1260 1261 StatementMatcher WrongIndex = callExpr( 1262 hasArgument(42, declRefExpr(to(varDecl(hasName("y")))))); 1263 EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex)); 1264} 1265 1266TEST(Matcher, AnyArgument) { 1267 StatementMatcher CallArgumentY = callExpr( 1268 hasAnyArgument(declRefExpr(to(varDecl(hasName("y")))))); 1269 EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY)); 1270 EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY)); 1271 EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY)); 1272} 1273 1274TEST(Matcher, ArgumentCount) { 1275 StatementMatcher Call1Arg = callExpr(argumentCountIs(1)); 1276 1277 EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg)); 1278 EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg)); 1279 EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg)); 1280} 1281 1282TEST(Matcher, ParameterCount) { 1283 DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1)); 1284 EXPECT_TRUE(matches("void f(int i) {}", Function1Arg)); 1285 EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg)); 1286 EXPECT_TRUE(notMatches("void f() {}", Function1Arg)); 1287 EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg)); 1288} 1289 1290TEST(Matcher, References) { 1291 DeclarationMatcher ReferenceClassX = varDecl( 1292 hasType(references(recordDecl(hasName("X"))))); 1293 EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }", 1294 ReferenceClassX)); 1295 EXPECT_TRUE( 1296 matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX)); 1297 EXPECT_TRUE( 1298 notMatches("class X {}; void y(X y) { X x = y; }", ReferenceClassX)); 1299 EXPECT_TRUE( 1300 notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX)); 1301} 1302 1303TEST(HasParameter, CallsInnerMatcher) { 1304 EXPECT_TRUE(matches("class X { void x(int) {} };", 1305 methodDecl(hasParameter(0, varDecl())))); 1306 EXPECT_TRUE(notMatches("class X { void x(int) {} };", 1307 methodDecl(hasParameter(0, hasName("x"))))); 1308} 1309 1310TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) { 1311 EXPECT_TRUE(notMatches("class X { void x(int) {} };", 1312 methodDecl(hasParameter(42, varDecl())))); 1313} 1314 1315TEST(HasType, MatchesParameterVariableTypesStrictly) { 1316 EXPECT_TRUE(matches("class X { void x(X x) {} };", 1317 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X"))))))); 1318 EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };", 1319 methodDecl(hasParameter(0, hasType(recordDecl(hasName("X"))))))); 1320 EXPECT_TRUE(matches("class X { void x(const X *x) {} };", 1321 methodDecl(hasParameter(0, 1322 hasType(pointsTo(recordDecl(hasName("X")))))))); 1323 EXPECT_TRUE(matches("class X { void x(const X &x) {} };", 1324 methodDecl(hasParameter(0, 1325 hasType(references(recordDecl(hasName("X")))))))); 1326} 1327 1328TEST(HasAnyParameter, MatchesIndependentlyOfPosition) { 1329 EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };", 1330 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); 1331 EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };", 1332 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); 1333} 1334 1335TEST(Returns, MatchesReturnTypes) { 1336 EXPECT_TRUE(matches("class Y { int f() { return 1; } };", 1337 functionDecl(returns(asString("int"))))); 1338 EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };", 1339 functionDecl(returns(asString("float"))))); 1340 EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };", 1341 functionDecl(returns(hasDeclaration( 1342 recordDecl(hasName("Y"))))))); 1343} 1344 1345TEST(IsExternC, MatchesExternCFunctionDeclarations) { 1346 EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC()))); 1347 EXPECT_TRUE(matches("extern \"C\" { void f() {} }", 1348 functionDecl(isExternC()))); 1349 EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC()))); 1350} 1351 1352TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) { 1353 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };", 1354 methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); 1355} 1356 1357TEST(HasAnyParameter, DoesNotMatchThisPointer) { 1358 EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };", 1359 methodDecl(hasAnyParameter(hasType(pointsTo( 1360 recordDecl(hasName("X")))))))); 1361} 1362 1363TEST(HasName, MatchesParameterVariableDeclartions) { 1364 EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };", 1365 methodDecl(hasAnyParameter(hasName("x"))))); 1366 EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };", 1367 methodDecl(hasAnyParameter(hasName("x"))))); 1368} 1369 1370TEST(Matcher, MatchesClassTemplateSpecialization) { 1371 EXPECT_TRUE(matches("template<typename T> struct A {};" 1372 "template<> struct A<int> {};", 1373 classTemplateSpecializationDecl())); 1374 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;", 1375 classTemplateSpecializationDecl())); 1376 EXPECT_TRUE(notMatches("template<typename T> struct A {};", 1377 classTemplateSpecializationDecl())); 1378} 1379 1380TEST(Matcher, MatchesTypeTemplateArgument) { 1381 EXPECT_TRUE(matches( 1382 "template<typename T> struct B {};" 1383 "B<int> b;", 1384 classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType( 1385 asString("int")))))); 1386} 1387 1388TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) { 1389 EXPECT_TRUE(matches( 1390 "struct B { int next; };" 1391 "template<int(B::*next_ptr)> struct A {};" 1392 "A<&B::next> a;", 1393 classTemplateSpecializationDecl(hasAnyTemplateArgument( 1394 refersToDeclaration(fieldDecl(hasName("next"))))))); 1395 1396 EXPECT_TRUE(notMatches( 1397 "template <typename T> struct A {};" 1398 "A<int> a;", 1399 classTemplateSpecializationDecl(hasAnyTemplateArgument( 1400 refersToDeclaration(decl()))))); 1401} 1402 1403TEST(Matcher, MatchesSpecificArgument) { 1404 EXPECT_TRUE(matches( 1405 "template<typename T, typename U> class A {};" 1406 "A<bool, int> a;", 1407 classTemplateSpecializationDecl(hasTemplateArgument( 1408 1, refersToType(asString("int")))))); 1409 EXPECT_TRUE(notMatches( 1410 "template<typename T, typename U> class A {};" 1411 "A<int, bool> a;", 1412 classTemplateSpecializationDecl(hasTemplateArgument( 1413 1, refersToType(asString("int")))))); 1414} 1415 1416TEST(Matcher, MatchesAccessSpecDecls) { 1417 EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl())); 1418 EXPECT_TRUE( 1419 matches("class C { public: int i; };", accessSpecDecl(isPublic()))); 1420 EXPECT_TRUE( 1421 notMatches("class C { public: int i; };", accessSpecDecl(isProtected()))); 1422 EXPECT_TRUE( 1423 notMatches("class C { public: int i; };", accessSpecDecl(isPrivate()))); 1424 1425 EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl())); 1426} 1427 1428TEST(Matcher, ConstructorCall) { 1429 StatementMatcher Constructor = constructExpr(); 1430 1431 EXPECT_TRUE( 1432 matches("class X { public: X(); }; void x() { X x; }", Constructor)); 1433 EXPECT_TRUE( 1434 matches("class X { public: X(); }; void x() { X x = X(); }", 1435 Constructor)); 1436 EXPECT_TRUE( 1437 matches("class X { public: X(int); }; void x() { X x = 0; }", 1438 Constructor)); 1439 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor)); 1440} 1441 1442TEST(Matcher, ConstructorArgument) { 1443 StatementMatcher Constructor = constructExpr( 1444 hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))); 1445 1446 EXPECT_TRUE( 1447 matches("class X { public: X(int); }; void x() { int y; X x(y); }", 1448 Constructor)); 1449 EXPECT_TRUE( 1450 matches("class X { public: X(int); }; void x() { int y; X x = X(y); }", 1451 Constructor)); 1452 EXPECT_TRUE( 1453 matches("class X { public: X(int); }; void x() { int y; X x = y; }", 1454 Constructor)); 1455 EXPECT_TRUE( 1456 notMatches("class X { public: X(int); }; void x() { int z; X x(z); }", 1457 Constructor)); 1458 1459 StatementMatcher WrongIndex = constructExpr( 1460 hasArgument(42, declRefExpr(to(varDecl(hasName("y")))))); 1461 EXPECT_TRUE( 1462 notMatches("class X { public: X(int); }; void x() { int y; X x(y); }", 1463 WrongIndex)); 1464} 1465 1466TEST(Matcher, ConstructorArgumentCount) { 1467 StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1)); 1468 1469 EXPECT_TRUE( 1470 matches("class X { public: X(int); }; void x() { X x(0); }", 1471 Constructor1Arg)); 1472 EXPECT_TRUE( 1473 matches("class X { public: X(int); }; void x() { X x = X(0); }", 1474 Constructor1Arg)); 1475 EXPECT_TRUE( 1476 matches("class X { public: X(int); }; void x() { X x = 0; }", 1477 Constructor1Arg)); 1478 EXPECT_TRUE( 1479 notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }", 1480 Constructor1Arg)); 1481} 1482 1483TEST(Matcher,ThisExpr) { 1484 EXPECT_TRUE( 1485 matches("struct X { int a; int f () { return a; } };", thisExpr())); 1486 EXPECT_TRUE( 1487 notMatches("struct X { int f () { int a; return a; } };", thisExpr())); 1488} 1489 1490TEST(Matcher, BindTemporaryExpression) { 1491 StatementMatcher TempExpression = bindTemporaryExpr(); 1492 1493 std::string ClassString = "class string { public: string(); ~string(); }; "; 1494 1495 EXPECT_TRUE( 1496 matches(ClassString + 1497 "string GetStringByValue();" 1498 "void FunctionTakesString(string s);" 1499 "void run() { FunctionTakesString(GetStringByValue()); }", 1500 TempExpression)); 1501 1502 EXPECT_TRUE( 1503 notMatches(ClassString + 1504 "string* GetStringPointer(); " 1505 "void FunctionTakesStringPtr(string* s);" 1506 "void run() {" 1507 " string* s = GetStringPointer();" 1508 " FunctionTakesStringPtr(GetStringPointer());" 1509 " FunctionTakesStringPtr(s);" 1510 "}", 1511 TempExpression)); 1512 1513 EXPECT_TRUE( 1514 notMatches("class no_dtor {};" 1515 "no_dtor GetObjByValue();" 1516 "void ConsumeObj(no_dtor param);" 1517 "void run() { ConsumeObj(GetObjByValue()); }", 1518 TempExpression)); 1519} 1520 1521TEST(MaterializeTemporaryExpr, MatchesTemporary) { 1522 std::string ClassString = 1523 "class string { public: string(); int length(); }; "; 1524 1525 EXPECT_TRUE( 1526 matches(ClassString + 1527 "string GetStringByValue();" 1528 "void FunctionTakesString(string s);" 1529 "void run() { FunctionTakesString(GetStringByValue()); }", 1530 materializeTemporaryExpr())); 1531 1532 EXPECT_TRUE( 1533 notMatches(ClassString + 1534 "string* GetStringPointer(); " 1535 "void FunctionTakesStringPtr(string* s);" 1536 "void run() {" 1537 " string* s = GetStringPointer();" 1538 " FunctionTakesStringPtr(GetStringPointer());" 1539 " FunctionTakesStringPtr(s);" 1540 "}", 1541 materializeTemporaryExpr())); 1542 1543 EXPECT_TRUE( 1544 notMatches(ClassString + 1545 "string GetStringByValue();" 1546 "void run() { int k = GetStringByValue().length(); }", 1547 materializeTemporaryExpr())); 1548 1549 EXPECT_TRUE( 1550 notMatches(ClassString + 1551 "string GetStringByValue();" 1552 "void run() { GetStringByValue(); }", 1553 materializeTemporaryExpr())); 1554} 1555 1556TEST(ConstructorDeclaration, SimpleCase) { 1557 EXPECT_TRUE(matches("class Foo { Foo(int i); };", 1558 constructorDecl(ofClass(hasName("Foo"))))); 1559 EXPECT_TRUE(notMatches("class Foo { Foo(int i); };", 1560 constructorDecl(ofClass(hasName("Bar"))))); 1561} 1562 1563TEST(ConstructorDeclaration, IsImplicit) { 1564 // This one doesn't match because the constructor is not added by the 1565 // compiler (it is not needed). 1566 EXPECT_TRUE(notMatches("class Foo { };", 1567 constructorDecl(isImplicit()))); 1568 // The compiler added the implicit default constructor. 1569 EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();", 1570 constructorDecl(isImplicit()))); 1571 EXPECT_TRUE(matches("class Foo { Foo(){} };", 1572 constructorDecl(unless(isImplicit())))); 1573} 1574 1575TEST(DestructorDeclaration, MatchesVirtualDestructor) { 1576 EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };", 1577 destructorDecl(ofClass(hasName("Foo"))))); 1578} 1579 1580TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) { 1581 EXPECT_TRUE(notMatches("class Foo {};", 1582 destructorDecl(ofClass(hasName("Foo"))))); 1583} 1584 1585TEST(HasAnyConstructorInitializer, SimpleCase) { 1586 EXPECT_TRUE(notMatches( 1587 "class Foo { Foo() { } };", 1588 constructorDecl(hasAnyConstructorInitializer(anything())))); 1589 EXPECT_TRUE(matches( 1590 "class Foo {" 1591 " Foo() : foo_() { }" 1592 " int foo_;" 1593 "};", 1594 constructorDecl(hasAnyConstructorInitializer(anything())))); 1595} 1596 1597TEST(HasAnyConstructorInitializer, ForField) { 1598 static const char Code[] = 1599 "class Baz { };" 1600 "class Foo {" 1601 " Foo() : foo_() { }" 1602 " Baz foo_;" 1603 " Baz bar_;" 1604 "};"; 1605 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer( 1606 forField(hasType(recordDecl(hasName("Baz")))))))); 1607 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer( 1608 forField(hasName("foo_")))))); 1609 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer( 1610 forField(hasType(recordDecl(hasName("Bar")))))))); 1611} 1612 1613TEST(HasAnyConstructorInitializer, WithInitializer) { 1614 static const char Code[] = 1615 "class Foo {" 1616 " Foo() : foo_(0) { }" 1617 " int foo_;" 1618 "};"; 1619 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer( 1620 withInitializer(integerLiteral(equals(0))))))); 1621 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer( 1622 withInitializer(integerLiteral(equals(1))))))); 1623} 1624 1625TEST(HasAnyConstructorInitializer, IsWritten) { 1626 static const char Code[] = 1627 "struct Bar { Bar(){} };" 1628 "class Foo {" 1629 " Foo() : foo_() { }" 1630 " Bar foo_;" 1631 " Bar bar_;" 1632 "};"; 1633 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer( 1634 allOf(forField(hasName("foo_")), isWritten()))))); 1635 EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer( 1636 allOf(forField(hasName("bar_")), isWritten()))))); 1637 EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer( 1638 allOf(forField(hasName("bar_")), unless(isWritten())))))); 1639} 1640 1641TEST(Matcher, NewExpression) { 1642 StatementMatcher New = newExpr(); 1643 1644 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New)); 1645 EXPECT_TRUE( 1646 matches("class X { public: X(); }; void x() { new X(); }", New)); 1647 EXPECT_TRUE( 1648 matches("class X { public: X(int); }; void x() { new X(0); }", New)); 1649 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New)); 1650} 1651 1652TEST(Matcher, NewExpressionArgument) { 1653 StatementMatcher New = constructExpr( 1654 hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))); 1655 1656 EXPECT_TRUE( 1657 matches("class X { public: X(int); }; void x() { int y; new X(y); }", 1658 New)); 1659 EXPECT_TRUE( 1660 matches("class X { public: X(int); }; void x() { int y; new X(y); }", 1661 New)); 1662 EXPECT_TRUE( 1663 notMatches("class X { public: X(int); }; void x() { int z; new X(z); }", 1664 New)); 1665 1666 StatementMatcher WrongIndex = constructExpr( 1667 hasArgument(42, declRefExpr(to(varDecl(hasName("y")))))); 1668 EXPECT_TRUE( 1669 notMatches("class X { public: X(int); }; void x() { int y; new X(y); }", 1670 WrongIndex)); 1671} 1672 1673TEST(Matcher, NewExpressionArgumentCount) { 1674 StatementMatcher New = constructExpr(argumentCountIs(1)); 1675 1676 EXPECT_TRUE( 1677 matches("class X { public: X(int); }; void x() { new X(0); }", New)); 1678 EXPECT_TRUE( 1679 notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }", 1680 New)); 1681} 1682 1683TEST(Matcher, DeleteExpression) { 1684 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }", 1685 deleteExpr())); 1686} 1687 1688TEST(Matcher, DefaultArgument) { 1689 StatementMatcher Arg = defaultArgExpr(); 1690 1691 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg)); 1692 EXPECT_TRUE( 1693 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg)); 1694 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg)); 1695} 1696 1697TEST(Matcher, StringLiterals) { 1698 StatementMatcher Literal = stringLiteral(); 1699 EXPECT_TRUE(matches("const char *s = \"string\";", Literal)); 1700 // wide string 1701 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal)); 1702 // with escaped characters 1703 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal)); 1704 // no matching -- though the data type is the same, there is no string literal 1705 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal)); 1706} 1707 1708TEST(Matcher, CharacterLiterals) { 1709 StatementMatcher CharLiteral = characterLiteral(); 1710 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral)); 1711 // wide character 1712 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral)); 1713 // wide character, Hex encoded, NOT MATCHED! 1714 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral)); 1715 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral)); 1716} 1717 1718TEST(Matcher, IntegerLiterals) { 1719 StatementMatcher HasIntLiteral = integerLiteral(); 1720 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral)); 1721 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral)); 1722 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral)); 1723 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral)); 1724 1725 // Non-matching cases (character literals, float and double) 1726 EXPECT_TRUE(notMatches("int i = L'a';", 1727 HasIntLiteral)); // this is actually a character 1728 // literal cast to int 1729 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral)); 1730 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral)); 1731 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral)); 1732} 1733 1734TEST(Matcher, NullPtrLiteral) { 1735 EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr())); 1736} 1737 1738TEST(Matcher, AsmStatement) { 1739 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt())); 1740} 1741 1742TEST(Matcher, Conditions) { 1743 StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true)))); 1744 1745 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition)); 1746 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition)); 1747 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition)); 1748 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition)); 1749 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition)); 1750} 1751 1752TEST(MatchBinaryOperator, HasOperatorName) { 1753 StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||")); 1754 1755 EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr)); 1756 EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr)); 1757} 1758 1759TEST(MatchBinaryOperator, HasLHSAndHasRHS) { 1760 StatementMatcher OperatorTrueFalse = 1761 binaryOperator(hasLHS(boolLiteral(equals(true))), 1762 hasRHS(boolLiteral(equals(false)))); 1763 1764 EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse)); 1765 EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse)); 1766 EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse)); 1767} 1768 1769TEST(MatchBinaryOperator, HasEitherOperand) { 1770 StatementMatcher HasOperand = 1771 binaryOperator(hasEitherOperand(boolLiteral(equals(false)))); 1772 1773 EXPECT_TRUE(matches("void x() { true || false; }", HasOperand)); 1774 EXPECT_TRUE(matches("void x() { false && true; }", HasOperand)); 1775 EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand)); 1776} 1777 1778TEST(Matcher, BinaryOperatorTypes) { 1779 // Integration test that verifies the AST provides all binary operators in 1780 // a way we expect. 1781 // FIXME: Operator ',' 1782 EXPECT_TRUE( 1783 matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(",")))); 1784 EXPECT_TRUE( 1785 matches("bool b; bool c = (b = true);", 1786 binaryOperator(hasOperatorName("=")))); 1787 EXPECT_TRUE( 1788 matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!=")))); 1789 EXPECT_TRUE( 1790 matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("==")))); 1791 EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<")))); 1792 EXPECT_TRUE( 1793 matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<=")))); 1794 EXPECT_TRUE( 1795 matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<")))); 1796 EXPECT_TRUE( 1797 matches("int i = 1; int j = (i <<= 2);", 1798 binaryOperator(hasOperatorName("<<=")))); 1799 EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">")))); 1800 EXPECT_TRUE( 1801 matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">=")))); 1802 EXPECT_TRUE( 1803 matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>")))); 1804 EXPECT_TRUE( 1805 matches("int i = 1; int j = (i >>= 2);", 1806 binaryOperator(hasOperatorName(">>=")))); 1807 EXPECT_TRUE( 1808 matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^")))); 1809 EXPECT_TRUE( 1810 matches("int i = 42; int j = (i ^= 42);", 1811 binaryOperator(hasOperatorName("^=")))); 1812 EXPECT_TRUE( 1813 matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%")))); 1814 EXPECT_TRUE( 1815 matches("int i = 42; int j = (i %= 42);", 1816 binaryOperator(hasOperatorName("%=")))); 1817 EXPECT_TRUE( 1818 matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&")))); 1819 EXPECT_TRUE( 1820 matches("bool b = true && false;", 1821 binaryOperator(hasOperatorName("&&")))); 1822 EXPECT_TRUE( 1823 matches("bool b = true; bool c = (b &= false);", 1824 binaryOperator(hasOperatorName("&=")))); 1825 EXPECT_TRUE( 1826 matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|")))); 1827 EXPECT_TRUE( 1828 matches("bool b = true || false;", 1829 binaryOperator(hasOperatorName("||")))); 1830 EXPECT_TRUE( 1831 matches("bool b = true; bool c = (b |= false);", 1832 binaryOperator(hasOperatorName("|=")))); 1833 EXPECT_TRUE( 1834 matches("int i = 42 *23;", binaryOperator(hasOperatorName("*")))); 1835 EXPECT_TRUE( 1836 matches("int i = 42; int j = (i *= 23);", 1837 binaryOperator(hasOperatorName("*=")))); 1838 EXPECT_TRUE( 1839 matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/")))); 1840 EXPECT_TRUE( 1841 matches("int i = 42; int j = (i /= 23);", 1842 binaryOperator(hasOperatorName("/=")))); 1843 EXPECT_TRUE( 1844 matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+")))); 1845 EXPECT_TRUE( 1846 matches("int i = 42; int j = (i += 23);", 1847 binaryOperator(hasOperatorName("+=")))); 1848 EXPECT_TRUE( 1849 matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-")))); 1850 EXPECT_TRUE( 1851 matches("int i = 42; int j = (i -= 23);", 1852 binaryOperator(hasOperatorName("-=")))); 1853 EXPECT_TRUE( 1854 matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };", 1855 binaryOperator(hasOperatorName("->*")))); 1856 EXPECT_TRUE( 1857 matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };", 1858 binaryOperator(hasOperatorName(".*")))); 1859 1860 // Member expressions as operators are not supported in matches. 1861 EXPECT_TRUE( 1862 notMatches("struct A { void x(A *a) { a->x(this); } };", 1863 binaryOperator(hasOperatorName("->")))); 1864 1865 // Initializer assignments are not represented as operator equals. 1866 EXPECT_TRUE( 1867 notMatches("bool b = true;", binaryOperator(hasOperatorName("=")))); 1868 1869 // Array indexing is not represented as operator. 1870 EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator())); 1871 1872 // Overloaded operators do not match at all. 1873 EXPECT_TRUE(notMatches( 1874 "struct A { bool operator&&(const A &a) const { return false; } };" 1875 "void x() { A a, b; a && b; }", 1876 binaryOperator())); 1877} 1878 1879TEST(MatchUnaryOperator, HasOperatorName) { 1880 StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!")); 1881 1882 EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot)); 1883 EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot)); 1884} 1885 1886TEST(MatchUnaryOperator, HasUnaryOperand) { 1887 StatementMatcher OperatorOnFalse = 1888 unaryOperator(hasUnaryOperand(boolLiteral(equals(false)))); 1889 1890 EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse)); 1891 EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse)); 1892} 1893 1894TEST(Matcher, UnaryOperatorTypes) { 1895 // Integration test that verifies the AST provides all unary operators in 1896 // a way we expect. 1897 EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!")))); 1898 EXPECT_TRUE( 1899 matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&")))); 1900 EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~")))); 1901 EXPECT_TRUE( 1902 matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*")))); 1903 EXPECT_TRUE( 1904 matches("int i; int j = +i;", unaryOperator(hasOperatorName("+")))); 1905 EXPECT_TRUE( 1906 matches("int i; int j = -i;", unaryOperator(hasOperatorName("-")))); 1907 EXPECT_TRUE( 1908 matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++")))); 1909 EXPECT_TRUE( 1910 matches("int i; int j = i++;", unaryOperator(hasOperatorName("++")))); 1911 EXPECT_TRUE( 1912 matches("int i; int j = --i;", unaryOperator(hasOperatorName("--")))); 1913 EXPECT_TRUE( 1914 matches("int i; int j = i--;", unaryOperator(hasOperatorName("--")))); 1915 1916 // We don't match conversion operators. 1917 EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator())); 1918 1919 // Function calls are not represented as operator. 1920 EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator())); 1921 1922 // Overloaded operators do not match at all. 1923 // FIXME: We probably want to add that. 1924 EXPECT_TRUE(notMatches( 1925 "struct A { bool operator!() const { return false; } };" 1926 "void x() { A a; !a; }", unaryOperator(hasOperatorName("!")))); 1927} 1928 1929TEST(Matcher, ConditionalOperator) { 1930 StatementMatcher Conditional = conditionalOperator( 1931 hasCondition(boolLiteral(equals(true))), 1932 hasTrueExpression(boolLiteral(equals(false)))); 1933 1934 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional)); 1935 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional)); 1936 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional)); 1937 1938 StatementMatcher ConditionalFalse = conditionalOperator( 1939 hasFalseExpression(boolLiteral(equals(false)))); 1940 1941 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse)); 1942 EXPECT_TRUE( 1943 notMatches("void x() { true ? false : true; }", ConditionalFalse)); 1944} 1945 1946TEST(ArraySubscriptMatchers, ArraySubscripts) { 1947 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }", 1948 arraySubscriptExpr())); 1949 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", 1950 arraySubscriptExpr())); 1951} 1952 1953TEST(ArraySubscriptMatchers, ArrayIndex) { 1954 EXPECT_TRUE(matches( 1955 "int i[2]; void f() { i[1] = 1; }", 1956 arraySubscriptExpr(hasIndex(integerLiteral(equals(1)))))); 1957 EXPECT_TRUE(matches( 1958 "int i[2]; void f() { 1[i] = 1; }", 1959 arraySubscriptExpr(hasIndex(integerLiteral(equals(1)))))); 1960 EXPECT_TRUE(notMatches( 1961 "int i[2]; void f() { i[1] = 1; }", 1962 arraySubscriptExpr(hasIndex(integerLiteral(equals(0)))))); 1963} 1964 1965TEST(ArraySubscriptMatchers, MatchesArrayBase) { 1966 EXPECT_TRUE(matches( 1967 "int i[2]; void f() { i[1] = 2; }", 1968 arraySubscriptExpr(hasBase(implicitCastExpr( 1969 hasSourceExpression(declRefExpr())))))); 1970} 1971 1972TEST(Matcher, HasNameSupportsNamespaces) { 1973 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }", 1974 recordDecl(hasName("a::b::C")))); 1975 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }", 1976 recordDecl(hasName("::a::b::C")))); 1977 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }", 1978 recordDecl(hasName("b::C")))); 1979 EXPECT_TRUE(matches("namespace a { namespace b { class C; } }", 1980 recordDecl(hasName("C")))); 1981 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1982 recordDecl(hasName("c::b::C")))); 1983 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1984 recordDecl(hasName("a::c::C")))); 1985 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1986 recordDecl(hasName("a::b::A")))); 1987 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1988 recordDecl(hasName("::C")))); 1989 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1990 recordDecl(hasName("::b::C")))); 1991 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1992 recordDecl(hasName("z::a::b::C")))); 1993 EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }", 1994 recordDecl(hasName("a+b::C")))); 1995 EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }", 1996 recordDecl(hasName("C")))); 1997} 1998 1999TEST(Matcher, HasNameSupportsOuterClasses) { 2000 EXPECT_TRUE( 2001 matches("class A { class B { class C; }; };", 2002 recordDecl(hasName("A::B::C")))); 2003 EXPECT_TRUE( 2004 matches("class A { class B { class C; }; };", 2005 recordDecl(hasName("::A::B::C")))); 2006 EXPECT_TRUE( 2007 matches("class A { class B { class C; }; };", 2008 recordDecl(hasName("B::C")))); 2009 EXPECT_TRUE( 2010 matches("class A { class B { class C; }; };", 2011 recordDecl(hasName("C")))); 2012 EXPECT_TRUE( 2013 notMatches("class A { class B { class C; }; };", 2014 recordDecl(hasName("c::B::C")))); 2015 EXPECT_TRUE( 2016 notMatches("class A { class B { class C; }; };", 2017 recordDecl(hasName("A::c::C")))); 2018 EXPECT_TRUE( 2019 notMatches("class A { class B { class C; }; };", 2020 recordDecl(hasName("A::B::A")))); 2021 EXPECT_TRUE( 2022 notMatches("class A { class B { class C; }; };", 2023 recordDecl(hasName("::C")))); 2024 EXPECT_TRUE( 2025 notMatches("class A { class B { class C; }; };", 2026 recordDecl(hasName("::B::C")))); 2027 EXPECT_TRUE(notMatches("class A { class B { class C; }; };", 2028 recordDecl(hasName("z::A::B::C")))); 2029 EXPECT_TRUE( 2030 notMatches("class A { class B { class C; }; };", 2031 recordDecl(hasName("A+B::C")))); 2032} 2033 2034TEST(Matcher, IsDefinition) { 2035 DeclarationMatcher DefinitionOfClassA = 2036 recordDecl(hasName("A"), isDefinition()); 2037 EXPECT_TRUE(matches("class A {};", DefinitionOfClassA)); 2038 EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA)); 2039 2040 DeclarationMatcher DefinitionOfVariableA = 2041 varDecl(hasName("a"), isDefinition()); 2042 EXPECT_TRUE(matches("int a;", DefinitionOfVariableA)); 2043 EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA)); 2044 2045 DeclarationMatcher DefinitionOfMethodA = 2046 methodDecl(hasName("a"), isDefinition()); 2047 EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA)); 2048 EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA)); 2049} 2050 2051TEST(Matcher, OfClass) { 2052 StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl( 2053 ofClass(hasName("X"))))); 2054 2055 EXPECT_TRUE( 2056 matches("class X { public: X(); }; void x(int) { X x; }", Constructor)); 2057 EXPECT_TRUE( 2058 matches("class X { public: X(); }; void x(int) { X x = X(); }", 2059 Constructor)); 2060 EXPECT_TRUE( 2061 notMatches("class Y { public: Y(); }; void x(int) { Y y; }", 2062 Constructor)); 2063} 2064 2065TEST(Matcher, VisitsTemplateInstantiations) { 2066 EXPECT_TRUE(matches( 2067 "class A { public: void x(); };" 2068 "template <typename T> class B { public: void y() { T t; t.x(); } };" 2069 "void f() { B<A> b; b.y(); }", 2070 callExpr(callee(methodDecl(hasName("x")))))); 2071 2072 EXPECT_TRUE(matches( 2073 "class A { public: void x(); };" 2074 "class C {" 2075 " public:" 2076 " template <typename T> class B { public: void y() { T t; t.x(); } };" 2077 "};" 2078 "void f() {" 2079 " C::B<A> b; b.y();" 2080 "}", 2081 recordDecl(hasName("C"), 2082 hasDescendant(callExpr(callee(methodDecl(hasName("x")))))))); 2083} 2084 2085TEST(Matcher, HandlesNullQualTypes) { 2086 // FIXME: Add a Type matcher so we can replace uses of this 2087 // variable with Type(True()) 2088 const TypeMatcher AnyType = anything(); 2089 2090 // We don't really care whether this matcher succeeds; we're testing that 2091 // it completes without crashing. 2092 EXPECT_TRUE(matches( 2093 "struct A { };" 2094 "template <typename T>" 2095 "void f(T t) {" 2096 " T local_t(t /* this becomes a null QualType in the AST */);" 2097 "}" 2098 "void g() {" 2099 " f(0);" 2100 "}", 2101 expr(hasType(TypeMatcher( 2102 anyOf( 2103 TypeMatcher(hasDeclaration(anything())), 2104 pointsTo(AnyType), 2105 references(AnyType) 2106 // Other QualType matchers should go here. 2107 )))))); 2108} 2109 2110// For testing AST_MATCHER_P(). 2111AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) { 2112 // Make sure all special variables are used: node, match_finder, 2113 // bound_nodes_builder, and the parameter named 'AMatcher'. 2114 return AMatcher.matches(Node, Finder, Builder); 2115} 2116 2117TEST(AstMatcherPMacro, Works) { 2118 DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b"))); 2119 2120 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };", 2121 HasClassB, new VerifyIdIsBoundTo<Decl>("b"))); 2122 2123 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };", 2124 HasClassB, new VerifyIdIsBoundTo<Decl>("a"))); 2125 2126 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };", 2127 HasClassB, new VerifyIdIsBoundTo<Decl>("b"))); 2128} 2129 2130AST_POLYMORPHIC_MATCHER_P( 2131 polymorphicHas, internal::Matcher<Decl>, AMatcher) { 2132 TOOLING_COMPILE_ASSERT((llvm::is_same<NodeType, Decl>::value) || 2133 (llvm::is_same<NodeType, Stmt>::value), 2134 assert_node_type_is_accessible); 2135 return Finder->matchesChildOf( 2136 Node, AMatcher, Builder, 2137 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 2138 ASTMatchFinder::BK_First); 2139} 2140 2141TEST(AstPolymorphicMatcherPMacro, Works) { 2142 DeclarationMatcher HasClassB = 2143 polymorphicHas(recordDecl(hasName("B")).bind("b")); 2144 2145 EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };", 2146 HasClassB, new VerifyIdIsBoundTo<Decl>("b"))); 2147 2148 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };", 2149 HasClassB, new VerifyIdIsBoundTo<Decl>("a"))); 2150 2151 EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };", 2152 HasClassB, new VerifyIdIsBoundTo<Decl>("b"))); 2153 2154 StatementMatcher StatementHasClassB = 2155 polymorphicHas(recordDecl(hasName("B"))); 2156 2157 EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB)); 2158} 2159 2160TEST(For, FindsForLoops) { 2161 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt())); 2162 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt())); 2163 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };" 2164 "void f() { for (auto &a : as); }", 2165 forStmt())); 2166} 2167 2168TEST(For, ForLoopInternals) { 2169 EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }", 2170 forStmt(hasCondition(anything())))); 2171 EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }", 2172 forStmt(hasLoopInit(anything())))); 2173} 2174 2175TEST(For, NegativeForLoopInternals) { 2176 EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }", 2177 forStmt(hasCondition(expr())))); 2178 EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }", 2179 forStmt(hasLoopInit(anything())))); 2180} 2181 2182TEST(For, ReportsNoFalsePositives) { 2183 EXPECT_TRUE(notMatches("void f() { ; }", forStmt())); 2184 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt())); 2185} 2186 2187TEST(CompoundStatement, HandlesSimpleCases) { 2188 EXPECT_TRUE(notMatches("void f();", compoundStmt())); 2189 EXPECT_TRUE(matches("void f() {}", compoundStmt())); 2190 EXPECT_TRUE(matches("void f() {{}}", compoundStmt())); 2191} 2192 2193TEST(CompoundStatement, DoesNotMatchEmptyStruct) { 2194 // It's not a compound statement just because there's "{}" in the source 2195 // text. This is an AST search, not grep. 2196 EXPECT_TRUE(notMatches("namespace n { struct S {}; }", 2197 compoundStmt())); 2198 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }", 2199 compoundStmt())); 2200} 2201 2202TEST(HasBody, FindsBodyOfForWhileDoLoops) { 2203 EXPECT_TRUE(matches("void f() { for(;;) {} }", 2204 forStmt(hasBody(compoundStmt())))); 2205 EXPECT_TRUE(notMatches("void f() { for(;;); }", 2206 forStmt(hasBody(compoundStmt())))); 2207 EXPECT_TRUE(matches("void f() { while(true) {} }", 2208 whileStmt(hasBody(compoundStmt())))); 2209 EXPECT_TRUE(matches("void f() { do {} while(true); }", 2210 doStmt(hasBody(compoundStmt())))); 2211} 2212 2213TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) { 2214 // The simplest case: every compound statement is in a function 2215 // definition, and the function body itself must be a compound 2216 // statement. 2217 EXPECT_TRUE(matches("void f() { for (;;); }", 2218 compoundStmt(hasAnySubstatement(forStmt())))); 2219} 2220 2221TEST(HasAnySubstatement, IsNotRecursive) { 2222 // It's really "has any immediate substatement". 2223 EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }", 2224 compoundStmt(hasAnySubstatement(forStmt())))); 2225} 2226 2227TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) { 2228 EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }", 2229 compoundStmt(hasAnySubstatement(forStmt())))); 2230} 2231 2232TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) { 2233 EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }", 2234 compoundStmt(hasAnySubstatement(forStmt())))); 2235} 2236 2237TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) { 2238 EXPECT_TRUE(matches("void f() { }", 2239 compoundStmt(statementCountIs(0)))); 2240 EXPECT_TRUE(notMatches("void f() {}", 2241 compoundStmt(statementCountIs(1)))); 2242} 2243 2244TEST(StatementCountIs, AppearsToMatchOnlyOneCount) { 2245 EXPECT_TRUE(matches("void f() { 1; }", 2246 compoundStmt(statementCountIs(1)))); 2247 EXPECT_TRUE(notMatches("void f() { 1; }", 2248 compoundStmt(statementCountIs(0)))); 2249 EXPECT_TRUE(notMatches("void f() { 1; }", 2250 compoundStmt(statementCountIs(2)))); 2251} 2252 2253TEST(StatementCountIs, WorksWithMultipleStatements) { 2254 EXPECT_TRUE(matches("void f() { 1; 2; 3; }", 2255 compoundStmt(statementCountIs(3)))); 2256} 2257 2258TEST(StatementCountIs, WorksWithNestedCompoundStatements) { 2259 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }", 2260 compoundStmt(statementCountIs(1)))); 2261 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }", 2262 compoundStmt(statementCountIs(2)))); 2263 EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }", 2264 compoundStmt(statementCountIs(3)))); 2265 EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }", 2266 compoundStmt(statementCountIs(4)))); 2267} 2268 2269TEST(Member, WorksInSimplestCase) { 2270 EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);", 2271 memberExpr(member(hasName("first"))))); 2272} 2273 2274TEST(Member, DoesNotMatchTheBaseExpression) { 2275 // Don't pick out the wrong part of the member expression, this should 2276 // be checking the member (name) only. 2277 EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);", 2278 memberExpr(member(hasName("first"))))); 2279} 2280 2281TEST(Member, MatchesInMemberFunctionCall) { 2282 EXPECT_TRUE(matches("void f() {" 2283 " struct { void first() {}; } s;" 2284 " s.first();" 2285 "};", 2286 memberExpr(member(hasName("first"))))); 2287} 2288 2289TEST(Member, MatchesMember) { 2290 EXPECT_TRUE(matches( 2291 "struct A { int i; }; void f() { A a; a.i = 2; }", 2292 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger())))))); 2293 EXPECT_TRUE(notMatches( 2294 "struct A { float f; }; void f() { A a; a.f = 2.0f; }", 2295 memberExpr(hasDeclaration(fieldDecl(hasType(isInteger())))))); 2296} 2297 2298TEST(Member, UnderstandsAccess) { 2299 EXPECT_TRUE(matches( 2300 "struct A { int i; };", fieldDecl(isPublic(), hasName("i")))); 2301 EXPECT_TRUE(notMatches( 2302 "struct A { int i; };", fieldDecl(isProtected(), hasName("i")))); 2303 EXPECT_TRUE(notMatches( 2304 "struct A { int i; };", fieldDecl(isPrivate(), hasName("i")))); 2305 2306 EXPECT_TRUE(notMatches( 2307 "class A { int i; };", fieldDecl(isPublic(), hasName("i")))); 2308 EXPECT_TRUE(notMatches( 2309 "class A { int i; };", fieldDecl(isProtected(), hasName("i")))); 2310 EXPECT_TRUE(matches( 2311 "class A { int i; };", fieldDecl(isPrivate(), hasName("i")))); 2312 2313 EXPECT_TRUE(notMatches( 2314 "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i")))); 2315 EXPECT_TRUE(matches("class A { protected: int i; };", 2316 fieldDecl(isProtected(), hasName("i")))); 2317 EXPECT_TRUE(notMatches( 2318 "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i")))); 2319 2320 // Non-member decls have the AccessSpecifier AS_none and thus aren't matched. 2321 EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i")))); 2322 EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i")))); 2323 EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i")))); 2324} 2325 2326TEST(Member, MatchesMemberAllocationFunction) { 2327 // Fails in C++11 mode 2328 EXPECT_TRUE(matchesConditionally( 2329 "namespace std { typedef typeof(sizeof(int)) size_t; }" 2330 "class X { void *operator new(std::size_t); };", 2331 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98")); 2332 2333 EXPECT_TRUE(matches("class X { void operator delete(void*); };", 2334 methodDecl(ofClass(hasName("X"))))); 2335 2336 // Fails in C++11 mode 2337 EXPECT_TRUE(matchesConditionally( 2338 "namespace std { typedef typeof(sizeof(int)) size_t; }" 2339 "class X { void operator delete[](void*, std::size_t); };", 2340 methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98")); 2341} 2342 2343TEST(HasObjectExpression, DoesNotMatchMember) { 2344 EXPECT_TRUE(notMatches( 2345 "class X {}; struct Z { X m; }; void f(Z z) { z.m; }", 2346 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))); 2347} 2348 2349TEST(HasObjectExpression, MatchesBaseOfVariable) { 2350 EXPECT_TRUE(matches( 2351 "struct X { int m; }; void f(X x) { x.m; }", 2352 memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))); 2353 EXPECT_TRUE(matches( 2354 "struct X { int m; }; void f(X* x) { x->m; }", 2355 memberExpr(hasObjectExpression( 2356 hasType(pointsTo(recordDecl(hasName("X")))))))); 2357} 2358 2359TEST(HasObjectExpression, 2360 MatchesObjectExpressionOfImplicitlyFormedMemberExpression) { 2361 EXPECT_TRUE(matches( 2362 "class X {}; struct S { X m; void f() { this->m; } };", 2363 memberExpr(hasObjectExpression( 2364 hasType(pointsTo(recordDecl(hasName("S")))))))); 2365 EXPECT_TRUE(matches( 2366 "class X {}; struct S { X m; void f() { m; } };", 2367 memberExpr(hasObjectExpression( 2368 hasType(pointsTo(recordDecl(hasName("S")))))))); 2369} 2370 2371TEST(Field, DoesNotMatchNonFieldMembers) { 2372 EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m")))); 2373 EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m")))); 2374 EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m")))); 2375 EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m")))); 2376} 2377 2378TEST(Field, MatchesField) { 2379 EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m")))); 2380} 2381 2382TEST(IsConstQualified, MatchesConstInt) { 2383 EXPECT_TRUE(matches("const int i = 42;", 2384 varDecl(hasType(isConstQualified())))); 2385} 2386 2387TEST(IsConstQualified, MatchesConstPointer) { 2388 EXPECT_TRUE(matches("int i = 42; int* const p(&i);", 2389 varDecl(hasType(isConstQualified())))); 2390} 2391 2392TEST(IsConstQualified, MatchesThroughTypedef) { 2393 EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;", 2394 varDecl(hasType(isConstQualified())))); 2395 EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);", 2396 varDecl(hasType(isConstQualified())))); 2397} 2398 2399TEST(IsConstQualified, DoesNotMatchInappropriately) { 2400 EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;", 2401 varDecl(hasType(isConstQualified())))); 2402 EXPECT_TRUE(notMatches("int const* p;", 2403 varDecl(hasType(isConstQualified())))); 2404} 2405 2406TEST(CastExpression, MatchesExplicitCasts) { 2407 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr())); 2408 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr())); 2409 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr())); 2410 EXPECT_TRUE(matches("char c = char(0);", castExpr())); 2411} 2412TEST(CastExpression, MatchesImplicitCasts) { 2413 // This test creates an implicit cast from int to char. 2414 EXPECT_TRUE(matches("char c = 0;", castExpr())); 2415 // This test creates an implicit cast from lvalue to rvalue. 2416 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr())); 2417} 2418 2419TEST(CastExpression, DoesNotMatchNonCasts) { 2420 EXPECT_TRUE(notMatches("char c = '0';", castExpr())); 2421 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr())); 2422 EXPECT_TRUE(notMatches("int i = (0);", castExpr())); 2423 EXPECT_TRUE(notMatches("int i = 0;", castExpr())); 2424} 2425 2426TEST(ReinterpretCast, MatchesSimpleCase) { 2427 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);", 2428 reinterpretCastExpr())); 2429} 2430 2431TEST(ReinterpretCast, DoesNotMatchOtherCasts) { 2432 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr())); 2433 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);", 2434 reinterpretCastExpr())); 2435 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);", 2436 reinterpretCastExpr())); 2437 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};" 2438 "B b;" 2439 "D* p = dynamic_cast<D*>(&b);", 2440 reinterpretCastExpr())); 2441} 2442 2443TEST(FunctionalCast, MatchesSimpleCase) { 2444 std::string foo_class = "class Foo { public: Foo(char*); };"; 2445 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }", 2446 functionalCastExpr())); 2447} 2448 2449TEST(FunctionalCast, DoesNotMatchOtherCasts) { 2450 std::string FooClass = "class Foo { public: Foo(char*); };"; 2451 EXPECT_TRUE( 2452 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }", 2453 functionalCastExpr())); 2454 EXPECT_TRUE( 2455 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }", 2456 functionalCastExpr())); 2457} 2458 2459TEST(DynamicCast, MatchesSimpleCase) { 2460 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};" 2461 "B b;" 2462 "D* p = dynamic_cast<D*>(&b);", 2463 dynamicCastExpr())); 2464} 2465 2466TEST(StaticCast, MatchesSimpleCase) { 2467 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", 2468 staticCastExpr())); 2469} 2470 2471TEST(StaticCast, DoesNotMatchOtherCasts) { 2472 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr())); 2473 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);", 2474 staticCastExpr())); 2475 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);", 2476 staticCastExpr())); 2477 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};" 2478 "B b;" 2479 "D* p = dynamic_cast<D*>(&b);", 2480 staticCastExpr())); 2481} 2482 2483TEST(CStyleCast, MatchesSimpleCase) { 2484 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr())); 2485} 2486 2487TEST(CStyleCast, DoesNotMatchOtherCasts) { 2488 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);" 2489 "char q, *r = const_cast<char*>(&q);" 2490 "void* s = reinterpret_cast<char*>(&s);" 2491 "struct B { virtual ~B() {} }; struct D : B {};" 2492 "B b;" 2493 "D* t = dynamic_cast<D*>(&b);", 2494 cStyleCastExpr())); 2495} 2496 2497TEST(HasDestinationType, MatchesSimpleCase) { 2498 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);", 2499 staticCastExpr(hasDestinationType( 2500 pointsTo(TypeMatcher(anything())))))); 2501} 2502 2503TEST(HasImplicitDestinationType, MatchesSimpleCase) { 2504 // This test creates an implicit const cast. 2505 EXPECT_TRUE(matches("int x; const int i = x;", 2506 implicitCastExpr( 2507 hasImplicitDestinationType(isInteger())))); 2508 // This test creates an implicit array-to-pointer cast. 2509 EXPECT_TRUE(matches("int arr[3]; int *p = arr;", 2510 implicitCastExpr(hasImplicitDestinationType( 2511 pointsTo(TypeMatcher(anything())))))); 2512} 2513 2514TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) { 2515 // This test creates an implicit cast from int to char. 2516 EXPECT_TRUE(notMatches("char c = 0;", 2517 implicitCastExpr(hasImplicitDestinationType( 2518 unless(anything()))))); 2519 // This test creates an implicit array-to-pointer cast. 2520 EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;", 2521 implicitCastExpr(hasImplicitDestinationType( 2522 unless(anything()))))); 2523} 2524 2525TEST(ImplicitCast, MatchesSimpleCase) { 2526 // This test creates an implicit const cast. 2527 EXPECT_TRUE(matches("int x = 0; const int y = x;", 2528 varDecl(hasInitializer(implicitCastExpr())))); 2529 // This test creates an implicit cast from int to char. 2530 EXPECT_TRUE(matches("char c = 0;", 2531 varDecl(hasInitializer(implicitCastExpr())))); 2532 // This test creates an implicit array-to-pointer cast. 2533 EXPECT_TRUE(matches("int arr[6]; int *p = arr;", 2534 varDecl(hasInitializer(implicitCastExpr())))); 2535} 2536 2537TEST(ImplicitCast, DoesNotMatchIncorrectly) { 2538 // This test verifies that implicitCastExpr() matches exactly when implicit casts 2539 // are present, and that it ignores explicit and paren casts. 2540 2541 // These two test cases have no casts. 2542 EXPECT_TRUE(notMatches("int x = 0;", 2543 varDecl(hasInitializer(implicitCastExpr())))); 2544 EXPECT_TRUE(notMatches("int x = 0, &y = x;", 2545 varDecl(hasInitializer(implicitCastExpr())))); 2546 2547 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;", 2548 varDecl(hasInitializer(implicitCastExpr())))); 2549 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);", 2550 varDecl(hasInitializer(implicitCastExpr())))); 2551 2552 EXPECT_TRUE(notMatches("int x = (0);", 2553 varDecl(hasInitializer(implicitCastExpr())))); 2554} 2555 2556TEST(IgnoringImpCasts, MatchesImpCasts) { 2557 // This test checks that ignoringImpCasts matches when implicit casts are 2558 // present and its inner matcher alone does not match. 2559 // Note that this test creates an implicit const cast. 2560 EXPECT_TRUE(matches("int x = 0; const int y = x;", 2561 varDecl(hasInitializer(ignoringImpCasts( 2562 declRefExpr(to(varDecl(hasName("x"))))))))); 2563 // This test creates an implict cast from int to char. 2564 EXPECT_TRUE(matches("char x = 0;", 2565 varDecl(hasInitializer(ignoringImpCasts( 2566 integerLiteral(equals(0))))))); 2567} 2568 2569TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) { 2570 // These tests verify that ignoringImpCasts does not match if the inner 2571 // matcher does not match. 2572 // Note that the first test creates an implicit const cast. 2573 EXPECT_TRUE(notMatches("int x; const int y = x;", 2574 varDecl(hasInitializer(ignoringImpCasts( 2575 unless(anything())))))); 2576 EXPECT_TRUE(notMatches("int x; int y = x;", 2577 varDecl(hasInitializer(ignoringImpCasts( 2578 unless(anything())))))); 2579 2580 // These tests verify that ignoringImplictCasts does not look through explicit 2581 // casts or parentheses. 2582 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);", 2583 varDecl(hasInitializer(ignoringImpCasts( 2584 integerLiteral()))))); 2585 EXPECT_TRUE(notMatches("int i = (0);", 2586 varDecl(hasInitializer(ignoringImpCasts( 2587 integerLiteral()))))); 2588 EXPECT_TRUE(notMatches("float i = (float)0;", 2589 varDecl(hasInitializer(ignoringImpCasts( 2590 integerLiteral()))))); 2591 EXPECT_TRUE(notMatches("float i = float(0);", 2592 varDecl(hasInitializer(ignoringImpCasts( 2593 integerLiteral()))))); 2594} 2595 2596TEST(IgnoringImpCasts, MatchesWithoutImpCasts) { 2597 // This test verifies that expressions that do not have implicit casts 2598 // still match the inner matcher. 2599 EXPECT_TRUE(matches("int x = 0; int &y = x;", 2600 varDecl(hasInitializer(ignoringImpCasts( 2601 declRefExpr(to(varDecl(hasName("x"))))))))); 2602} 2603 2604TEST(IgnoringParenCasts, MatchesParenCasts) { 2605 // This test checks that ignoringParenCasts matches when parentheses and/or 2606 // casts are present and its inner matcher alone does not match. 2607 EXPECT_TRUE(matches("int x = (0);", 2608 varDecl(hasInitializer(ignoringParenCasts( 2609 integerLiteral(equals(0))))))); 2610 EXPECT_TRUE(matches("int x = (((((0)))));", 2611 varDecl(hasInitializer(ignoringParenCasts( 2612 integerLiteral(equals(0))))))); 2613 2614 // This test creates an implict cast from int to char in addition to the 2615 // parentheses. 2616 EXPECT_TRUE(matches("char x = (0);", 2617 varDecl(hasInitializer(ignoringParenCasts( 2618 integerLiteral(equals(0))))))); 2619 2620 EXPECT_TRUE(matches("char x = (char)0;", 2621 varDecl(hasInitializer(ignoringParenCasts( 2622 integerLiteral(equals(0))))))); 2623 EXPECT_TRUE(matches("char* p = static_cast<char*>(0);", 2624 varDecl(hasInitializer(ignoringParenCasts( 2625 integerLiteral(equals(0))))))); 2626} 2627 2628TEST(IgnoringParenCasts, MatchesWithoutParenCasts) { 2629 // This test verifies that expressions that do not have any casts still match. 2630 EXPECT_TRUE(matches("int x = 0;", 2631 varDecl(hasInitializer(ignoringParenCasts( 2632 integerLiteral(equals(0))))))); 2633} 2634 2635TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) { 2636 // These tests verify that ignoringImpCasts does not match if the inner 2637 // matcher does not match. 2638 EXPECT_TRUE(notMatches("int x = ((0));", 2639 varDecl(hasInitializer(ignoringParenCasts( 2640 unless(anything())))))); 2641 2642 // This test creates an implicit cast from int to char in addition to the 2643 // parentheses. 2644 EXPECT_TRUE(notMatches("char x = ((0));", 2645 varDecl(hasInitializer(ignoringParenCasts( 2646 unless(anything())))))); 2647 2648 EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));", 2649 varDecl(hasInitializer(ignoringParenCasts( 2650 unless(anything())))))); 2651} 2652 2653TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) { 2654 // This test checks that ignoringParenAndImpCasts matches when 2655 // parentheses and/or implicit casts are present and its inner matcher alone 2656 // does not match. 2657 // Note that this test creates an implicit const cast. 2658 EXPECT_TRUE(matches("int x = 0; const int y = x;", 2659 varDecl(hasInitializer(ignoringParenImpCasts( 2660 declRefExpr(to(varDecl(hasName("x"))))))))); 2661 // This test creates an implicit cast from int to char. 2662 EXPECT_TRUE(matches("const char x = (0);", 2663 varDecl(hasInitializer(ignoringParenImpCasts( 2664 integerLiteral(equals(0))))))); 2665} 2666 2667TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) { 2668 // This test verifies that expressions that do not have parentheses or 2669 // implicit casts still match. 2670 EXPECT_TRUE(matches("int x = 0; int &y = x;", 2671 varDecl(hasInitializer(ignoringParenImpCasts( 2672 declRefExpr(to(varDecl(hasName("x"))))))))); 2673 EXPECT_TRUE(matches("int x = 0;", 2674 varDecl(hasInitializer(ignoringParenImpCasts( 2675 integerLiteral(equals(0))))))); 2676} 2677 2678TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) { 2679 // These tests verify that ignoringParenImpCasts does not match if 2680 // the inner matcher does not match. 2681 // This test creates an implicit cast. 2682 EXPECT_TRUE(notMatches("char c = ((3));", 2683 varDecl(hasInitializer(ignoringParenImpCasts( 2684 unless(anything())))))); 2685 // These tests verify that ignoringParenAndImplictCasts does not look 2686 // through explicit casts. 2687 EXPECT_TRUE(notMatches("float y = (float(0));", 2688 varDecl(hasInitializer(ignoringParenImpCasts( 2689 integerLiteral()))))); 2690 EXPECT_TRUE(notMatches("float y = (float)0;", 2691 varDecl(hasInitializer(ignoringParenImpCasts( 2692 integerLiteral()))))); 2693 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);", 2694 varDecl(hasInitializer(ignoringParenImpCasts( 2695 integerLiteral()))))); 2696} 2697 2698TEST(HasSourceExpression, MatchesImplicitCasts) { 2699 EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };" 2700 "void r() {string a_string; URL url = a_string; }", 2701 implicitCastExpr( 2702 hasSourceExpression(constructExpr())))); 2703} 2704 2705TEST(HasSourceExpression, MatchesExplicitCasts) { 2706 EXPECT_TRUE(matches("float x = static_cast<float>(42);", 2707 explicitCastExpr( 2708 hasSourceExpression(hasDescendant( 2709 expr(integerLiteral())))))); 2710} 2711 2712TEST(Statement, DoesNotMatchDeclarations) { 2713 EXPECT_TRUE(notMatches("class X {};", stmt())); 2714} 2715 2716TEST(Statement, MatchesCompoundStatments) { 2717 EXPECT_TRUE(matches("void x() {}", stmt())); 2718} 2719 2720TEST(DeclarationStatement, DoesNotMatchCompoundStatements) { 2721 EXPECT_TRUE(notMatches("void x() {}", declStmt())); 2722} 2723 2724TEST(DeclarationStatement, MatchesVariableDeclarationStatements) { 2725 EXPECT_TRUE(matches("void x() { int a; }", declStmt())); 2726} 2727 2728TEST(InitListExpression, MatchesInitListExpression) { 2729 EXPECT_TRUE(matches("int a[] = { 1, 2 };", 2730 initListExpr(hasType(asString("int [2]"))))); 2731 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };", 2732 initListExpr(hasType(recordDecl(hasName("B")))))); 2733} 2734 2735TEST(UsingDeclaration, MatchesUsingDeclarations) { 2736 EXPECT_TRUE(matches("namespace X { int x; } using X::x;", 2737 usingDecl())); 2738} 2739 2740TEST(UsingDeclaration, MatchesShadowUsingDelcarations) { 2741 EXPECT_TRUE(matches("namespace f { int a; } using f::a;", 2742 usingDecl(hasAnyUsingShadowDecl(hasName("a"))))); 2743} 2744 2745TEST(UsingDeclaration, MatchesSpecificTarget) { 2746 EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;", 2747 usingDecl(hasAnyUsingShadowDecl( 2748 hasTargetDecl(functionDecl()))))); 2749 EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;", 2750 usingDecl(hasAnyUsingShadowDecl( 2751 hasTargetDecl(functionDecl()))))); 2752} 2753 2754TEST(UsingDeclaration, ThroughUsingDeclaration) { 2755 EXPECT_TRUE(matches( 2756 "namespace a { void f(); } using a::f; void g() { f(); }", 2757 declRefExpr(throughUsingDecl(anything())))); 2758 EXPECT_TRUE(notMatches( 2759 "namespace a { void f(); } using a::f; void g() { a::f(); }", 2760 declRefExpr(throughUsingDecl(anything())))); 2761} 2762 2763TEST(SingleDecl, IsSingleDecl) { 2764 StatementMatcher SingleDeclStmt = 2765 declStmt(hasSingleDecl(varDecl(hasInitializer(anything())))); 2766 EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt)); 2767 EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt)); 2768 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}", 2769 SingleDeclStmt)); 2770} 2771 2772TEST(DeclStmt, ContainsDeclaration) { 2773 DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything())); 2774 2775 EXPECT_TRUE(matches("void f() {int a = 4;}", 2776 declStmt(containsDeclaration(0, MatchesInit)))); 2777 EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}", 2778 declStmt(containsDeclaration(0, MatchesInit), 2779 containsDeclaration(1, MatchesInit)))); 2780 unsigned WrongIndex = 42; 2781 EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}", 2782 declStmt(containsDeclaration(WrongIndex, 2783 MatchesInit)))); 2784} 2785 2786TEST(DeclCount, DeclCountIsCorrect) { 2787 EXPECT_TRUE(matches("void f() {int i,j;}", 2788 declStmt(declCountIs(2)))); 2789 EXPECT_TRUE(notMatches("void f() {int i,j; int k;}", 2790 declStmt(declCountIs(3)))); 2791 EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}", 2792 declStmt(declCountIs(3)))); 2793} 2794 2795TEST(While, MatchesWhileLoops) { 2796 EXPECT_TRUE(notMatches("void x() {}", whileStmt())); 2797 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt())); 2798 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt())); 2799} 2800 2801TEST(Do, MatchesDoLoops) { 2802 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt())); 2803 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt())); 2804} 2805 2806TEST(Do, DoesNotMatchWhileLoops) { 2807 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt())); 2808} 2809 2810TEST(SwitchCase, MatchesCase) { 2811 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase())); 2812 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase())); 2813 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase())); 2814 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase())); 2815} 2816 2817TEST(SwitchCase, MatchesSwitch) { 2818 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt())); 2819 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt())); 2820 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt())); 2821 EXPECT_TRUE(notMatches("void x() {}", switchStmt())); 2822} 2823 2824TEST(ExceptionHandling, SimpleCases) { 2825 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt())); 2826 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt())); 2827 EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr())); 2828 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }", 2829 throwExpr())); 2830 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }", 2831 throwExpr())); 2832} 2833 2834TEST(HasConditionVariableStatement, DoesNotMatchCondition) { 2835 EXPECT_TRUE(notMatches( 2836 "void x() { if(true) {} }", 2837 ifStmt(hasConditionVariableStatement(declStmt())))); 2838 EXPECT_TRUE(notMatches( 2839 "void x() { int x; if((x = 42)) {} }", 2840 ifStmt(hasConditionVariableStatement(declStmt())))); 2841} 2842 2843TEST(HasConditionVariableStatement, MatchesConditionVariables) { 2844 EXPECT_TRUE(matches( 2845 "void x() { if(int* a = 0) {} }", 2846 ifStmt(hasConditionVariableStatement(declStmt())))); 2847} 2848 2849TEST(ForEach, BindsOneNode) { 2850 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };", 2851 recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))), 2852 new VerifyIdIsBoundTo<FieldDecl>("x", 1))); 2853} 2854 2855TEST(ForEach, BindsMultipleNodes) { 2856 EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };", 2857 recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))), 2858 new VerifyIdIsBoundTo<FieldDecl>("f", 3))); 2859} 2860 2861TEST(ForEach, BindsRecursiveCombinations) { 2862 EXPECT_TRUE(matchAndVerifyResultTrue( 2863 "class C { class D { int x; int y; }; class E { int y; int z; }; };", 2864 recordDecl(hasName("C"), 2865 forEach(recordDecl(forEach(fieldDecl().bind("f"))))), 2866 new VerifyIdIsBoundTo<FieldDecl>("f", 4))); 2867} 2868 2869TEST(ForEachDescendant, BindsOneNode) { 2870 EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };", 2871 recordDecl(hasName("C"), 2872 forEachDescendant(fieldDecl(hasName("x")).bind("x"))), 2873 new VerifyIdIsBoundTo<FieldDecl>("x", 1))); 2874} 2875 2876TEST(ForEachDescendant, NestedForEachDescendant) { 2877 DeclarationMatcher m = recordDecl( 2878 isDefinition(), decl().bind("x"), hasName("C")); 2879 EXPECT_TRUE(matchAndVerifyResultTrue( 2880 "class A { class B { class C {}; }; };", 2881 recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))), 2882 new VerifyIdIsBoundTo<Decl>("x", "C"))); 2883 2884 // FIXME: This is not really a useful matcher, but the result is still 2885 // surprising (currently binds "A"). 2886 //EXPECT_TRUE(matchAndVerifyResultTrue( 2887 // "class A { class B { class C {}; }; };", 2888 // recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))), 2889 // new VerifyIdIsBoundTo<Decl>("x", "C"))); 2890} 2891 2892TEST(ForEachDescendant, BindsMultipleNodes) { 2893 EXPECT_TRUE(matchAndVerifyResultTrue( 2894 "class C { class D { int x; int y; }; " 2895 " class E { class F { int y; int z; }; }; };", 2896 recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))), 2897 new VerifyIdIsBoundTo<FieldDecl>("f", 4))); 2898} 2899 2900TEST(ForEachDescendant, BindsRecursiveCombinations) { 2901 EXPECT_TRUE(matchAndVerifyResultTrue( 2902 "class C { class D { " 2903 " class E { class F { class G { int y; int z; }; }; }; }; };", 2904 recordDecl(hasName("C"), forEachDescendant(recordDecl( 2905 forEachDescendant(fieldDecl().bind("f"))))), 2906 new VerifyIdIsBoundTo<FieldDecl>("f", 8))); 2907} 2908 2909TEST(ForEachDescendant, BindsCorrectNodes) { 2910 EXPECT_TRUE(matchAndVerifyResultTrue( 2911 "class C { void f(); int i; };", 2912 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))), 2913 new VerifyIdIsBoundTo<FieldDecl>("decl", 1))); 2914 EXPECT_TRUE(matchAndVerifyResultTrue( 2915 "class C { void f() {} int i; };", 2916 recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))), 2917 new VerifyIdIsBoundTo<FunctionDecl>("decl", 1))); 2918} 2919 2920TEST(FindAll, BindsNodeOnMatch) { 2921 EXPECT_TRUE(matchAndVerifyResultTrue( 2922 "class A {};", 2923 recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))), 2924 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1))); 2925} 2926 2927TEST(FindAll, BindsDescendantNodeOnMatch) { 2928 EXPECT_TRUE(matchAndVerifyResultTrue( 2929 "class A { int a; int b; };", 2930 recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))), 2931 new VerifyIdIsBoundTo<FieldDecl>("v", 2))); 2932} 2933 2934TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) { 2935 EXPECT_TRUE(matchAndVerifyResultTrue( 2936 "class A { int a; int b; };", 2937 recordDecl(hasName("::A"), 2938 findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"), 2939 fieldDecl().bind("v"))))), 2940 new VerifyIdIsBoundTo<Decl>("v", 3))); 2941 2942 EXPECT_TRUE(matchAndVerifyResultTrue( 2943 "class A { class B {}; class C {}; };", 2944 recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))), 2945 new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3))); 2946} 2947 2948TEST(EachOf, TriggersForEachMatch) { 2949 EXPECT_TRUE(matchAndVerifyResultTrue( 2950 "class A { int a; int b; };", 2951 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 2952 has(fieldDecl(hasName("b")).bind("v")))), 2953 new VerifyIdIsBoundTo<FieldDecl>("v", 2))); 2954} 2955 2956TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) { 2957 EXPECT_TRUE(matchAndVerifyResultTrue( 2958 "class A { int a; int c; };", 2959 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 2960 has(fieldDecl(hasName("b")).bind("v")))), 2961 new VerifyIdIsBoundTo<FieldDecl>("v", 1))); 2962 EXPECT_TRUE(matchAndVerifyResultTrue( 2963 "class A { int c; int b; };", 2964 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 2965 has(fieldDecl(hasName("b")).bind("v")))), 2966 new VerifyIdIsBoundTo<FieldDecl>("v", 1))); 2967 EXPECT_TRUE(notMatches( 2968 "class A { int c; int d; };", 2969 recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 2970 has(fieldDecl(hasName("b")).bind("v")))))); 2971} 2972 2973TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) { 2974 // Make sure that we can both match the class by name (::X) and by the type 2975 // the template was instantiated with (via a field). 2976 2977 EXPECT_TRUE(matches( 2978 "template <typename T> class X {}; class A {}; X<A> x;", 2979 recordDecl(hasName("::X"), isTemplateInstantiation()))); 2980 2981 EXPECT_TRUE(matches( 2982 "template <typename T> class X { T t; }; class A {}; X<A> x;", 2983 recordDecl(isTemplateInstantiation(), hasDescendant( 2984 fieldDecl(hasType(recordDecl(hasName("A")))))))); 2985} 2986 2987TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) { 2988 EXPECT_TRUE(matches( 2989 "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }", 2990 functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))), 2991 isTemplateInstantiation()))); 2992} 2993 2994TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) { 2995 EXPECT_TRUE(matches( 2996 "template <typename T> class X { T t; }; class A {};" 2997 "template class X<A>;", 2998 recordDecl(isTemplateInstantiation(), hasDescendant( 2999 fieldDecl(hasType(recordDecl(hasName("A")))))))); 3000} 3001 3002TEST(IsTemplateInstantiation, 3003 MatchesInstantiationOfPartiallySpecializedClassTemplate) { 3004 EXPECT_TRUE(matches( 3005 "template <typename T> class X {};" 3006 "template <typename T> class X<T*> {}; class A {}; X<A*> x;", 3007 recordDecl(hasName("::X"), isTemplateInstantiation()))); 3008} 3009 3010TEST(IsTemplateInstantiation, 3011 MatchesInstantiationOfClassTemplateNestedInNonTemplate) { 3012 EXPECT_TRUE(matches( 3013 "class A {};" 3014 "class X {" 3015 " template <typename U> class Y { U u; };" 3016 " Y<A> y;" 3017 "};", 3018 recordDecl(hasName("::X::Y"), isTemplateInstantiation()))); 3019} 3020 3021TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) { 3022 // FIXME: Figure out whether this makes sense. It doesn't affect the 3023 // normal use case as long as the uppermost instantiation always is marked 3024 // as template instantiation, but it might be confusing as a predicate. 3025 EXPECT_TRUE(matches( 3026 "class A {};" 3027 "template <typename T> class X {" 3028 " template <typename U> class Y { U u; };" 3029 " Y<T> y;" 3030 "}; X<A> x;", 3031 recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation())))); 3032} 3033 3034TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) { 3035 EXPECT_TRUE(notMatches( 3036 "template <typename T> class X {}; class A {};" 3037 "template <> class X<A> {}; X<A> x;", 3038 recordDecl(hasName("::X"), isTemplateInstantiation()))); 3039} 3040 3041TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) { 3042 EXPECT_TRUE(notMatches( 3043 "class A {}; class Y { A a; };", 3044 recordDecl(isTemplateInstantiation()))); 3045} 3046 3047TEST(IsExplicitTemplateSpecialization, 3048 DoesNotMatchPrimaryTemplate) { 3049 EXPECT_TRUE(notMatches( 3050 "template <typename T> class X {};", 3051 recordDecl(isExplicitTemplateSpecialization()))); 3052 EXPECT_TRUE(notMatches( 3053 "template <typename T> void f(T t);", 3054 functionDecl(isExplicitTemplateSpecialization()))); 3055} 3056 3057TEST(IsExplicitTemplateSpecialization, 3058 DoesNotMatchExplicitTemplateInstantiations) { 3059 EXPECT_TRUE(notMatches( 3060 "template <typename T> class X {};" 3061 "template class X<int>; extern template class X<long>;", 3062 recordDecl(isExplicitTemplateSpecialization()))); 3063 EXPECT_TRUE(notMatches( 3064 "template <typename T> void f(T t) {}" 3065 "template void f(int t); extern template void f(long t);", 3066 functionDecl(isExplicitTemplateSpecialization()))); 3067} 3068 3069TEST(IsExplicitTemplateSpecialization, 3070 DoesNotMatchImplicitTemplateInstantiations) { 3071 EXPECT_TRUE(notMatches( 3072 "template <typename T> class X {}; X<int> x;", 3073 recordDecl(isExplicitTemplateSpecialization()))); 3074 EXPECT_TRUE(notMatches( 3075 "template <typename T> void f(T t); void g() { f(10); }", 3076 functionDecl(isExplicitTemplateSpecialization()))); 3077} 3078 3079TEST(IsExplicitTemplateSpecialization, 3080 MatchesExplicitTemplateSpecializations) { 3081 EXPECT_TRUE(matches( 3082 "template <typename T> class X {};" 3083 "template<> class X<int> {};", 3084 recordDecl(isExplicitTemplateSpecialization()))); 3085 EXPECT_TRUE(matches( 3086 "template <typename T> void f(T t) {}" 3087 "template<> void f(int t) {}", 3088 functionDecl(isExplicitTemplateSpecialization()))); 3089} 3090 3091TEST(HasAncenstor, MatchesDeclarationAncestors) { 3092 EXPECT_TRUE(matches( 3093 "class A { class B { class C {}; }; };", 3094 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A")))))); 3095} 3096 3097TEST(HasAncenstor, FailsIfNoAncestorMatches) { 3098 EXPECT_TRUE(notMatches( 3099 "class A { class B { class C {}; }; };", 3100 recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X")))))); 3101} 3102 3103TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) { 3104 EXPECT_TRUE(matches( 3105 "class A { class B { void f() { C c; } class C {}; }; };", 3106 varDecl(hasName("c"), hasType(recordDecl(hasName("C"), 3107 hasAncestor(recordDecl(hasName("A")))))))); 3108} 3109 3110TEST(HasAncenstor, MatchesStatementAncestors) { 3111 EXPECT_TRUE(matches( 3112 "void f() { if (true) { while (false) { 42; } } }", 3113 integerLiteral(equals(42), hasAncestor(ifStmt())))); 3114} 3115 3116TEST(HasAncestor, DrillsThroughDifferentHierarchies) { 3117 EXPECT_TRUE(matches( 3118 "void f() { if (true) { int x = 42; } }", 3119 integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f")))))); 3120} 3121 3122TEST(HasAncestor, BindsRecursiveCombinations) { 3123 EXPECT_TRUE(matchAndVerifyResultTrue( 3124 "class C { class D { class E { class F { int y; }; }; }; };", 3125 fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))), 3126 new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1))); 3127} 3128 3129TEST(HasAncestor, BindsCombinationsWithHasDescendant) { 3130 EXPECT_TRUE(matchAndVerifyResultTrue( 3131 "class C { class D { class E { class F { int y; }; }; }; };", 3132 fieldDecl(hasAncestor( 3133 decl( 3134 hasDescendant(recordDecl(isDefinition(), 3135 hasAncestor(recordDecl()))) 3136 ).bind("d") 3137 )), 3138 new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E"))); 3139} 3140 3141TEST(HasAncestor, MatchesInTemplateInstantiations) { 3142 EXPECT_TRUE(matches( 3143 "template <typename T> struct A { struct B { struct C { T t; }; }; }; " 3144 "A<int>::B::C a;", 3145 fieldDecl(hasType(asString("int")), 3146 hasAncestor(recordDecl(hasName("A")))))); 3147} 3148 3149TEST(HasAncestor, MatchesInImplicitCode) { 3150 EXPECT_TRUE(matches( 3151 "struct X {}; struct A { A() {} X x; };", 3152 constructorDecl( 3153 hasAnyConstructorInitializer(withInitializer(expr( 3154 hasAncestor(recordDecl(hasName("A"))))))))); 3155} 3156 3157TEST(HasParent, MatchesOnlyParent) { 3158 EXPECT_TRUE(matches( 3159 "void f() { if (true) { int x = 42; } }", 3160 compoundStmt(hasParent(ifStmt())))); 3161 EXPECT_TRUE(notMatches( 3162 "void f() { for (;;) { int x = 42; } }", 3163 compoundStmt(hasParent(ifStmt())))); 3164 EXPECT_TRUE(notMatches( 3165 "void f() { if (true) for (;;) { int x = 42; } }", 3166 compoundStmt(hasParent(ifStmt())))); 3167} 3168 3169TEST(HasAncestor, MatchesAllAncestors) { 3170 EXPECT_TRUE(matches( 3171 "template <typename T> struct C { static void f() { 42; } };" 3172 "void t() { C<int>::f(); }", 3173 integerLiteral( 3174 equals(42), 3175 allOf(hasAncestor(recordDecl(isTemplateInstantiation())), 3176 hasAncestor(recordDecl(unless(isTemplateInstantiation()))))))); 3177} 3178 3179TEST(HasParent, MatchesAllParents) { 3180 EXPECT_TRUE(matches( 3181 "template <typename T> struct C { static void f() { 42; } };" 3182 "void t() { C<int>::f(); }", 3183 integerLiteral( 3184 equals(42), 3185 hasParent(compoundStmt(hasParent(functionDecl( 3186 hasParent(recordDecl(isTemplateInstantiation()))))))))); 3187 EXPECT_TRUE(matches( 3188 "template <typename T> struct C { static void f() { 42; } };" 3189 "void t() { C<int>::f(); }", 3190 integerLiteral( 3191 equals(42), 3192 hasParent(compoundStmt(hasParent(functionDecl( 3193 hasParent(recordDecl(unless(isTemplateInstantiation())))))))))); 3194 EXPECT_TRUE(matches( 3195 "template <typename T> struct C { static void f() { 42; } };" 3196 "void t() { C<int>::f(); }", 3197 integerLiteral(equals(42), 3198 hasParent(compoundStmt(allOf( 3199 hasParent(functionDecl( 3200 hasParent(recordDecl(isTemplateInstantiation())))), 3201 hasParent(functionDecl(hasParent(recordDecl( 3202 unless(isTemplateInstantiation()))))))))))); 3203} 3204 3205TEST(TypeMatching, MatchesTypes) { 3206 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc"))); 3207} 3208 3209TEST(TypeMatching, MatchesArrayTypes) { 3210 EXPECT_TRUE(matches("int a[] = {2,3};", arrayType())); 3211 EXPECT_TRUE(matches("int a[42];", arrayType())); 3212 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType())); 3213 3214 EXPECT_TRUE(notMatches("struct A {}; A a[7];", 3215 arrayType(hasElementType(builtinType())))); 3216 3217 EXPECT_TRUE(matches( 3218 "int const a[] = { 2, 3 };", 3219 qualType(arrayType(hasElementType(builtinType()))))); 3220 EXPECT_TRUE(matches( 3221 "int const a[] = { 2, 3 };", 3222 qualType(isConstQualified(), arrayType(hasElementType(builtinType()))))); 3223 EXPECT_TRUE(matches( 3224 "typedef const int T; T x[] = { 1, 2 };", 3225 qualType(isConstQualified(), arrayType()))); 3226 3227 EXPECT_TRUE(notMatches( 3228 "int a[] = { 2, 3 };", 3229 qualType(isConstQualified(), arrayType(hasElementType(builtinType()))))); 3230 EXPECT_TRUE(notMatches( 3231 "int a[] = { 2, 3 };", 3232 qualType(arrayType(hasElementType(isConstQualified(), builtinType()))))); 3233 EXPECT_TRUE(notMatches( 3234 "int const a[] = { 2, 3 };", 3235 qualType(arrayType(hasElementType(builtinType())), 3236 unless(isConstQualified())))); 3237 3238 EXPECT_TRUE(matches("int a[2];", 3239 constantArrayType(hasElementType(builtinType())))); 3240 EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger()))); 3241} 3242 3243TEST(TypeMatching, MatchesComplexTypes) { 3244 EXPECT_TRUE(matches("_Complex float f;", complexType())); 3245 EXPECT_TRUE(matches( 3246 "_Complex float f;", 3247 complexType(hasElementType(builtinType())))); 3248 EXPECT_TRUE(notMatches( 3249 "_Complex float f;", 3250 complexType(hasElementType(isInteger())))); 3251} 3252 3253TEST(TypeMatching, MatchesConstantArrayTypes) { 3254 EXPECT_TRUE(matches("int a[2];", constantArrayType())); 3255 EXPECT_TRUE(notMatches( 3256 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }", 3257 constantArrayType(hasElementType(builtinType())))); 3258 3259 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42)))); 3260 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42)))); 3261 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42)))); 3262} 3263 3264TEST(TypeMatching, MatchesDependentSizedArrayTypes) { 3265 EXPECT_TRUE(matches( 3266 "template <typename T, int Size> class array { T data[Size]; };", 3267 dependentSizedArrayType())); 3268 EXPECT_TRUE(notMatches( 3269 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }", 3270 dependentSizedArrayType())); 3271} 3272 3273TEST(TypeMatching, MatchesIncompleteArrayType) { 3274 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType())); 3275 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType())); 3276 3277 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }", 3278 incompleteArrayType())); 3279} 3280 3281TEST(TypeMatching, MatchesVariableArrayType) { 3282 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType())); 3283 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType())); 3284 3285 EXPECT_TRUE(matches( 3286 "void f(int b) { int a[b]; }", 3287 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 3288 varDecl(hasName("b"))))))))); 3289} 3290 3291TEST(TypeMatching, MatchesAtomicTypes) { 3292 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType())); 3293 3294 EXPECT_TRUE(matches("_Atomic(int) i;", 3295 atomicType(hasValueType(isInteger())))); 3296 EXPECT_TRUE(notMatches("_Atomic(float) f;", 3297 atomicType(hasValueType(isInteger())))); 3298} 3299 3300TEST(TypeMatching, MatchesAutoTypes) { 3301 EXPECT_TRUE(matches("auto i = 2;", autoType())); 3302 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }", 3303 autoType())); 3304 3305 EXPECT_TRUE(matches("auto a = 1;", 3306 autoType(hasDeducedType(isInteger())))); 3307 EXPECT_TRUE(notMatches("auto b = 2.0;", 3308 autoType(hasDeducedType(isInteger())))); 3309} 3310 3311TEST(TypeMatching, MatchesFunctionTypes) { 3312 EXPECT_TRUE(matches("int (*f)(int);", functionType())); 3313 EXPECT_TRUE(matches("void f(int i) {}", functionType())); 3314} 3315 3316TEST(TypeMatching, PointerTypes) { 3317 // FIXME: Reactive when these tests can be more specific (not matching 3318 // implicit code on certain platforms), likely when we have hasDescendant for 3319 // Types/TypeLocs. 3320 //EXPECT_TRUE(matchAndVerifyResultTrue( 3321 // "int* a;", 3322 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))), 3323 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1))); 3324 //EXPECT_TRUE(matchAndVerifyResultTrue( 3325 // "int* a;", 3326 // pointerTypeLoc().bind("loc"), 3327 // new VerifyIdIsBoundTo<TypeLoc>("loc", 1))); 3328 EXPECT_TRUE(matches( 3329 "int** a;", 3330 loc(pointerType(pointee(qualType()))))); 3331 EXPECT_TRUE(matches( 3332 "int** a;", 3333 loc(pointerType(pointee(pointerType()))))); 3334 EXPECT_TRUE(matches( 3335 "int* b; int* * const a = &b;", 3336 loc(qualType(isConstQualified(), pointerType())))); 3337 3338 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;"; 3339 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3340 hasType(blockPointerType())))); 3341 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"), 3342 hasType(memberPointerType())))); 3343 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3344 hasType(pointerType())))); 3345 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3346 hasType(referenceType())))); 3347 3348 Fragment = "int *ptr;"; 3349 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3350 hasType(blockPointerType())))); 3351 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3352 hasType(memberPointerType())))); 3353 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"), 3354 hasType(pointerType())))); 3355 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 3356 hasType(referenceType())))); 3357 3358 Fragment = "int a; int &ref = a;"; 3359 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 3360 hasType(blockPointerType())))); 3361 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 3362 hasType(memberPointerType())))); 3363 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 3364 hasType(pointerType())))); 3365 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"), 3366 hasType(referenceType())))); 3367} 3368 3369TEST(TypeMatching, PointeeTypes) { 3370 EXPECT_TRUE(matches("int b; int &a = b;", 3371 referenceType(pointee(builtinType())))); 3372 EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType())))); 3373 3374 EXPECT_TRUE(matches("int *a;", 3375 loc(pointerType(pointee(builtinType()))))); 3376 3377 EXPECT_TRUE(matches( 3378 "int const *A;", 3379 pointerType(pointee(isConstQualified(), builtinType())))); 3380 EXPECT_TRUE(notMatches( 3381 "int *A;", 3382 pointerType(pointee(isConstQualified(), builtinType())))); 3383} 3384 3385TEST(TypeMatching, MatchesPointersToConstTypes) { 3386 EXPECT_TRUE(matches("int b; int * const a = &b;", 3387 loc(pointerType()))); 3388 EXPECT_TRUE(matches("int b; int * const a = &b;", 3389 loc(pointerType()))); 3390 EXPECT_TRUE(matches( 3391 "int b; const int * a = &b;", 3392 loc(pointerType(pointee(builtinType()))))); 3393 EXPECT_TRUE(matches( 3394 "int b; const int * a = &b;", 3395 pointerType(pointee(builtinType())))); 3396} 3397 3398TEST(TypeMatching, MatchesTypedefTypes) { 3399 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"), 3400 hasType(typedefType())))); 3401} 3402 3403TEST(NNS, MatchesNestedNameSpecifiers) { 3404 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", 3405 nestedNameSpecifier())); 3406 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };", 3407 nestedNameSpecifier())); 3408 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}", 3409 nestedNameSpecifier())); 3410 3411 EXPECT_TRUE(matches( 3412 "struct A { static void f() {} }; void g() { A::f(); }", 3413 nestedNameSpecifier())); 3414 EXPECT_TRUE(notMatches( 3415 "struct A { static void f() {} }; void g(A* a) { a->f(); }", 3416 nestedNameSpecifier())); 3417} 3418 3419TEST(NullStatement, SimpleCases) { 3420 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt())); 3421 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt())); 3422} 3423 3424TEST(NNS, MatchesTypes) { 3425 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier( 3426 specifiesType(hasDeclaration(recordDecl(hasName("A"))))); 3427 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher)); 3428 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;", 3429 Matcher)); 3430 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher)); 3431} 3432 3433TEST(NNS, MatchesNamespaceDecls) { 3434 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier( 3435 specifiesNamespace(hasName("ns"))); 3436 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher)); 3437 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher)); 3438 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher)); 3439} 3440 3441TEST(NNS, BindsNestedNameSpecifiers) { 3442 EXPECT_TRUE(matchAndVerifyResultTrue( 3443 "namespace ns { struct E { struct B {}; }; } ns::E::B b;", 3444 nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"), 3445 new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::"))); 3446} 3447 3448TEST(NNS, BindsNestedNameSpecifierLocs) { 3449 EXPECT_TRUE(matchAndVerifyResultTrue( 3450 "namespace ns { struct B {}; } ns::B b;", 3451 loc(nestedNameSpecifier()).bind("loc"), 3452 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1))); 3453} 3454 3455TEST(NNS, MatchesNestedNameSpecifierPrefixes) { 3456 EXPECT_TRUE(matches( 3457 "struct A { struct B { struct C {}; }; }; A::B::C c;", 3458 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))))); 3459 EXPECT_TRUE(matches( 3460 "struct A { struct B { struct C {}; }; }; A::B::C c;", 3461 nestedNameSpecifierLoc(hasPrefix( 3462 specifiesTypeLoc(loc(qualType(asString("struct A")))))))); 3463} 3464 3465TEST(NNS, DescendantsOfNestedNameSpecifiers) { 3466 std::string Fragment = 3467 "namespace a { struct A { struct B { struct C {}; }; }; };" 3468 "void f() { a::A::B::C c; }"; 3469 EXPECT_TRUE(matches( 3470 Fragment, 3471 nestedNameSpecifier(specifiesType(asString("struct a::A::B")), 3472 hasDescendant(nestedNameSpecifier( 3473 specifiesNamespace(hasName("a"))))))); 3474 EXPECT_TRUE(notMatches( 3475 Fragment, 3476 nestedNameSpecifier(specifiesType(asString("struct a::A::B")), 3477 has(nestedNameSpecifier( 3478 specifiesNamespace(hasName("a"))))))); 3479 EXPECT_TRUE(matches( 3480 Fragment, 3481 nestedNameSpecifier(specifiesType(asString("struct a::A")), 3482 has(nestedNameSpecifier( 3483 specifiesNamespace(hasName("a"))))))); 3484 3485 // Not really useful because a NestedNameSpecifier can af at most one child, 3486 // but to complete the interface. 3487 EXPECT_TRUE(matchAndVerifyResultTrue( 3488 Fragment, 3489 nestedNameSpecifier(specifiesType(asString("struct a::A::B")), 3490 forEach(nestedNameSpecifier().bind("x"))), 3491 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1))); 3492} 3493 3494TEST(NNS, NestedNameSpecifiersAsDescendants) { 3495 std::string Fragment = 3496 "namespace a { struct A { struct B { struct C {}; }; }; };" 3497 "void f() { a::A::B::C c; }"; 3498 EXPECT_TRUE(matches( 3499 Fragment, 3500 decl(hasDescendant(nestedNameSpecifier(specifiesType( 3501 asString("struct a::A"))))))); 3502 EXPECT_TRUE(matchAndVerifyResultTrue( 3503 Fragment, 3504 functionDecl(hasName("f"), 3505 forEachDescendant(nestedNameSpecifier().bind("x"))), 3506 // Nested names: a, a::A and a::A::B. 3507 new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3))); 3508} 3509 3510TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) { 3511 std::string Fragment = 3512 "namespace a { struct A { struct B { struct C {}; }; }; };" 3513 "void f() { a::A::B::C c; }"; 3514 EXPECT_TRUE(matches( 3515 Fragment, 3516 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), 3517 hasDescendant(loc(nestedNameSpecifier( 3518 specifiesNamespace(hasName("a")))))))); 3519 EXPECT_TRUE(notMatches( 3520 Fragment, 3521 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), 3522 has(loc(nestedNameSpecifier( 3523 specifiesNamespace(hasName("a")))))))); 3524 EXPECT_TRUE(matches( 3525 Fragment, 3526 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))), 3527 has(loc(nestedNameSpecifier( 3528 specifiesNamespace(hasName("a")))))))); 3529 3530 EXPECT_TRUE(matchAndVerifyResultTrue( 3531 Fragment, 3532 nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), 3533 forEach(nestedNameSpecifierLoc().bind("x"))), 3534 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1))); 3535} 3536 3537TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) { 3538 std::string Fragment = 3539 "namespace a { struct A { struct B { struct C {}; }; }; };" 3540 "void f() { a::A::B::C c; }"; 3541 EXPECT_TRUE(matches( 3542 Fragment, 3543 decl(hasDescendant(loc(nestedNameSpecifier(specifiesType( 3544 asString("struct a::A")))))))); 3545 EXPECT_TRUE(matchAndVerifyResultTrue( 3546 Fragment, 3547 functionDecl(hasName("f"), 3548 forEachDescendant(nestedNameSpecifierLoc().bind("x"))), 3549 // Nested names: a, a::A and a::A::B. 3550 new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3))); 3551} 3552 3553template <typename T> class VerifyMatchOnNode : public BoundNodesCallback { 3554public: 3555 VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher, 3556 StringRef InnerId) 3557 : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) { 3558 } 3559 3560 virtual bool run(const BoundNodes *Nodes) { return false; } 3561 3562 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) { 3563 const T *Node = Nodes->getNodeAs<T>(Id); 3564 return selectFirst<const T>(InnerId, 3565 match(InnerMatcher, *Node, *Context)) != NULL; 3566 } 3567private: 3568 std::string Id; 3569 internal::Matcher<T> InnerMatcher; 3570 std::string InnerId; 3571}; 3572 3573TEST(MatchFinder, CanMatchDeclarationsRecursively) { 3574 EXPECT_TRUE(matchAndVerifyResultTrue( 3575 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), 3576 new VerifyMatchOnNode<clang::Decl>( 3577 "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))), 3578 "Y"))); 3579 EXPECT_TRUE(matchAndVerifyResultFalse( 3580 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), 3581 new VerifyMatchOnNode<clang::Decl>( 3582 "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))), 3583 "Z"))); 3584} 3585 3586TEST(MatchFinder, CanMatchStatementsRecursively) { 3587 EXPECT_TRUE(matchAndVerifyResultTrue( 3588 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"), 3589 new VerifyMatchOnNode<clang::Stmt>( 3590 "if", stmt(hasDescendant(forStmt().bind("for"))), "for"))); 3591 EXPECT_TRUE(matchAndVerifyResultFalse( 3592 "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"), 3593 new VerifyMatchOnNode<clang::Stmt>( 3594 "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl"))); 3595} 3596 3597TEST(MatchFinder, CanMatchSingleNodesRecursively) { 3598 EXPECT_TRUE(matchAndVerifyResultTrue( 3599 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), 3600 new VerifyMatchOnNode<clang::Decl>( 3601 "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y"))); 3602 EXPECT_TRUE(matchAndVerifyResultFalse( 3603 "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), 3604 new VerifyMatchOnNode<clang::Decl>( 3605 "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z"))); 3606} 3607 3608template <typename T> 3609class VerifyAncestorHasChildIsEqual : public BoundNodesCallback { 3610public: 3611 virtual bool run(const BoundNodes *Nodes) { return false; } 3612 3613 virtual bool run(const BoundNodes *Nodes, ASTContext *Context) { 3614 const T *Node = Nodes->getNodeAs<T>(""); 3615 return verify(*Nodes, *Context, Node); 3616 } 3617 3618 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) { 3619 return selectFirst<const T>( 3620 "", match(stmt(hasParent(stmt(has(stmt(equalsNode(Node)))).bind(""))), 3621 *Node, Context)) != NULL; 3622 } 3623 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) { 3624 return selectFirst<const T>( 3625 "", match(decl(hasParent(decl(has(decl(equalsNode(Node)))).bind(""))), 3626 *Node, Context)) != NULL; 3627 } 3628}; 3629 3630TEST(IsEqualTo, MatchesNodesByIdentity) { 3631 EXPECT_TRUE(matchAndVerifyResultTrue( 3632 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""), 3633 new VerifyAncestorHasChildIsEqual<Decl>())); 3634 EXPECT_TRUE( 3635 matchAndVerifyResultTrue("void f() { if(true) {} }", ifStmt().bind(""), 3636 new VerifyAncestorHasChildIsEqual<Stmt>())); 3637} 3638 3639class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback { 3640public: 3641 VerifyStartOfTranslationUnit() : Called(false) {} 3642 virtual void run(const MatchFinder::MatchResult &Result) { 3643 EXPECT_TRUE(Called); 3644 } 3645 virtual void onStartOfTranslationUnit() { 3646 Called = true; 3647 } 3648 bool Called; 3649}; 3650 3651TEST(MatchFinder, InterceptsStartOfTranslationUnit) { 3652 MatchFinder Finder; 3653 VerifyStartOfTranslationUnit VerifyCallback; 3654 Finder.addMatcher(decl(), &VerifyCallback); 3655 OwningPtr<FrontendActionFactory> Factory(newFrontendActionFactory(&Finder)); 3656 ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;")); 3657 EXPECT_TRUE(VerifyCallback.Called); 3658} 3659 3660} // end namespace ast_matchers 3661} // end namespace clang 3662