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