1 //== unittests/ASTMatchers/ASTMatchersNodeTest.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 "llvm/ADT/Triple.h" 16 #include "llvm/Support/Host.h" 17 #include "gtest/gtest.h" 18 19 namespace clang { 20 namespace ast_matchers { 21 22 TEST(Finder, DynamicOnlyAcceptsSomeMatchers) { 23 MatchFinder Finder; 24 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr)); 25 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr)); 26 EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)), 27 nullptr)); 28 29 // Do not accept non-toplevel matchers. 30 EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr)); 31 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr)); 32 } 33 34 TEST(Decl, MatchesDeclarations) { 35 EXPECT_TRUE(notMatches("", decl(usingDecl()))); 36 EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;", 37 decl(usingDecl()))); 38 } 39 40 TEST(NameableDeclaration, MatchesVariousDecls) { 41 DeclarationMatcher NamedX = namedDecl(hasName("X")); 42 EXPECT_TRUE(matches("typedef int X;", NamedX)); 43 EXPECT_TRUE(matches("int X;", NamedX)); 44 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX)); 45 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX)); 46 EXPECT_TRUE(matches("void foo() { int X; }", NamedX)); 47 EXPECT_TRUE(matches("namespace X { }", NamedX)); 48 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX)); 49 50 EXPECT_TRUE(notMatches("#define X 1", NamedX)); 51 } 52 53 TEST(NameableDeclaration, REMatchesVariousDecls) { 54 DeclarationMatcher NamedX = namedDecl(matchesName("::X")); 55 EXPECT_TRUE(matches("typedef int Xa;", NamedX)); 56 EXPECT_TRUE(matches("int Xb;", NamedX)); 57 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX)); 58 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX)); 59 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX)); 60 EXPECT_TRUE(matches("namespace Xij { }", NamedX)); 61 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX)); 62 63 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX)); 64 65 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no")); 66 EXPECT_TRUE(matches("int no_foo;", StartsWithNo)); 67 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo)); 68 69 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c")); 70 EXPECT_TRUE(matches("int abc;", Abc)); 71 EXPECT_TRUE(matches("int aFOObBARc;", Abc)); 72 EXPECT_TRUE(notMatches("int cab;", Abc)); 73 EXPECT_TRUE(matches("int cabc;", Abc)); 74 75 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$")); 76 EXPECT_TRUE(matches("int k;", StartsWithK)); 77 EXPECT_TRUE(matches("int kAbc;", StartsWithK)); 78 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK)); 79 EXPECT_TRUE(matches("class C { int k; };", StartsWithK)); 80 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK)); 81 } 82 83 TEST(DeclarationMatcher, MatchClass) { 84 DeclarationMatcher ClassMatcher(recordDecl()); 85 86 // This passes on Windows only because we explicitly pass -target 87 // i386-unknown-unknown. If we were to compile with the default target 88 // triple, we'd want to EXPECT_TRUE if it's Win32 or MSVC. 89 EXPECT_FALSE(matches("", ClassMatcher)); 90 91 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X"))); 92 EXPECT_TRUE(matches("class X;", ClassX)); 93 EXPECT_TRUE(matches("class X {};", ClassX)); 94 EXPECT_TRUE(matches("template<class T> class X {};", ClassX)); 95 EXPECT_TRUE(notMatches("", ClassX)); 96 } 97 98 TEST(DeclarationMatcher, translationUnitDecl) { 99 const std::string Code = "int MyVar1;\n" 100 "namespace NameSpace {\n" 101 "int MyVar2;\n" 102 "} // namespace NameSpace\n"; 103 EXPECT_TRUE(matches( 104 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl())))); 105 EXPECT_FALSE(matches( 106 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl())))); 107 EXPECT_TRUE(matches( 108 Code, 109 varDecl(hasName("MyVar2"), 110 hasDeclContext(decl(hasDeclContext(translationUnitDecl())))))); 111 } 112 113 TEST(DeclarationMatcher, LinkageSpecification) { 114 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl())); 115 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl())); 116 } 117 118 TEST(ClassTemplate, DoesNotMatchClass) { 119 DeclarationMatcher ClassX = classTemplateDecl(hasName("X")); 120 EXPECT_TRUE(notMatches("class X;", ClassX)); 121 EXPECT_TRUE(notMatches("class X {};", ClassX)); 122 } 123 124 TEST(ClassTemplate, MatchesClassTemplate) { 125 DeclarationMatcher ClassX = classTemplateDecl(hasName("X")); 126 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX)); 127 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX)); 128 } 129 130 TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) { 131 EXPECT_TRUE(notMatches("template<typename T> class X { };" 132 "template<> class X<int> { int a; };", 133 classTemplateDecl(hasName("X"), 134 hasDescendant(fieldDecl(hasName("a")))))); 135 } 136 137 TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) { 138 EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };" 139 "template<typename T> class X<T, int> { int a; };", 140 classTemplateDecl(hasName("X"), 141 hasDescendant(fieldDecl(hasName("a")))))); 142 } 143 144 TEST(DeclarationMatcher, MatchCudaDecl) { 145 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }" 146 "void g() { f<<<1, 2>>>(); }", 147 cudaKernelCallExpr())); 148 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}", 149 hasAttr(clang::attr::CUDADevice))); 150 EXPECT_TRUE(notMatchesWithCuda("void f() {}", 151 cudaKernelCallExpr())); 152 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}", 153 hasAttr(clang::attr::CUDAGlobal))); 154 } 155 156 TEST(ValueDecl, Matches) { 157 EXPECT_TRUE(matches("enum EnumType { EnumValue };", 158 valueDecl(hasType(asString("enum EnumType"))))); 159 EXPECT_TRUE(matches("void FunctionDecl();", 160 valueDecl(hasType(asString("void (void)"))))); 161 } 162 163 TEST(Enum, DoesNotMatchClasses) { 164 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X")))); 165 } 166 167 TEST(Enum, MatchesEnums) { 168 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X")))); 169 } 170 171 TEST(EnumConstant, Matches) { 172 DeclarationMatcher Matcher = enumConstantDecl(hasName("A")); 173 EXPECT_TRUE(matches("enum X{ A };", Matcher)); 174 EXPECT_TRUE(notMatches("enum X{ B };", Matcher)); 175 EXPECT_TRUE(notMatches("enum X {};", Matcher)); 176 } 177 178 TEST(Matcher, UnresolvedLookupExpr) { 179 // FIXME: The test is known to be broken on Windows with delayed template 180 // parsing. 181 EXPECT_TRUE(matchesConditionally("template<typename T>" 182 "T foo() { T a; return a; }" 183 "template<typename T>" 184 "void bar() {" 185 " foo<T>();" 186 "}", 187 unresolvedLookupExpr(), 188 /*ExpectMatch=*/true, 189 "-fno-delayed-template-parsing")); 190 } 191 192 TEST(Matcher, Call) { 193 // FIXME: Do we want to overload Call() to directly take 194 // Matcher<Decl>, too? 195 StatementMatcher MethodX = 196 callExpr(hasDeclaration(cxxMethodDecl(hasName("x")))); 197 198 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX)); 199 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX)); 200 201 StatementMatcher MethodOnY = 202 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y"))))); 203 204 EXPECT_TRUE( 205 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 206 MethodOnY)); 207 EXPECT_TRUE( 208 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 209 MethodOnY)); 210 EXPECT_TRUE( 211 notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 212 MethodOnY)); 213 EXPECT_TRUE( 214 notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 215 MethodOnY)); 216 EXPECT_TRUE( 217 notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 218 MethodOnY)); 219 220 StatementMatcher MethodOnYPointer = 221 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))); 222 223 EXPECT_TRUE( 224 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 225 MethodOnYPointer)); 226 EXPECT_TRUE( 227 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 228 MethodOnYPointer)); 229 EXPECT_TRUE( 230 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 231 MethodOnYPointer)); 232 EXPECT_TRUE( 233 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 234 MethodOnYPointer)); 235 EXPECT_TRUE( 236 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 237 MethodOnYPointer)); 238 } 239 TEST(Matcher, Lambda) { 240 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", 241 lambdaExpr())); 242 } 243 244 TEST(Matcher, ForRange) { 245 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };" 246 "void f() { for (auto &a : as); }", 247 cxxForRangeStmt())); 248 EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }", 249 cxxForRangeStmt())); 250 } 251 252 TEST(Matcher, SubstNonTypeTemplateParm) { 253 EXPECT_FALSE(matches("template<int N>\n" 254 "struct A { static const int n = 0; };\n" 255 "struct B : public A<42> {};", 256 substNonTypeTemplateParmExpr())); 257 EXPECT_TRUE(matches("template<int N>\n" 258 "struct A { static const int n = N; };\n" 259 "struct B : public A<42> {};", 260 substNonTypeTemplateParmExpr())); 261 } 262 263 TEST(Matcher, NonTypeTemplateParmDecl) { 264 EXPECT_TRUE(matches("template <int N> void f();", 265 nonTypeTemplateParmDecl(hasName("N")))); 266 EXPECT_TRUE( 267 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl())); 268 } 269 270 TEST(Matcher, templateTypeParmDecl) { 271 EXPECT_TRUE(matches("template <typename T> void f();", 272 templateTypeParmDecl(hasName("T")))); 273 EXPECT_TRUE( 274 notMatches("template <int N> void f();", templateTypeParmDecl())); 275 } 276 277 TEST(Matcher, UserDefinedLiteral) { 278 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {" 279 " return i + 1;" 280 "}" 281 "char c = 'a'_inc;", 282 userDefinedLiteral())); 283 } 284 285 TEST(Matcher, FlowControl) { 286 EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt())); 287 EXPECT_TRUE(matches("void f() { while(true) { continue; } }", 288 continueStmt())); 289 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt())); 290 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", 291 labelStmt( 292 hasDeclaration( 293 labelDecl(hasName("FOO")))))); 294 EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }", 295 addrLabelExpr())); 296 EXPECT_TRUE(matches("void f() { return; }", returnStmt())); 297 } 298 299 TEST(Matcher, OverloadedOperatorCall) { 300 StatementMatcher OpCall = cxxOperatorCallExpr(); 301 // Unary operator 302 EXPECT_TRUE(matches("class Y { }; " 303 "bool operator!(Y x) { return false; }; " 304 "Y y; bool c = !y;", OpCall)); 305 // No match -- special operators like "new", "delete" 306 // FIXME: operator new takes size_t, for which we need stddef.h, for which 307 // we need to figure out include paths in the test. 308 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n" 309 // "class Y { }; " 310 // "void *operator new(size_t size) { return 0; } " 311 // "Y *y = new Y;", OpCall)); 312 EXPECT_TRUE(notMatches("class Y { }; " 313 "void operator delete(void *p) { } " 314 "void a() {Y *y = new Y; delete y;}", OpCall)); 315 // Binary operator 316 EXPECT_TRUE(matches("class Y { }; " 317 "bool operator&&(Y x, Y y) { return true; }; " 318 "Y a; Y b; bool c = a && b;", 319 OpCall)); 320 // No match -- normal operator, not an overloaded one. 321 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall)); 322 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall)); 323 } 324 325 TEST(Matcher, ThisPointerType) { 326 StatementMatcher MethodOnY = 327 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))); 328 329 EXPECT_TRUE( 330 matches("class Y { public: void x(); }; void z() { Y y; y.x(); }", 331 MethodOnY)); 332 EXPECT_TRUE( 333 matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }", 334 MethodOnY)); 335 EXPECT_TRUE( 336 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }", 337 MethodOnY)); 338 EXPECT_TRUE( 339 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }", 340 MethodOnY)); 341 EXPECT_TRUE( 342 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }", 343 MethodOnY)); 344 345 EXPECT_TRUE(matches( 346 "class Y {" 347 " public: virtual void x();" 348 "};" 349 "class X : public Y {" 350 " public: virtual void x();" 351 "};" 352 "void z() { X *x; x->Y::x(); }", MethodOnY)); 353 } 354 355 TEST(Matcher, VariableUsage) { 356 StatementMatcher Reference = 357 declRefExpr(to( 358 varDecl(hasInitializer( 359 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))))))); 360 361 EXPECT_TRUE(matches( 362 "class Y {" 363 " public:" 364 " bool x() const;" 365 "};" 366 "void z(const Y &y) {" 367 " bool b = y.x();" 368 " if (b) {}" 369 "}", Reference)); 370 371 EXPECT_TRUE(notMatches( 372 "class Y {" 373 " public:" 374 " bool x() const;" 375 "};" 376 "void z(const Y &y) {" 377 " bool b = y.x();" 378 "}", Reference)); 379 } 380 381 TEST(Matcher, CalledVariable) { 382 StatementMatcher CallOnVariableY = 383 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y")))))); 384 385 EXPECT_TRUE(matches( 386 "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY)); 387 EXPECT_TRUE(matches( 388 "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY)); 389 EXPECT_TRUE(matches( 390 "class Y { public: void x(); };" 391 "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY)); 392 EXPECT_TRUE(matches( 393 "class Y { public: void x(); };" 394 "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY)); 395 EXPECT_TRUE(notMatches( 396 "class Y { public: void x(); };" 397 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };", 398 CallOnVariableY)); 399 } 400 401 TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) { 402 EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", 403 unaryExprOrTypeTraitExpr())); 404 EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", 405 alignOfExpr(anything()))); 406 // FIXME: Uncomment once alignof is enabled. 407 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }", 408 // unaryExprOrTypeTraitExpr())); 409 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }", 410 // sizeOfExpr())); 411 } 412 413 TEST(MemberExpression, DoesNotMatchClasses) { 414 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr())); 415 } 416 417 TEST(MemberExpression, MatchesMemberFunctionCall) { 418 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr())); 419 } 420 421 TEST(MemberExpression, MatchesVariable) { 422 EXPECT_TRUE( 423 matches("class Y { void x() { this->y; } int y; };", memberExpr())); 424 EXPECT_TRUE( 425 matches("class Y { void x() { y; } int y; };", memberExpr())); 426 EXPECT_TRUE( 427 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr())); 428 } 429 430 TEST(MemberExpression, MatchesStaticVariable) { 431 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };", 432 memberExpr())); 433 EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };", 434 memberExpr())); 435 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };", 436 memberExpr())); 437 } 438 439 TEST(Function, MatchesFunctionDeclarations) { 440 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f")))); 441 442 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF)); 443 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF)); 444 445 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() != 446 llvm::Triple::Win32) { 447 // FIXME: Make this work for MSVC. 448 // Dependent contexts, but a non-dependent call. 449 EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }", 450 CallFunctionF)); 451 EXPECT_TRUE( 452 matches("void f(); template <int N> struct S { void g() { f(); } };", 453 CallFunctionF)); 454 } 455 456 // Depedent calls don't match. 457 EXPECT_TRUE( 458 notMatches("void f(int); template <typename T> void g(T t) { f(t); }", 459 CallFunctionF)); 460 EXPECT_TRUE( 461 notMatches("void f(int);" 462 "template <typename T> struct S { void g(T t) { f(t); } };", 463 CallFunctionF)); 464 465 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic()))); 466 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic()))); 467 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);", 468 functionDecl(isVariadic()))); 469 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic()))); 470 EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic()))); 471 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0)))); 472 EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0)))); 473 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1)))); 474 } 475 476 TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) { 477 EXPECT_TRUE( 478 matches("template <typename T> void f(T t) {}", 479 functionTemplateDecl(hasName("f")))); 480 } 481 482 TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) { 483 EXPECT_TRUE( 484 notMatches("void f(double d); void f(int t) {}", 485 functionTemplateDecl(hasName("f")))); 486 } 487 488 TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) { 489 EXPECT_TRUE( 490 notMatches("void g(); template <typename T> void f(T t) {}" 491 "template <> void f(int t) { g(); }", 492 functionTemplateDecl(hasName("f"), 493 hasDescendant(declRefExpr(to( 494 functionDecl(hasName("g")))))))); 495 } 496 497 TEST(Matcher, MatchesClassTemplateSpecialization) { 498 EXPECT_TRUE(matches("template<typename T> struct A {};" 499 "template<> struct A<int> {};", 500 classTemplateSpecializationDecl())); 501 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;", 502 classTemplateSpecializationDecl())); 503 EXPECT_TRUE(notMatches("template<typename T> struct A {};", 504 classTemplateSpecializationDecl())); 505 } 506 507 TEST(DeclaratorDecl, MatchesDeclaratorDecls) { 508 EXPECT_TRUE(matches("int x;", declaratorDecl())); 509 EXPECT_TRUE(notMatches("class A {};", declaratorDecl())); 510 } 511 512 TEST(ParmVarDecl, MatchesParmVars) { 513 EXPECT_TRUE(matches("void f(int x);", parmVarDecl())); 514 EXPECT_TRUE(notMatches("void f();", parmVarDecl())); 515 } 516 517 TEST(Matcher, ConstructorCall) { 518 StatementMatcher Constructor = cxxConstructExpr(); 519 520 EXPECT_TRUE( 521 matches("class X { public: X(); }; void x() { X x; }", Constructor)); 522 EXPECT_TRUE( 523 matches("class X { public: X(); }; void x() { X x = X(); }", 524 Constructor)); 525 EXPECT_TRUE( 526 matches("class X { public: X(int); }; void x() { X x = 0; }", 527 Constructor)); 528 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor)); 529 } 530 531 TEST(Match, ConstructorInitializers) { 532 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };", 533 cxxCtorInitializer(forField(hasName("i"))))); 534 } 535 536 TEST(Matcher, ThisExpr) { 537 EXPECT_TRUE( 538 matches("struct X { int a; int f () { return a; } };", cxxThisExpr())); 539 EXPECT_TRUE( 540 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr())); 541 } 542 543 TEST(Matcher, BindTemporaryExpression) { 544 StatementMatcher TempExpression = cxxBindTemporaryExpr(); 545 546 std::string ClassString = "class string { public: string(); ~string(); }; "; 547 548 EXPECT_TRUE( 549 matches(ClassString + 550 "string GetStringByValue();" 551 "void FunctionTakesString(string s);" 552 "void run() { FunctionTakesString(GetStringByValue()); }", 553 TempExpression)); 554 555 EXPECT_TRUE( 556 notMatches(ClassString + 557 "string* GetStringPointer(); " 558 "void FunctionTakesStringPtr(string* s);" 559 "void run() {" 560 " string* s = GetStringPointer();" 561 " FunctionTakesStringPtr(GetStringPointer());" 562 " FunctionTakesStringPtr(s);" 563 "}", 564 TempExpression)); 565 566 EXPECT_TRUE( 567 notMatches("class no_dtor {};" 568 "no_dtor GetObjByValue();" 569 "void ConsumeObj(no_dtor param);" 570 "void run() { ConsumeObj(GetObjByValue()); }", 571 TempExpression)); 572 } 573 574 TEST(MaterializeTemporaryExpr, MatchesTemporary) { 575 std::string ClassString = 576 "class string { public: string(); int length(); }; "; 577 578 EXPECT_TRUE( 579 matches(ClassString + 580 "string GetStringByValue();" 581 "void FunctionTakesString(string s);" 582 "void run() { FunctionTakesString(GetStringByValue()); }", 583 materializeTemporaryExpr())); 584 585 EXPECT_TRUE( 586 notMatches(ClassString + 587 "string* GetStringPointer(); " 588 "void FunctionTakesStringPtr(string* s);" 589 "void run() {" 590 " string* s = GetStringPointer();" 591 " FunctionTakesStringPtr(GetStringPointer());" 592 " FunctionTakesStringPtr(s);" 593 "}", 594 materializeTemporaryExpr())); 595 596 EXPECT_TRUE( 597 matches(ClassString + 598 "string GetStringByValue();" 599 "void run() { int k = GetStringByValue().length(); }", 600 materializeTemporaryExpr())); 601 602 EXPECT_TRUE( 603 notMatches(ClassString + 604 "string GetStringByValue();" 605 "void run() { GetStringByValue(); }", 606 materializeTemporaryExpr())); 607 } 608 609 TEST(Matcher, NewExpression) { 610 StatementMatcher New = cxxNewExpr(); 611 612 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New)); 613 EXPECT_TRUE( 614 matches("class X { public: X(); }; void x() { new X(); }", New)); 615 EXPECT_TRUE( 616 matches("class X { public: X(int); }; void x() { new X(0); }", New)); 617 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New)); 618 } 619 620 TEST(Matcher, DeleteExpression) { 621 EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }", 622 cxxDeleteExpr())); 623 } 624 625 TEST(Matcher, DefaultArgument) { 626 StatementMatcher Arg = cxxDefaultArgExpr(); 627 628 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg)); 629 EXPECT_TRUE( 630 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg)); 631 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg)); 632 } 633 634 TEST(Matcher, StringLiterals) { 635 StatementMatcher Literal = stringLiteral(); 636 EXPECT_TRUE(matches("const char *s = \"string\";", Literal)); 637 // wide string 638 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal)); 639 // with escaped characters 640 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal)); 641 // no matching -- though the data type is the same, there is no string literal 642 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal)); 643 } 644 645 TEST(Matcher, CharacterLiterals) { 646 StatementMatcher CharLiteral = characterLiteral(); 647 EXPECT_TRUE(matches("const char c = 'c';", CharLiteral)); 648 // wide character 649 EXPECT_TRUE(matches("const char c = L'c';", CharLiteral)); 650 // wide character, Hex encoded, NOT MATCHED! 651 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral)); 652 EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral)); 653 } 654 655 TEST(Matcher, IntegerLiterals) { 656 StatementMatcher HasIntLiteral = integerLiteral(); 657 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral)); 658 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral)); 659 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral)); 660 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral)); 661 662 // Non-matching cases (character literals, float and double) 663 EXPECT_TRUE(notMatches("int i = L'a';", 664 HasIntLiteral)); // this is actually a character 665 // literal cast to int 666 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral)); 667 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral)); 668 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral)); 669 } 670 671 TEST(Matcher, FloatLiterals) { 672 StatementMatcher HasFloatLiteral = floatLiteral(); 673 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral)); 674 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral)); 675 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral)); 676 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral)); 677 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral)); 678 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0)))); 679 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f)))); 680 EXPECT_TRUE( 681 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0))))); 682 683 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral)); 684 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0)))); 685 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f)))); 686 EXPECT_TRUE( 687 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0))))); 688 } 689 690 TEST(Matcher, NullPtrLiteral) { 691 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr())); 692 } 693 694 TEST(Matcher, GNUNullExpr) { 695 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr())); 696 } 697 698 TEST(Matcher, AtomicExpr) { 699 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }", 700 atomicExpr())); 701 } 702 703 TEST(Matcher, Initializers) { 704 const char *ToMatch = "void foo() { struct point { double x; double y; };" 705 " struct point ptarray[10] = " 706 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }"; 707 EXPECT_TRUE(matchesConditionally( 708 ToMatch, 709 initListExpr( 710 has( 711 cxxConstructExpr( 712 requiresZeroInitialization())), 713 has( 714 initListExpr( 715 hasType(asString("struct point")), 716 has(floatLiteral(equals(1.0))), 717 has(implicitValueInitExpr( 718 hasType(asString("double")))))), 719 has( 720 initListExpr( 721 hasType(asString("struct point")), 722 has(floatLiteral(equals(2.0))), 723 has(floatLiteral(equals(1.0))))) 724 ), true, "-std=gnu++98")); 725 726 EXPECT_TRUE(matchesC99(ToMatch, 727 initListExpr( 728 hasSyntacticForm( 729 initListExpr( 730 has( 731 designatedInitExpr( 732 designatorCountIs(2), 733 has(floatLiteral( 734 equals(1.0))), 735 has(integerLiteral( 736 equals(2))))), 737 has( 738 designatedInitExpr( 739 designatorCountIs(2), 740 has(floatLiteral( 741 equals(2.0))), 742 has(integerLiteral( 743 equals(2))))), 744 has( 745 designatedInitExpr( 746 designatorCountIs(2), 747 has(floatLiteral( 748 equals(1.0))), 749 has(integerLiteral( 750 equals(0))))) 751 ))))); 752 } 753 754 TEST(Matcher, ParenListExpr) { 755 EXPECT_TRUE( 756 matches("template<typename T> class foo { void bar() { foo X(*this); } };" 757 "template class foo<int>;", 758 varDecl(hasInitializer(parenListExpr(has(unaryOperator())))))); 759 } 760 761 TEST(Matcher, StmtExpr) { 762 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }", 763 varDecl(hasInitializer(stmtExpr())))); 764 } 765 766 TEST(Matcher, ImportPredefinedExpr) { 767 // __func__ expands as StringLiteral("foo") 768 EXPECT_TRUE(matches("void foo() { __func__; }", 769 predefinedExpr( 770 hasType(asString("const char [4]")), 771 has(stringLiteral())))); 772 } 773 774 TEST(Matcher, AsmStatement) { 775 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt())); 776 } 777 778 TEST(Matcher, Conditions) { 779 StatementMatcher Condition = 780 ifStmt(hasCondition(cxxBoolLiteral(equals(true)))); 781 782 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition)); 783 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition)); 784 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition)); 785 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition)); 786 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition)); 787 } 788 789 TEST(Matcher, ConditionalOperator) { 790 StatementMatcher Conditional = conditionalOperator( 791 hasCondition(cxxBoolLiteral(equals(true))), 792 hasTrueExpression(cxxBoolLiteral(equals(false)))); 793 794 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional)); 795 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional)); 796 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional)); 797 798 StatementMatcher ConditionalFalse = conditionalOperator( 799 hasFalseExpression(cxxBoolLiteral(equals(false)))); 800 801 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse)); 802 EXPECT_TRUE( 803 notMatches("void x() { true ? false : true; }", ConditionalFalse)); 804 805 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse)); 806 EXPECT_TRUE( 807 notMatches("void x() { true ? false : true; }", ConditionalFalse)); 808 } 809 810 TEST(Matcher, BinaryConditionalOperator) { 811 StatementMatcher AlwaysOne = binaryConditionalOperator( 812 hasCondition(implicitCastExpr( 813 has( 814 opaqueValueExpr( 815 hasSourceExpression((integerLiteral(equals(1)))))))), 816 hasFalseExpression(integerLiteral(equals(0)))); 817 818 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne)); 819 820 StatementMatcher FourNotFive = binaryConditionalOperator( 821 hasTrueExpression(opaqueValueExpr( 822 hasSourceExpression((integerLiteral(equals(4)))))), 823 hasFalseExpression(integerLiteral(equals(5)))); 824 825 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive)); 826 } 827 828 TEST(ArraySubscriptMatchers, ArraySubscripts) { 829 EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }", 830 arraySubscriptExpr())); 831 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", 832 arraySubscriptExpr())); 833 } 834 835 TEST(For, FindsForLoops) { 836 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt())); 837 EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt())); 838 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };" 839 "void f() { for (auto &a : as); }", 840 forStmt())); 841 } 842 843 TEST(For, ReportsNoFalsePositives) { 844 EXPECT_TRUE(notMatches("void f() { ; }", forStmt())); 845 EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt())); 846 } 847 848 TEST(CompoundStatement, HandlesSimpleCases) { 849 EXPECT_TRUE(notMatches("void f();", compoundStmt())); 850 EXPECT_TRUE(matches("void f() {}", compoundStmt())); 851 EXPECT_TRUE(matches("void f() {{}}", compoundStmt())); 852 } 853 854 TEST(CompoundStatement, DoesNotMatchEmptyStruct) { 855 // It's not a compound statement just because there's "{}" in the source 856 // text. This is an AST search, not grep. 857 EXPECT_TRUE(notMatches("namespace n { struct S {}; }", 858 compoundStmt())); 859 EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }", 860 compoundStmt())); 861 } 862 863 TEST(CastExpression, MatchesExplicitCasts) { 864 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr())); 865 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr())); 866 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr())); 867 EXPECT_TRUE(matches("char c = char(0);", castExpr())); 868 } 869 TEST(CastExpression, MatchesImplicitCasts) { 870 // This test creates an implicit cast from int to char. 871 EXPECT_TRUE(matches("char c = 0;", castExpr())); 872 // This test creates an implicit cast from lvalue to rvalue. 873 EXPECT_TRUE(matches("char c = 0, d = c;", castExpr())); 874 } 875 876 TEST(CastExpression, DoesNotMatchNonCasts) { 877 EXPECT_TRUE(notMatches("char c = '0';", castExpr())); 878 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr())); 879 EXPECT_TRUE(notMatches("int i = (0);", castExpr())); 880 EXPECT_TRUE(notMatches("int i = 0;", castExpr())); 881 } 882 883 TEST(ReinterpretCast, MatchesSimpleCase) { 884 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);", 885 cxxReinterpretCastExpr())); 886 } 887 888 TEST(ReinterpretCast, DoesNotMatchOtherCasts) { 889 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr())); 890 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);", 891 cxxReinterpretCastExpr())); 892 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);", 893 cxxReinterpretCastExpr())); 894 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};" 895 "B b;" 896 "D* p = dynamic_cast<D*>(&b);", 897 cxxReinterpretCastExpr())); 898 } 899 900 TEST(FunctionalCast, MatchesSimpleCase) { 901 std::string foo_class = "class Foo { public: Foo(const char*); };"; 902 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }", 903 cxxFunctionalCastExpr())); 904 } 905 906 TEST(FunctionalCast, DoesNotMatchOtherCasts) { 907 std::string FooClass = "class Foo { public: Foo(const char*); };"; 908 EXPECT_TRUE( 909 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }", 910 cxxFunctionalCastExpr())); 911 EXPECT_TRUE( 912 notMatches(FooClass + "void r() { Foo f = \"hello world\"; }", 913 cxxFunctionalCastExpr())); 914 } 915 916 TEST(DynamicCast, MatchesSimpleCase) { 917 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};" 918 "B b;" 919 "D* p = dynamic_cast<D*>(&b);", 920 cxxDynamicCastExpr())); 921 } 922 923 TEST(StaticCast, MatchesSimpleCase) { 924 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", 925 cxxStaticCastExpr())); 926 } 927 928 TEST(StaticCast, DoesNotMatchOtherCasts) { 929 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr())); 930 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);", 931 cxxStaticCastExpr())); 932 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);", 933 cxxStaticCastExpr())); 934 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};" 935 "B b;" 936 "D* p = dynamic_cast<D*>(&b);", 937 cxxStaticCastExpr())); 938 } 939 940 TEST(CStyleCast, MatchesSimpleCase) { 941 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr())); 942 } 943 944 TEST(CStyleCast, DoesNotMatchOtherCasts) { 945 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);" 946 "char q, *r = const_cast<char*>(&q);" 947 "void* s = reinterpret_cast<char*>(&s);" 948 "struct B { virtual ~B() {} }; struct D : B {};" 949 "B b;" 950 "D* t = dynamic_cast<D*>(&b);", 951 cStyleCastExpr())); 952 } 953 954 TEST(ImplicitCast, MatchesSimpleCase) { 955 // This test creates an implicit const cast. 956 EXPECT_TRUE(matches("int x = 0; const int y = x;", 957 varDecl(hasInitializer(implicitCastExpr())))); 958 // This test creates an implicit cast from int to char. 959 EXPECT_TRUE(matches("char c = 0;", 960 varDecl(hasInitializer(implicitCastExpr())))); 961 // This test creates an implicit array-to-pointer cast. 962 EXPECT_TRUE(matches("int arr[6]; int *p = arr;", 963 varDecl(hasInitializer(implicitCastExpr())))); 964 } 965 966 TEST(ImplicitCast, DoesNotMatchIncorrectly) { 967 // This test verifies that implicitCastExpr() matches exactly when implicit casts 968 // are present, and that it ignores explicit and paren casts. 969 970 // These two test cases have no casts. 971 EXPECT_TRUE(notMatches("int x = 0;", 972 varDecl(hasInitializer(implicitCastExpr())))); 973 EXPECT_TRUE(notMatches("int x = 0, &y = x;", 974 varDecl(hasInitializer(implicitCastExpr())))); 975 976 EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;", 977 varDecl(hasInitializer(implicitCastExpr())))); 978 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);", 979 varDecl(hasInitializer(implicitCastExpr())))); 980 981 EXPECT_TRUE(notMatches("int x = (0);", 982 varDecl(hasInitializer(implicitCastExpr())))); 983 } 984 985 TEST(Statement, DoesNotMatchDeclarations) { 986 EXPECT_TRUE(notMatches("class X {};", stmt())); 987 } 988 989 TEST(Statement, MatchesCompoundStatments) { 990 EXPECT_TRUE(matches("void x() {}", stmt())); 991 } 992 993 TEST(DeclarationStatement, DoesNotMatchCompoundStatements) { 994 EXPECT_TRUE(notMatches("void x() {}", declStmt())); 995 } 996 997 TEST(DeclarationStatement, MatchesVariableDeclarationStatements) { 998 EXPECT_TRUE(matches("void x() { int a; }", declStmt())); 999 } 1000 1001 TEST(ExprWithCleanups, MatchesExprWithCleanups) { 1002 EXPECT_TRUE(matches("struct Foo { ~Foo(); };" 1003 "const Foo f = Foo();", 1004 varDecl(hasInitializer(exprWithCleanups())))); 1005 EXPECT_FALSE(matches("struct Foo { }; Foo a;" 1006 "const Foo f = a;", 1007 varDecl(hasInitializer(exprWithCleanups())))); 1008 } 1009 1010 TEST(InitListExpression, MatchesInitListExpression) { 1011 EXPECT_TRUE(matches("int a[] = { 1, 2 };", 1012 initListExpr(hasType(asString("int [2]"))))); 1013 EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };", 1014 initListExpr(hasType(recordDecl(hasName("B")))))); 1015 EXPECT_TRUE(matches("struct S { S(void (*a)()); };" 1016 "void f();" 1017 "S s[1] = { &f };", 1018 declRefExpr(to(functionDecl(hasName("f")))))); 1019 EXPECT_TRUE( 1020 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42)))); 1021 } 1022 1023 TEST(CXXStdInitializerListExpression, MatchesCXXStdInitializerListExpression) { 1024 const std::string code = "namespace std {" 1025 "template <typename> class initializer_list {" 1026 " public: initializer_list() noexcept {}" 1027 "};" 1028 "}" 1029 "struct A {" 1030 " A(std::initializer_list<int>) {}" 1031 "};"; 1032 EXPECT_TRUE(matches(code + "A a{0};", 1033 cxxConstructExpr(has(cxxStdInitializerListExpr()), 1034 hasDeclaration(cxxConstructorDecl( 1035 ofClass(hasName("A"))))))); 1036 EXPECT_TRUE(matches(code + "A a = {0};", 1037 cxxConstructExpr(has(cxxStdInitializerListExpr()), 1038 hasDeclaration(cxxConstructorDecl( 1039 ofClass(hasName("A"))))))); 1040 1041 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr())); 1042 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };", 1043 cxxStdInitializerListExpr())); 1044 } 1045 1046 TEST(UsingDeclaration, MatchesUsingDeclarations) { 1047 EXPECT_TRUE(matches("namespace X { int x; } using X::x;", 1048 usingDecl())); 1049 } 1050 1051 TEST(UsingDeclaration, MatchesShadowUsingDelcarations) { 1052 EXPECT_TRUE(matches("namespace f { int a; } using f::a;", 1053 usingDecl(hasAnyUsingShadowDecl(hasName("a"))))); 1054 } 1055 1056 TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) { 1057 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;", 1058 usingDirectiveDecl())); 1059 EXPECT_FALSE( 1060 matches("namespace X { int x; } using X::x;", usingDirectiveDecl())); 1061 } 1062 1063 1064 TEST(While, MatchesWhileLoops) { 1065 EXPECT_TRUE(notMatches("void x() {}", whileStmt())); 1066 EXPECT_TRUE(matches("void x() { while(true); }", whileStmt())); 1067 EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt())); 1068 } 1069 1070 TEST(Do, MatchesDoLoops) { 1071 EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt())); 1072 EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt())); 1073 } 1074 1075 TEST(Do, DoesNotMatchWhileLoops) { 1076 EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt())); 1077 } 1078 1079 TEST(SwitchCase, MatchesCase) { 1080 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase())); 1081 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase())); 1082 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase())); 1083 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase())); 1084 } 1085 1086 TEST(SwitchCase, MatchesSwitch) { 1087 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt())); 1088 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt())); 1089 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt())); 1090 EXPECT_TRUE(notMatches("void x() {}", switchStmt())); 1091 } 1092 1093 TEST(ExceptionHandling, SimpleCases) { 1094 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt())); 1095 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt())); 1096 EXPECT_TRUE( 1097 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr())); 1098 EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }", 1099 cxxThrowExpr())); 1100 EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }", 1101 cxxThrowExpr())); 1102 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }", 1103 cxxCatchStmt(isCatchAll()))); 1104 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }", 1105 cxxCatchStmt(isCatchAll()))); 1106 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }", 1107 varDecl(isExceptionVariable()))); 1108 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }", 1109 varDecl(isExceptionVariable()))); 1110 } 1111 1112 TEST(ParenExpression, SimpleCases) { 1113 EXPECT_TRUE(matches("int i = (3);", parenExpr())); 1114 EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr())); 1115 EXPECT_TRUE(notMatches("int i = 3;", parenExpr())); 1116 EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();", 1117 parenExpr())); 1118 } 1119 1120 TEST(TypeMatching, MatchesTypes) { 1121 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc"))); 1122 } 1123 1124 TEST(TypeMatching, MatchesConstantArrayTypes) { 1125 EXPECT_TRUE(matches("int a[2];", constantArrayType())); 1126 EXPECT_TRUE(notMatches( 1127 "void f() { int a[] = { 2, 3 }; int b[a[0]]; }", 1128 constantArrayType(hasElementType(builtinType())))); 1129 1130 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42)))); 1131 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42)))); 1132 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42)))); 1133 } 1134 1135 TEST(TypeMatching, MatchesDependentSizedArrayTypes) { 1136 EXPECT_TRUE(matches( 1137 "template <typename T, int Size> class array { T data[Size]; };", 1138 dependentSizedArrayType())); 1139 EXPECT_TRUE(notMatches( 1140 "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }", 1141 dependentSizedArrayType())); 1142 } 1143 1144 TEST(TypeMatching, MatchesIncompleteArrayType) { 1145 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType())); 1146 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType())); 1147 1148 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }", 1149 incompleteArrayType())); 1150 } 1151 1152 TEST(TypeMatching, MatchesVariableArrayType) { 1153 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType())); 1154 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType())); 1155 1156 EXPECT_TRUE(matches( 1157 "void f(int b) { int a[b]; }", 1158 variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 1159 varDecl(hasName("b"))))))))); 1160 } 1161 1162 1163 TEST(TypeMatching, MatchesAtomicTypes) { 1164 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() != 1165 llvm::Triple::Win32) { 1166 // FIXME: Make this work for MSVC. 1167 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType())); 1168 1169 EXPECT_TRUE(matches("_Atomic(int) i;", 1170 atomicType(hasValueType(isInteger())))); 1171 EXPECT_TRUE(notMatches("_Atomic(float) f;", 1172 atomicType(hasValueType(isInteger())))); 1173 } 1174 } 1175 1176 TEST(TypeMatching, MatchesAutoTypes) { 1177 EXPECT_TRUE(matches("auto i = 2;", autoType())); 1178 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }", 1179 autoType())); 1180 1181 // FIXME: Matching against the type-as-written can't work here, because the 1182 // type as written was not deduced. 1183 //EXPECT_TRUE(matches("auto a = 1;", 1184 // autoType(hasDeducedType(isInteger())))); 1185 //EXPECT_TRUE(notMatches("auto b = 2.0;", 1186 // autoType(hasDeducedType(isInteger())))); 1187 } 1188 1189 TEST(TypeMatching, MatchesFunctionTypes) { 1190 EXPECT_TRUE(matches("int (*f)(int);", functionType())); 1191 EXPECT_TRUE(matches("void f(int i) {}", functionType())); 1192 } 1193 1194 TEST(TypeMatching, IgnoringParens) { 1195 EXPECT_TRUE( 1196 notMatches("void (*fp)(void);", pointerType(pointee(functionType())))); 1197 EXPECT_TRUE(matches("void (*fp)(void);", 1198 pointerType(pointee(ignoringParens(functionType()))))); 1199 } 1200 1201 TEST(TypeMatching, MatchesFunctionProtoTypes) { 1202 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType())); 1203 EXPECT_TRUE(matches("void f(int i);", functionProtoType())); 1204 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0)))); 1205 EXPECT_TRUE(notMatchesC("void f();", functionProtoType())); 1206 EXPECT_TRUE( 1207 matchesC("void f(void);", functionProtoType(parameterCountIs(0)))); 1208 } 1209 1210 TEST(TypeMatching, MatchesParenType) { 1211 EXPECT_TRUE( 1212 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType()))))); 1213 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType())))); 1214 1215 EXPECT_TRUE(matches( 1216 "int (*ptr_to_func)(int);", 1217 varDecl(hasType(pointsTo(parenType(innerType(functionType()))))))); 1218 EXPECT_TRUE(notMatches( 1219 "int (*ptr_to_array)[4];", 1220 varDecl(hasType(pointsTo(parenType(innerType(functionType()))))))); 1221 } 1222 1223 TEST(TypeMatching, PointerTypes) { 1224 // FIXME: Reactive when these tests can be more specific (not matching 1225 // implicit code on certain platforms), likely when we have hasDescendant for 1226 // Types/TypeLocs. 1227 //EXPECT_TRUE(matchAndVerifyResultTrue( 1228 // "int* a;", 1229 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))), 1230 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1))); 1231 //EXPECT_TRUE(matchAndVerifyResultTrue( 1232 // "int* a;", 1233 // pointerTypeLoc().bind("loc"), 1234 // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1))); 1235 EXPECT_TRUE(matches( 1236 "int** a;", 1237 loc(pointerType(pointee(qualType()))))); 1238 EXPECT_TRUE(matches( 1239 "int** a;", 1240 loc(pointerType(pointee(pointerType()))))); 1241 EXPECT_TRUE(matches( 1242 "int* b; int* * const a = &b;", 1243 loc(qualType(isConstQualified(), pointerType())))); 1244 1245 std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;"; 1246 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1247 hasType(blockPointerType())))); 1248 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"), 1249 hasType(memberPointerType())))); 1250 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1251 hasType(pointerType())))); 1252 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1253 hasType(referenceType())))); 1254 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1255 hasType(lValueReferenceType())))); 1256 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1257 hasType(rValueReferenceType())))); 1258 1259 Fragment = "int *ptr;"; 1260 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1261 hasType(blockPointerType())))); 1262 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1263 hasType(memberPointerType())))); 1264 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"), 1265 hasType(pointerType())))); 1266 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"), 1267 hasType(referenceType())))); 1268 1269 Fragment = "int a; int &ref = a;"; 1270 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1271 hasType(blockPointerType())))); 1272 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1273 hasType(memberPointerType())))); 1274 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1275 hasType(pointerType())))); 1276 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"), 1277 hasType(referenceType())))); 1278 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"), 1279 hasType(lValueReferenceType())))); 1280 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1281 hasType(rValueReferenceType())))); 1282 1283 Fragment = "int &&ref = 2;"; 1284 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1285 hasType(blockPointerType())))); 1286 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1287 hasType(memberPointerType())))); 1288 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1289 hasType(pointerType())))); 1290 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"), 1291 hasType(referenceType())))); 1292 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"), 1293 hasType(lValueReferenceType())))); 1294 EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"), 1295 hasType(rValueReferenceType())))); 1296 } 1297 1298 TEST(TypeMatching, AutoRefTypes) { 1299 std::string Fragment = "auto a = 1;" 1300 "auto b = a;" 1301 "auto &c = a;" 1302 "auto &&d = c;" 1303 "auto &&e = 2;"; 1304 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"), 1305 hasType(referenceType())))); 1306 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"), 1307 hasType(referenceType())))); 1308 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"), 1309 hasType(referenceType())))); 1310 EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"), 1311 hasType(lValueReferenceType())))); 1312 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"), 1313 hasType(rValueReferenceType())))); 1314 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"), 1315 hasType(referenceType())))); 1316 EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"), 1317 hasType(lValueReferenceType())))); 1318 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"), 1319 hasType(rValueReferenceType())))); 1320 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"), 1321 hasType(referenceType())))); 1322 EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"), 1323 hasType(lValueReferenceType())))); 1324 EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"), 1325 hasType(rValueReferenceType())))); 1326 } 1327 1328 TEST(TypeMatching, MatchesEnumTypes) { 1329 EXPECT_TRUE(matches("enum Color { Green }; Color color;", 1330 loc(enumType()))); 1331 EXPECT_TRUE(matches("enum class Color { Green }; Color color;", 1332 loc(enumType()))); 1333 } 1334 1335 TEST(TypeMatching, MatchesPointersToConstTypes) { 1336 EXPECT_TRUE(matches("int b; int * const a = &b;", 1337 loc(pointerType()))); 1338 EXPECT_TRUE(matches("int b; int * const a = &b;", 1339 loc(pointerType()))); 1340 EXPECT_TRUE(matches( 1341 "int b; const int * a = &b;", 1342 loc(pointerType(pointee(builtinType()))))); 1343 EXPECT_TRUE(matches( 1344 "int b; const int * a = &b;", 1345 pointerType(pointee(builtinType())))); 1346 } 1347 1348 TEST(TypeMatching, MatchesTypedefTypes) { 1349 EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"), 1350 hasType(typedefType())))); 1351 } 1352 1353 TEST(TypeMatching, MatchesTemplateSpecializationType) { 1354 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;", 1355 templateSpecializationType())); 1356 } 1357 1358 TEST(TypeMatching, MatchesRecordType) { 1359 EXPECT_TRUE(matches("class C{}; C c;", recordType())); 1360 EXPECT_TRUE(matches("struct S{}; S s;", 1361 recordType(hasDeclaration(recordDecl(hasName("S")))))); 1362 EXPECT_TRUE(notMatches("int i;", 1363 recordType(hasDeclaration(recordDecl(hasName("S")))))); 1364 } 1365 1366 TEST(TypeMatching, MatchesElaboratedType) { 1367 EXPECT_TRUE(matches( 1368 "namespace N {" 1369 " namespace M {" 1370 " class D {};" 1371 " }" 1372 "}" 1373 "N::M::D d;", elaboratedType())); 1374 EXPECT_TRUE(matches("class C {} c;", elaboratedType())); 1375 EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType())); 1376 } 1377 1378 TEST(TypeMatching, MatchesSubstTemplateTypeParmType) { 1379 const std::string code = "template <typename T>" 1380 "int F() {" 1381 " return 1 + T();" 1382 "}" 1383 "int i = F<int>();"; 1384 EXPECT_FALSE(matches(code, binaryOperator(hasLHS( 1385 expr(hasType(substTemplateTypeParmType())))))); 1386 EXPECT_TRUE(matches(code, binaryOperator(hasRHS( 1387 expr(hasType(substTemplateTypeParmType())))))); 1388 } 1389 1390 TEST(NNS, MatchesNestedNameSpecifiers) { 1391 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", 1392 nestedNameSpecifier())); 1393 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };", 1394 nestedNameSpecifier())); 1395 EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}", 1396 nestedNameSpecifier())); 1397 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;", 1398 nestedNameSpecifier())); 1399 1400 EXPECT_TRUE(matches( 1401 "struct A { static void f() {} }; void g() { A::f(); }", 1402 nestedNameSpecifier())); 1403 EXPECT_TRUE(notMatches( 1404 "struct A { static void f() {} }; void g(A* a) { a->f(); }", 1405 nestedNameSpecifier())); 1406 } 1407 1408 TEST(NullStatement, SimpleCases) { 1409 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt())); 1410 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt())); 1411 } 1412 1413 TEST(NS, Alias) { 1414 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;", 1415 namespaceAliasDecl(hasName("alias")))); 1416 } 1417 1418 TEST(NNS, MatchesTypes) { 1419 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier( 1420 specifiesType(hasDeclaration(recordDecl(hasName("A"))))); 1421 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher)); 1422 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;", 1423 Matcher)); 1424 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher)); 1425 } 1426 1427 TEST(NNS, MatchesNamespaceDecls) { 1428 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier( 1429 specifiesNamespace(hasName("ns"))); 1430 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher)); 1431 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher)); 1432 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher)); 1433 } 1434 1435 TEST(NNS, MatchesNestedNameSpecifierPrefixes) { 1436 EXPECT_TRUE(matches( 1437 "struct A { struct B { struct C {}; }; }; A::B::C c;", 1438 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))))); 1439 EXPECT_TRUE(matches( 1440 "struct A { struct B { struct C {}; }; }; A::B::C c;", 1441 nestedNameSpecifierLoc(hasPrefix( 1442 specifiesTypeLoc(loc(qualType(asString("struct A")))))))); 1443 } 1444 1445 1446 template <typename T> 1447 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback { 1448 public: 1449 bool run(const BoundNodes *Nodes) override { return false; } 1450 1451 bool run(const BoundNodes *Nodes, ASTContext *Context) override { 1452 const T *Node = Nodes->getNodeAs<T>(""); 1453 return verify(*Nodes, *Context, Node); 1454 } 1455 1456 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) { 1457 // Use the original typed pointer to verify we can pass pointers to subtypes 1458 // to equalsNode. 1459 const T *TypedNode = cast<T>(Node); 1460 return selectFirst<T>( 1461 "", match(stmt(hasParent( 1462 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))), 1463 *Node, Context)) != nullptr; 1464 } 1465 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) { 1466 // Use the original typed pointer to verify we can pass pointers to subtypes 1467 // to equalsNode. 1468 const T *TypedNode = cast<T>(Node); 1469 return selectFirst<T>( 1470 "", match(decl(hasParent( 1471 decl(has(decl(equalsNode(TypedNode)))).bind(""))), 1472 *Node, Context)) != nullptr; 1473 } 1474 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) { 1475 // Use the original typed pointer to verify we can pass pointers to subtypes 1476 // to equalsNode. 1477 const T *TypedNode = cast<T>(Node); 1478 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl"); 1479 return selectFirst<T>( 1480 "", match(fieldDecl(hasParent(decl(has(fieldDecl( 1481 hasType(type(equalsNode(TypedNode)).bind(""))))))), 1482 *Dec, Context)) != nullptr; 1483 } 1484 }; 1485 1486 TEST(IsEqualTo, MatchesNodesByIdentity) { 1487 EXPECT_TRUE(matchAndVerifyResultTrue( 1488 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""), 1489 llvm::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>())); 1490 EXPECT_TRUE(matchAndVerifyResultTrue( 1491 "void f() { if (true) if(true) {} }", ifStmt().bind(""), 1492 llvm::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>())); 1493 EXPECT_TRUE(matchAndVerifyResultTrue( 1494 "class X { class Y {} y; };", 1495 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"), 1496 llvm::make_unique<VerifyAncestorHasChildIsEqual<Type>>())); 1497 } 1498 1499 TEST(TypedefDeclMatcher, Match) { 1500 EXPECT_TRUE(matches("typedef int typedefDeclTest;", 1501 typedefDecl(hasName("typedefDeclTest")))); 1502 EXPECT_TRUE(notMatches("using typedefDeclTest2 = int;", 1503 typedefDecl(hasName("typedefDeclTest2")))); 1504 } 1505 1506 TEST(TypeAliasDeclMatcher, Match) { 1507 EXPECT_TRUE(matches("using typeAliasTest2 = int;", 1508 typeAliasDecl(hasName("typeAliasTest2")))); 1509 EXPECT_TRUE(notMatches("typedef int typeAliasTest;", 1510 typeAliasDecl(hasName("typeAliasTest")))); 1511 } 1512 1513 TEST(TypedefNameDeclMatcher, Match) { 1514 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;", 1515 typedefNameDecl(hasName("typedefNameDeclTest1")))); 1516 EXPECT_TRUE(matches("using typedefNameDeclTest2 = int;", 1517 typedefNameDecl(hasName("typedefNameDeclTest2")))); 1518 } 1519 1520 TEST(TypeAliasTemplateDeclMatcher, Match) { 1521 std::string Code = R"( 1522 template <typename T> 1523 class X { T t; }; 1524 1525 template <typename T> 1526 using typeAliasTemplateDecl = X<T>; 1527 1528 using typeAliasDecl = X<int>; 1529 )"; 1530 EXPECT_TRUE( 1531 matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl")))); 1532 EXPECT_TRUE( 1533 notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl")))); 1534 } 1535 1536 TEST(ObjCMessageExprMatcher, SimpleExprs) { 1537 // don't find ObjCMessageExpr where none are present 1538 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything()))); 1539 1540 std::string Objc1String = 1541 "@interface Str " 1542 " - (Str *)uppercaseString;" 1543 "@end " 1544 "@interface foo " 1545 "- (void)contents;" 1546 "- (void)meth:(Str *)text;" 1547 "@end " 1548 " " 1549 "@implementation foo " 1550 "- (void) meth:(Str *)text { " 1551 " [self contents];" 1552 " Str *up = [text uppercaseString];" 1553 "} " 1554 "@end "; 1555 EXPECT_TRUE(matchesObjC( 1556 Objc1String, 1557 objcMessageExpr(anything()))); 1558 EXPECT_TRUE(matchesObjC( 1559 Objc1String, 1560 objcMessageExpr(hasSelector("contents")))); 1561 EXPECT_TRUE(matchesObjC( 1562 Objc1String, 1563 objcMessageExpr(matchesSelector("cont*")))); 1564 EXPECT_FALSE(matchesObjC( 1565 Objc1String, 1566 objcMessageExpr(matchesSelector("?cont*")))); 1567 EXPECT_TRUE(notMatchesObjC( 1568 Objc1String, 1569 objcMessageExpr(hasSelector("contents"), hasNullSelector()))); 1570 EXPECT_TRUE(matchesObjC( 1571 Objc1String, 1572 objcMessageExpr(hasSelector("contents"), hasUnarySelector()))); 1573 EXPECT_TRUE(matchesObjC( 1574 Objc1String, 1575 objcMessageExpr(hasSelector("contents"), numSelectorArgs(0)))); 1576 EXPECT_TRUE(matchesObjC( 1577 Objc1String, 1578 objcMessageExpr(matchesSelector("uppercase*"), 1579 argumentCountIs(0) 1580 ))); 1581 } 1582 1583 TEST(ObjCDeclMacher, CoreDecls) { 1584 std::string ObjCString = 1585 "@protocol Proto " 1586 "- (void)protoDidThing; " 1587 "@end " 1588 "@interface Thing " 1589 "@property int enabled; " 1590 "@end " 1591 "@interface Thing (ABC) " 1592 "- (void)abc_doThing; " 1593 "@end " 1594 "@implementation Thing " 1595 "{ id _ivar; } " 1596 "- (void)anything {} " 1597 "@end " 1598 ; 1599 1600 EXPECT_TRUE(matchesObjC( 1601 ObjCString, 1602 objcProtocolDecl(hasName("Proto")))); 1603 EXPECT_TRUE(matchesObjC( 1604 ObjCString, 1605 objcCategoryDecl(hasName("ABC")))); 1606 EXPECT_TRUE(matchesObjC( 1607 ObjCString, 1608 objcMethodDecl(hasName("protoDidThing")))); 1609 EXPECT_TRUE(matchesObjC( 1610 ObjCString, 1611 objcMethodDecl(hasName("abc_doThing")))); 1612 EXPECT_TRUE(matchesObjC( 1613 ObjCString, 1614 objcMethodDecl(hasName("anything")))); 1615 EXPECT_TRUE(matchesObjC( 1616 ObjCString, 1617 objcIvarDecl(hasName("_ivar")))); 1618 EXPECT_TRUE(matchesObjC( 1619 ObjCString, 1620 objcPropertyDecl(hasName("enabled")))); 1621 } 1622 1623 } // namespace ast_matchers 1624 } // namespace clang 1625