1 //===- unittests/AST/ASTTraverserTest.h------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/AST/ASTContext.h" 10 #include "clang/AST/ASTNodeTraverser.h" 11 #include "clang/AST/TextNodeDumper.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/ASTMatchers/ASTMatchers.h" 14 #include "clang/Tooling/Tooling.h" 15 #include "gmock/gmock.h" 16 #include "gtest/gtest.h" 17 18 using namespace clang::tooling; 19 using namespace clang::ast_matchers; 20 21 namespace clang { 22 23 class NodeTreePrinter : public TextTreeStructure { 24 llvm::raw_ostream &OS; 25 26 public: 27 NodeTreePrinter(llvm::raw_ostream &OS) 28 : TextTreeStructure(OS, /* showColors */ false), OS(OS) {} 29 30 void Visit(const Decl *D) { 31 OS << D->getDeclKindName() << "Decl"; 32 if (auto *ND = dyn_cast<NamedDecl>(D)) { 33 OS << " '" << ND->getDeclName() << "'"; 34 } 35 } 36 37 void Visit(const Stmt *S) { 38 OS << S->getStmtClassName(); 39 if (auto *E = dyn_cast<DeclRefExpr>(S)) { 40 OS << " '" << E->getDecl()->getDeclName() << "'"; 41 } 42 } 43 44 void Visit(QualType QT) { 45 OS << "QualType " << QT.split().Quals.getAsString(); 46 } 47 48 void Visit(const Type *T) { OS << T->getTypeClassName() << "Type"; } 49 50 void Visit(const comments::Comment *C, const comments::FullComment *FC) { 51 OS << C->getCommentKindName(); 52 } 53 54 void Visit(const CXXCtorInitializer *Init) { OS << "CXXCtorInitializer"; } 55 56 void Visit(const Attr *A) { 57 switch (A->getKind()) { 58 #define ATTR(X) \ 59 case attr::X: \ 60 OS << #X; \ 61 break; 62 #include "clang/Basic/AttrList.inc" 63 } 64 OS << "Attr"; 65 } 66 67 void Visit(const OMPClause *C) { OS << "OMPClause"; } 68 void Visit(const TemplateArgument &A, SourceRange R = {}, 69 const Decl *From = nullptr, const char *Label = nullptr) { 70 OS << "TemplateArgument"; 71 } 72 73 template <typename... T> void Visit(T...) {} 74 }; 75 76 class TestASTDumper : public ASTNodeTraverser<TestASTDumper, NodeTreePrinter> { 77 78 NodeTreePrinter MyNodeRecorder; 79 80 public: 81 TestASTDumper(llvm::raw_ostream &OS) : MyNodeRecorder(OS) {} 82 NodeTreePrinter &doGetNodeDelegate() { return MyNodeRecorder; } 83 }; 84 85 template <typename... NodeType> std::string dumpASTString(NodeType &&... N) { 86 std::string Buffer; 87 llvm::raw_string_ostream OS(Buffer); 88 89 TestASTDumper Dumper(OS); 90 91 OS << "\n"; 92 93 Dumper.Visit(std::forward<NodeType &&>(N)...); 94 95 return OS.str(); 96 } 97 98 template <typename... NodeType> 99 std::string dumpASTString(TraversalKind TK, NodeType &&... N) { 100 std::string Buffer; 101 llvm::raw_string_ostream OS(Buffer); 102 103 TestASTDumper Dumper(OS); 104 Dumper.SetTraversalKind(TK); 105 106 OS << "\n"; 107 108 Dumper.Visit(std::forward<NodeType &&>(N)...); 109 110 return OS.str(); 111 } 112 113 const FunctionDecl *getFunctionNode(clang::ASTUnit *AST, 114 const std::string &Name) { 115 auto Result = ast_matchers::match(functionDecl(hasName(Name)).bind("fn"), 116 AST->getASTContext()); 117 EXPECT_EQ(Result.size(), 1u); 118 return Result[0].getNodeAs<FunctionDecl>("fn"); 119 } 120 121 template <typename T> struct Verifier { 122 static void withDynNode(T Node, const std::string &DumpString) { 123 EXPECT_EQ(dumpASTString(DynTypedNode::create(Node)), DumpString); 124 } 125 }; 126 127 template <typename T> struct Verifier<T *> { 128 static void withDynNode(T *Node, const std::string &DumpString) { 129 EXPECT_EQ(dumpASTString(DynTypedNode::create(*Node)), DumpString); 130 } 131 }; 132 133 template <typename T> 134 void verifyWithDynNode(T Node, const std::string &DumpString) { 135 EXPECT_EQ(dumpASTString(Node), DumpString); 136 137 Verifier<T>::withDynNode(Node, DumpString); 138 } 139 140 TEST(Traverse, Dump) { 141 142 auto AST = buildASTFromCode(R"cpp( 143 struct A { 144 int m_number; 145 146 /// CTor 147 A() : m_number(42) {} 148 149 [[nodiscard]] const int func() { 150 return 42; 151 } 152 153 }; 154 155 template<typename T> 156 struct templ 157 { 158 }; 159 160 template<> 161 struct templ<int> 162 { 163 }; 164 165 void parmvardecl_attr(struct A __attribute__((address_space(19)))*); 166 167 )cpp"); 168 169 const FunctionDecl *Func = getFunctionNode(AST.get(), "func"); 170 171 verifyWithDynNode(Func, 172 R"cpp( 173 CXXMethodDecl 'func' 174 |-CompoundStmt 175 | `-ReturnStmt 176 | `-IntegerLiteral 177 `-WarnUnusedResultAttr 178 )cpp"); 179 180 Stmt *Body = Func->getBody(); 181 182 verifyWithDynNode(Body, 183 R"cpp( 184 CompoundStmt 185 `-ReturnStmt 186 `-IntegerLiteral 187 )cpp"); 188 189 QualType QT = Func->getType(); 190 191 verifyWithDynNode(QT, 192 R"cpp( 193 FunctionProtoType 194 `-QualType const 195 `-BuiltinType 196 )cpp"); 197 198 const FunctionDecl *CTorFunc = getFunctionNode(AST.get(), "A"); 199 200 verifyWithDynNode(CTorFunc->getType(), 201 R"cpp( 202 FunctionProtoType 203 `-BuiltinType 204 )cpp"); 205 206 Attr *A = *Func->attr_begin(); 207 208 { 209 std::string expectedString = R"cpp( 210 WarnUnusedResultAttr 211 )cpp"; 212 213 EXPECT_EQ(dumpASTString(A), expectedString); 214 } 215 216 auto *CTor = dyn_cast<CXXConstructorDecl>(CTorFunc); 217 const CXXCtorInitializer *Init = *CTor->init_begin(); 218 219 verifyWithDynNode(Init, 220 R"cpp( 221 CXXCtorInitializer 222 `-IntegerLiteral 223 )cpp"); 224 225 const comments::FullComment *Comment = 226 AST->getASTContext().getLocalCommentForDeclUncached(CTorFunc); 227 { 228 std::string expectedString = R"cpp( 229 FullComment 230 `-ParagraphComment 231 `-TextComment 232 )cpp"; 233 EXPECT_EQ(dumpASTString(Comment, Comment), expectedString); 234 } 235 236 auto Result = ast_matchers::match( 237 classTemplateSpecializationDecl(hasName("templ")).bind("fn"), 238 AST->getASTContext()); 239 EXPECT_EQ(Result.size(), 1u); 240 auto Templ = Result[0].getNodeAs<ClassTemplateSpecializationDecl>("fn"); 241 242 TemplateArgument TA = Templ->getTemplateArgs()[0]; 243 244 verifyWithDynNode(TA, 245 R"cpp( 246 TemplateArgument 247 )cpp"); 248 249 Func = getFunctionNode(AST.get(), "parmvardecl_attr"); 250 251 const auto *Parm = Func->getParamDecl(0); 252 const auto TL = Parm->getTypeSourceInfo()->getTypeLoc(); 253 ASSERT_TRUE(TL.getType()->isPointerType()); 254 255 const auto ATL = TL.getNextTypeLoc().getAs<AttributedTypeLoc>(); 256 const auto *AS = cast<AddressSpaceAttr>(ATL.getAttr()); 257 EXPECT_EQ(toTargetAddressSpace(static_cast<LangAS>(AS->getAddressSpace())), 258 19u); 259 } 260 261 TEST(Traverse, IgnoreUnlessSpelledInSourceStructs) { 262 auto AST = buildASTFromCode(R"cpp( 263 264 struct MyStruct { 265 MyStruct(); 266 MyStruct(int i) { 267 MyStruct(); 268 } 269 ~MyStruct(); 270 }; 271 272 )cpp"); 273 274 auto BN = ast_matchers::match( 275 cxxConstructorDecl(hasName("MyStruct"), 276 hasParameter(0, parmVarDecl(hasType(isInteger())))) 277 .bind("ctor"), 278 AST->getASTContext()); 279 EXPECT_EQ(BN.size(), 1u); 280 281 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, 282 BN[0].getNodeAs<Decl>("ctor")), 283 R"cpp( 284 CXXConstructorDecl 'MyStruct' 285 |-ParmVarDecl 'i' 286 `-CompoundStmt 287 `-CXXTemporaryObjectExpr 288 )cpp"); 289 290 EXPECT_EQ(dumpASTString(TK_AsIs, BN[0].getNodeAs<Decl>("ctor")), 291 R"cpp( 292 CXXConstructorDecl 'MyStruct' 293 |-ParmVarDecl 'i' 294 `-CompoundStmt 295 `-ExprWithCleanups 296 `-CXXBindTemporaryExpr 297 `-CXXTemporaryObjectExpr 298 )cpp"); 299 } 300 301 TEST(Traverse, IgnoreUnlessSpelledInSourceReturnStruct) { 302 303 auto AST = buildASTFromCode(R"cpp( 304 struct Retval { 305 Retval() {} 306 ~Retval() {} 307 }; 308 309 Retval someFun(); 310 311 void foo() 312 { 313 someFun(); 314 } 315 )cpp"); 316 317 auto BN = ast_matchers::match(functionDecl(hasName("foo")).bind("fn"), 318 AST->getASTContext()); 319 EXPECT_EQ(BN.size(), 1u); 320 321 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, 322 BN[0].getNodeAs<Decl>("fn")), 323 R"cpp( 324 FunctionDecl 'foo' 325 `-CompoundStmt 326 `-CallExpr 327 `-DeclRefExpr 'someFun' 328 )cpp"); 329 330 EXPECT_EQ(dumpASTString(TK_AsIs, BN[0].getNodeAs<Decl>("fn")), 331 R"cpp( 332 FunctionDecl 'foo' 333 `-CompoundStmt 334 `-ExprWithCleanups 335 `-CXXBindTemporaryExpr 336 `-CallExpr 337 `-ImplicitCastExpr 338 `-DeclRefExpr 'someFun' 339 )cpp"); 340 } 341 342 TEST(Traverse, IgnoreUnlessSpelledInSourceReturns) { 343 344 auto AST = buildASTFromCode(R"cpp( 345 346 struct A 347 { 348 }; 349 350 struct B 351 { 352 B(int); 353 B(A const& a); 354 B(); 355 }; 356 357 struct C 358 { 359 operator B(); 360 }; 361 362 B func1() { 363 return 42; 364 } 365 366 B func2() { 367 return B{42}; 368 } 369 370 B func3() { 371 return B(42); 372 } 373 374 B func4() { 375 return B(); 376 } 377 378 B func5() { 379 return B{}; 380 } 381 382 B func6() { 383 return C(); 384 } 385 386 B func7() { 387 return A(); 388 } 389 390 B func8() { 391 return C{}; 392 } 393 394 B func9() { 395 return A{}; 396 } 397 398 B func10() { 399 A a; 400 return a; 401 } 402 403 B func11() { 404 B b; 405 return b; 406 } 407 408 B func12() { 409 C c; 410 return c; 411 } 412 413 )cpp"); 414 415 auto getFunctionNode = [&AST](const std::string &name) { 416 auto BN = ast_matchers::match(functionDecl(hasName(name)).bind("fn"), 417 AST->getASTContext()); 418 EXPECT_EQ(BN.size(), 1u); 419 return BN[0].getNodeAs<Decl>("fn"); 420 }; 421 422 { 423 auto FN = getFunctionNode("func1"); 424 llvm::StringRef Expected = R"cpp( 425 FunctionDecl 'func1' 426 `-CompoundStmt 427 `-ReturnStmt 428 `-ExprWithCleanups 429 `-CXXConstructExpr 430 `-MaterializeTemporaryExpr 431 `-ImplicitCastExpr 432 `-CXXConstructExpr 433 `-IntegerLiteral 434 )cpp"; 435 436 EXPECT_EQ(dumpASTString(TK_AsIs, FN), Expected); 437 438 Expected = R"cpp( 439 FunctionDecl 'func1' 440 `-CompoundStmt 441 `-ReturnStmt 442 `-IntegerLiteral 443 )cpp"; 444 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, FN), Expected); 445 } 446 447 llvm::StringRef Expected = R"cpp( 448 FunctionDecl 'func2' 449 `-CompoundStmt 450 `-ReturnStmt 451 `-CXXTemporaryObjectExpr 452 `-IntegerLiteral 453 )cpp"; 454 EXPECT_EQ( 455 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func2")), 456 Expected); 457 458 Expected = R"cpp( 459 FunctionDecl 'func3' 460 `-CompoundStmt 461 `-ReturnStmt 462 `-CXXFunctionalCastExpr 463 `-IntegerLiteral 464 )cpp"; 465 EXPECT_EQ( 466 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func3")), 467 Expected); 468 469 Expected = R"cpp( 470 FunctionDecl 'func4' 471 `-CompoundStmt 472 `-ReturnStmt 473 `-CXXTemporaryObjectExpr 474 )cpp"; 475 EXPECT_EQ( 476 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func4")), 477 Expected); 478 479 Expected = R"cpp( 480 FunctionDecl 'func5' 481 `-CompoundStmt 482 `-ReturnStmt 483 `-CXXTemporaryObjectExpr 484 )cpp"; 485 EXPECT_EQ( 486 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func5")), 487 Expected); 488 489 Expected = R"cpp( 490 FunctionDecl 'func6' 491 `-CompoundStmt 492 `-ReturnStmt 493 `-CXXTemporaryObjectExpr 494 )cpp"; 495 EXPECT_EQ( 496 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func6")), 497 Expected); 498 499 Expected = R"cpp( 500 FunctionDecl 'func7' 501 `-CompoundStmt 502 `-ReturnStmt 503 `-CXXTemporaryObjectExpr 504 )cpp"; 505 EXPECT_EQ( 506 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func7")), 507 Expected); 508 509 Expected = R"cpp( 510 FunctionDecl 'func8' 511 `-CompoundStmt 512 `-ReturnStmt 513 `-CXXFunctionalCastExpr 514 `-InitListExpr 515 )cpp"; 516 EXPECT_EQ( 517 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func8")), 518 Expected); 519 520 Expected = R"cpp( 521 FunctionDecl 'func9' 522 `-CompoundStmt 523 `-ReturnStmt 524 `-CXXFunctionalCastExpr 525 `-InitListExpr 526 )cpp"; 527 EXPECT_EQ( 528 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func9")), 529 Expected); 530 531 Expected = R"cpp( 532 FunctionDecl 'func10' 533 `-CompoundStmt 534 |-DeclStmt 535 | `-VarDecl 'a' 536 | `-CXXConstructExpr 537 `-ReturnStmt 538 `-DeclRefExpr 'a' 539 )cpp"; 540 EXPECT_EQ( 541 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func10")), 542 Expected); 543 544 Expected = R"cpp( 545 FunctionDecl 'func11' 546 `-CompoundStmt 547 |-DeclStmt 548 | `-VarDecl 'b' 549 | `-CXXConstructExpr 550 `-ReturnStmt 551 `-DeclRefExpr 'b' 552 )cpp"; 553 EXPECT_EQ( 554 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func11")), 555 Expected); 556 557 Expected = R"cpp( 558 FunctionDecl 'func12' 559 `-CompoundStmt 560 |-DeclStmt 561 | `-VarDecl 'c' 562 | `-CXXConstructExpr 563 `-ReturnStmt 564 `-DeclRefExpr 'c' 565 )cpp"; 566 EXPECT_EQ( 567 dumpASTString(TK_IgnoreUnlessSpelledInSource, getFunctionNode("func12")), 568 Expected); 569 } 570 571 TEST(Traverse, LambdaUnlessSpelledInSource) { 572 573 auto AST = 574 buildASTFromCodeWithArgs(R"cpp( 575 576 void captures() { 577 int a = 0; 578 int b = 0; 579 int d = 0; 580 int f = 0; 581 582 [a, &b, c = d, &e = f](int g, int h = 42) {}; 583 } 584 585 void templated() { 586 int a = 0; 587 [a]<typename T>(T t) {}; 588 } 589 590 struct SomeStruct { 591 int a = 0; 592 void capture_this() { 593 [this]() {}; 594 } 595 void capture_this_copy() { 596 [self = *this]() {}; 597 } 598 }; 599 )cpp", 600 {"-Wno-unused-value", "-Wno-c++2a-extensions"}); 601 602 auto getLambdaNode = [&AST](const std::string &name) { 603 auto BN = ast_matchers::match( 604 lambdaExpr(hasAncestor(functionDecl(hasName(name)))).bind("lambda"), 605 AST->getASTContext()); 606 EXPECT_EQ(BN.size(), 1u); 607 return BN[0].getNodeAs<LambdaExpr>("lambda"); 608 }; 609 610 { 611 auto L = getLambdaNode("captures"); 612 613 llvm::StringRef Expected = R"cpp( 614 LambdaExpr 615 |-DeclRefExpr 'a' 616 |-DeclRefExpr 'b' 617 |-VarDecl 'c' 618 | `-DeclRefExpr 'd' 619 |-VarDecl 'e' 620 | `-DeclRefExpr 'f' 621 |-ParmVarDecl 'g' 622 |-ParmVarDecl 'h' 623 | `-IntegerLiteral 624 `-CompoundStmt 625 )cpp"; 626 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, L), Expected); 627 628 Expected = R"cpp( 629 LambdaExpr 630 |-CXXRecordDecl '' 631 | |-CXXMethodDecl 'operator()' 632 | | |-ParmVarDecl 'g' 633 | | |-ParmVarDecl 'h' 634 | | | `-IntegerLiteral 635 | | `-CompoundStmt 636 | |-FieldDecl '' 637 | |-FieldDecl '' 638 | |-FieldDecl '' 639 | |-FieldDecl '' 640 | `-CXXDestructorDecl '~' 641 |-ImplicitCastExpr 642 | `-DeclRefExpr 'a' 643 |-DeclRefExpr 'b' 644 |-ImplicitCastExpr 645 | `-DeclRefExpr 'd' 646 |-DeclRefExpr 'f' 647 `-CompoundStmt 648 )cpp"; 649 EXPECT_EQ(dumpASTString(TK_AsIs, L), Expected); 650 } 651 652 { 653 auto L = getLambdaNode("templated"); 654 655 llvm::StringRef Expected = R"cpp( 656 LambdaExpr 657 |-DeclRefExpr 'a' 658 |-TemplateTypeParmDecl 'T' 659 |-ParmVarDecl 't' 660 `-CompoundStmt 661 )cpp"; 662 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, L), Expected); 663 } 664 665 { 666 auto L = getLambdaNode("capture_this"); 667 668 llvm::StringRef Expected = R"cpp( 669 LambdaExpr 670 |-CXXThisExpr 671 `-CompoundStmt 672 )cpp"; 673 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, L), Expected); 674 } 675 676 { 677 auto L = getLambdaNode("capture_this_copy"); 678 679 llvm::StringRef Expected = R"cpp( 680 LambdaExpr 681 |-VarDecl 'self' 682 | `-UnaryOperator 683 | `-CXXThisExpr 684 `-CompoundStmt 685 )cpp"; 686 EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource, L), Expected); 687 } 688 } 689 690 } // namespace clang 691