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