1 //===- unittest/AST/ASTImporterTest.cpp - AST node import test ------------===// 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 // Tests for the correct import of AST nodes from one AST context to another. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/ASTMatchers/ASTMatchers.h" 14 #include "llvm/ADT/StringMap.h" 15 #include "llvm/Support/SmallVectorMemoryBuffer.h" 16 17 #include "clang/AST/DeclContextInternals.h" 18 #include "gtest/gtest.h" 19 20 #include "ASTImporterFixtures.h" 21 22 namespace clang { 23 namespace ast_matchers { 24 25 using internal::Matcher; 26 using internal::BindableMatcher; 27 using llvm::StringMap; 28 29 static const RecordDecl *getRecordDeclOfFriend(FriendDecl *FD) { 30 QualType Ty = FD->getFriendType()->getType().getCanonicalType(); 31 return cast<RecordType>(Ty)->getDecl(); 32 } 33 34 struct ImportExpr : TestImportBase {}; 35 struct ImportType : TestImportBase {}; 36 struct ImportDecl : TestImportBase {}; 37 struct ImportFixedPointExpr : ImportExpr {}; 38 39 struct CanonicalRedeclChain : ASTImporterOptionSpecificTestBase {}; 40 41 TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers) { 42 Decl *FromTU = getTuDecl("void f();", Lang_CXX03); 43 auto Pattern = functionDecl(hasName("f")); 44 auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 45 46 auto Redecls = getCanonicalForwardRedeclChain(D0); 47 ASSERT_EQ(Redecls.size(), 1u); 48 EXPECT_EQ(D0, Redecls[0]); 49 } 50 51 TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers2) { 52 Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX03); 53 auto Pattern = functionDecl(hasName("f")); 54 auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 55 auto *D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 56 FunctionDecl *D1 = D2->getPreviousDecl(); 57 58 auto Redecls = getCanonicalForwardRedeclChain(D0); 59 ASSERT_EQ(Redecls.size(), 3u); 60 EXPECT_EQ(D0, Redecls[0]); 61 EXPECT_EQ(D1, Redecls[1]); 62 EXPECT_EQ(D2, Redecls[2]); 63 } 64 65 TEST_P(CanonicalRedeclChain, ShouldBeSameForAllDeclInTheChain) { 66 Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX03); 67 auto Pattern = functionDecl(hasName("f")); 68 auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 69 auto *D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 70 FunctionDecl *D1 = D2->getPreviousDecl(); 71 72 auto RedeclsD0 = getCanonicalForwardRedeclChain(D0); 73 auto RedeclsD1 = getCanonicalForwardRedeclChain(D1); 74 auto RedeclsD2 = getCanonicalForwardRedeclChain(D2); 75 76 EXPECT_THAT(RedeclsD0, ::testing::ContainerEq(RedeclsD1)); 77 EXPECT_THAT(RedeclsD1, ::testing::ContainerEq(RedeclsD2)); 78 } 79 80 namespace { 81 struct RedirectingImporter : public ASTImporter { 82 using ASTImporter::ASTImporter; 83 84 protected: 85 llvm::Expected<Decl *> ImportImpl(Decl *FromD) override { 86 auto *ND = dyn_cast<NamedDecl>(FromD); 87 if (!ND || ND->getName() != "shouldNotBeImported") 88 return ASTImporter::ImportImpl(FromD); 89 for (Decl *D : getToContext().getTranslationUnitDecl()->decls()) { 90 if (auto *ND = dyn_cast<NamedDecl>(D)) 91 if (ND->getName() == "realDecl") { 92 RegisterImportedDecl(FromD, ND); 93 return ND; 94 } 95 } 96 return ASTImporter::ImportImpl(FromD); 97 } 98 }; 99 100 } // namespace 101 102 struct RedirectingImporterTest : ASTImporterOptionSpecificTestBase { 103 RedirectingImporterTest() { 104 Creator = [](ASTContext &ToContext, FileManager &ToFileManager, 105 ASTContext &FromContext, FileManager &FromFileManager, 106 bool MinimalImport, 107 const std::shared_ptr<ASTImporterSharedState> &SharedState) { 108 return new RedirectingImporter(ToContext, ToFileManager, FromContext, 109 FromFileManager, MinimalImport, 110 SharedState); 111 }; 112 } 113 }; 114 115 // Test that an ASTImporter subclass can intercept an import call. 116 TEST_P(RedirectingImporterTest, InterceptImport) { 117 Decl *From, *To; 118 std::tie(From, To) = 119 getImportedDecl("class shouldNotBeImported {};", Lang_CXX03, 120 "class realDecl {};", Lang_CXX03, "shouldNotBeImported"); 121 auto *Imported = cast<CXXRecordDecl>(To); 122 EXPECT_EQ(Imported->getQualifiedNameAsString(), "realDecl"); 123 124 // Make sure our importer prevented the importing of the decl. 125 auto *ToTU = Imported->getTranslationUnitDecl(); 126 auto Pattern = functionDecl(hasName("shouldNotBeImported")); 127 unsigned count = 128 DeclCounterWithPredicate<CXXRecordDecl>().match(ToTU, Pattern); 129 EXPECT_EQ(0U, count); 130 } 131 132 // Test that when we indirectly import a declaration the custom ASTImporter 133 // is still intercepting the import. 134 TEST_P(RedirectingImporterTest, InterceptIndirectImport) { 135 Decl *From, *To; 136 std::tie(From, To) = 137 getImportedDecl("class shouldNotBeImported {};" 138 "class F { shouldNotBeImported f; };", 139 Lang_CXX03, "class realDecl {};", Lang_CXX03, "F"); 140 141 // Make sure our ASTImporter prevented the importing of the decl. 142 auto *ToTU = To->getTranslationUnitDecl(); 143 auto Pattern = functionDecl(hasName("shouldNotBeImported")); 144 unsigned count = 145 DeclCounterWithPredicate<CXXRecordDecl>().match(ToTU, Pattern); 146 EXPECT_EQ(0U, count); 147 } 148 149 struct ImportPath : ASTImporterOptionSpecificTestBase { 150 Decl *FromTU; 151 FunctionDecl *D0, *D1, *D2; 152 ImportPath() { 153 FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX03); 154 auto Pattern = functionDecl(hasName("f")); 155 D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 156 D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 157 D1 = D2->getPreviousDecl(); 158 } 159 }; 160 161 TEST_P(ImportPath, Push) { 162 ASTImporter::ImportPathTy path; 163 path.push(D0); 164 EXPECT_FALSE(path.hasCycleAtBack()); 165 } 166 167 TEST_P(ImportPath, SmallCycle) { 168 ASTImporter::ImportPathTy path; 169 path.push(D0); 170 path.push(D0); 171 EXPECT_TRUE(path.hasCycleAtBack()); 172 path.pop(); 173 EXPECT_FALSE(path.hasCycleAtBack()); 174 path.push(D0); 175 EXPECT_TRUE(path.hasCycleAtBack()); 176 } 177 178 TEST_P(ImportPath, GetSmallCycle) { 179 ASTImporter::ImportPathTy path; 180 path.push(D0); 181 path.push(D0); 182 EXPECT_TRUE(path.hasCycleAtBack()); 183 std::array<Decl* ,2> Res; 184 int i = 0; 185 for (Decl *Di : path.getCycleAtBack()) { 186 Res[i++] = Di; 187 } 188 ASSERT_EQ(i, 2); 189 EXPECT_EQ(Res[0], D0); 190 EXPECT_EQ(Res[1], D0); 191 } 192 193 TEST_P(ImportPath, GetCycle) { 194 ASTImporter::ImportPathTy path; 195 path.push(D0); 196 path.push(D1); 197 path.push(D2); 198 path.push(D0); 199 EXPECT_TRUE(path.hasCycleAtBack()); 200 std::array<Decl* ,4> Res; 201 int i = 0; 202 for (Decl *Di : path.getCycleAtBack()) { 203 Res[i++] = Di; 204 } 205 ASSERT_EQ(i, 4); 206 EXPECT_EQ(Res[0], D0); 207 EXPECT_EQ(Res[1], D2); 208 EXPECT_EQ(Res[2], D1); 209 EXPECT_EQ(Res[3], D0); 210 } 211 212 TEST_P(ImportPath, CycleAfterCycle) { 213 ASTImporter::ImportPathTy path; 214 path.push(D0); 215 path.push(D1); 216 path.push(D0); 217 path.push(D1); 218 path.push(D2); 219 path.push(D0); 220 EXPECT_TRUE(path.hasCycleAtBack()); 221 std::array<Decl* ,4> Res; 222 int i = 0; 223 for (Decl *Di : path.getCycleAtBack()) { 224 Res[i++] = Di; 225 } 226 ASSERT_EQ(i, 4); 227 EXPECT_EQ(Res[0], D0); 228 EXPECT_EQ(Res[1], D2); 229 EXPECT_EQ(Res[2], D1); 230 EXPECT_EQ(Res[3], D0); 231 232 path.pop(); 233 path.pop(); 234 path.pop(); 235 EXPECT_TRUE(path.hasCycleAtBack()); 236 i = 0; 237 for (Decl *Di : path.getCycleAtBack()) { 238 Res[i++] = Di; 239 } 240 ASSERT_EQ(i, 3); 241 EXPECT_EQ(Res[0], D0); 242 EXPECT_EQ(Res[1], D1); 243 EXPECT_EQ(Res[2], D0); 244 245 path.pop(); 246 EXPECT_FALSE(path.hasCycleAtBack()); 247 } 248 249 const internal::VariadicDynCastAllOfMatcher<Stmt, SourceLocExpr> sourceLocExpr; 250 251 AST_MATCHER_P(SourceLocExpr, hasBuiltinStr, StringRef, Str) { 252 return Node.getBuiltinStr() == Str; 253 } 254 255 TEST_P(ImportExpr, ImportSourceLocExpr) { 256 MatchVerifier<Decl> Verifier; 257 testImport("void declToImport() { (void)__builtin_FILE(); }", Lang_CXX03, "", 258 Lang_CXX03, Verifier, 259 functionDecl(hasDescendant( 260 sourceLocExpr(hasBuiltinStr("__builtin_FILE"))))); 261 testImport("void declToImport() { (void)__builtin_COLUMN(); }", Lang_CXX03, 262 "", Lang_CXX03, Verifier, 263 functionDecl(hasDescendant( 264 sourceLocExpr(hasBuiltinStr("__builtin_COLUMN"))))); 265 } 266 267 TEST_P(ImportExpr, ImportStringLiteral) { 268 MatchVerifier<Decl> Verifier; 269 testImport("void declToImport() { (void)\"foo\"; }", Lang_CXX03, "", 270 Lang_CXX03, Verifier, 271 functionDecl(hasDescendant( 272 stringLiteral(hasType(asString("const char[4]")))))); 273 testImport("void declToImport() { (void)L\"foo\"; }", Lang_CXX03, "", 274 Lang_CXX03, Verifier, 275 functionDecl(hasDescendant( 276 stringLiteral(hasType(asString("const wchar_t[4]")))))); 277 testImport("void declToImport() { (void) \"foo\" \"bar\"; }", Lang_CXX03, "", 278 Lang_CXX03, Verifier, 279 functionDecl(hasDescendant( 280 stringLiteral(hasType(asString("const char[7]")))))); 281 } 282 283 TEST_P(ImportExpr, ImportChooseExpr) { 284 MatchVerifier<Decl> Verifier; 285 286 // This case tests C code that is not condition-dependent and has a true 287 // condition. 288 testImport("void declToImport() { (void)__builtin_choose_expr(1, 2, 3); }", 289 Lang_C99, "", Lang_C99, Verifier, 290 functionDecl(hasDescendant(chooseExpr()))); 291 } 292 293 const internal::VariadicDynCastAllOfMatcher<Stmt, ShuffleVectorExpr> 294 shuffleVectorExpr; 295 296 TEST_P(ImportExpr, ImportShuffleVectorExpr) { 297 MatchVerifier<Decl> Verifier; 298 constexpr auto Code = R"code( 299 typedef double vector4double __attribute__((__vector_size__(32))); 300 vector4double declToImport(vector4double a, vector4double b) { 301 return __builtin_shufflevector(a, b, 0, 1, 2, 3); 302 } 303 )code"; 304 const auto Pattern = functionDecl(hasDescendant(shuffleVectorExpr( 305 allOf(has(declRefExpr(to(parmVarDecl(hasName("a"))))), 306 has(declRefExpr(to(parmVarDecl(hasName("b"))))), 307 has(integerLiteral(equals(0))), has(integerLiteral(equals(1))), 308 has(integerLiteral(equals(2))), has(integerLiteral(equals(3))))))); 309 testImport(Code, Lang_C99, "", Lang_C99, Verifier, Pattern); 310 } 311 312 TEST_P(ImportExpr, ImportGNUNullExpr) { 313 MatchVerifier<Decl> Verifier; 314 testImport("void declToImport() { (void)__null; }", Lang_CXX03, "", 315 Lang_CXX03, Verifier, 316 functionDecl(hasDescendant(gnuNullExpr(hasType(isInteger()))))); 317 } 318 319 TEST_P(ImportExpr, ImportGenericSelectionExpr) { 320 MatchVerifier<Decl> Verifier; 321 322 testImport( 323 "void declToImport() { int x; (void)_Generic(x, int: 0, float: 1); }", 324 Lang_C99, "", Lang_C99, Verifier, 325 functionDecl(hasDescendant(genericSelectionExpr()))); 326 } 327 328 TEST_P(ImportExpr, ImportCXXNullPtrLiteralExpr) { 329 MatchVerifier<Decl> Verifier; 330 testImport( 331 "void declToImport() { (void)nullptr; }", 332 Lang_CXX11, "", Lang_CXX11, Verifier, 333 functionDecl(hasDescendant(cxxNullPtrLiteralExpr()))); 334 } 335 336 337 TEST_P(ImportExpr, ImportFloatinglLiteralExpr) { 338 MatchVerifier<Decl> Verifier; 339 testImport("void declToImport() { (void)1.0; }", Lang_C99, "", Lang_C99, 340 Verifier, 341 functionDecl(hasDescendant( 342 floatLiteral(equals(1.0), hasType(asString("double")))))); 343 testImport("void declToImport() { (void)1.0e-5f; }", Lang_C99, "", Lang_C99, 344 Verifier, 345 functionDecl(hasDescendant( 346 floatLiteral(equals(1.0e-5f), hasType(asString("float")))))); 347 } 348 349 TEST_P(ImportFixedPointExpr, ImportFixedPointerLiteralExpr) { 350 MatchVerifier<Decl> Verifier; 351 testImport("void declToImport() { (void)1.0k; }", Lang_C99, "", Lang_C99, 352 Verifier, functionDecl(hasDescendant(fixedPointLiteral()))); 353 testImport("void declToImport() { (void)0.75r; }", Lang_C99, "", Lang_C99, 354 Verifier, functionDecl(hasDescendant(fixedPointLiteral()))); 355 } 356 357 TEST_P(ImportExpr, ImportImaginaryLiteralExpr) { 358 MatchVerifier<Decl> Verifier; 359 testImport( 360 "void declToImport() { (void)1.0i; }", 361 Lang_CXX14, "", Lang_CXX14, Verifier, 362 functionDecl(hasDescendant(imaginaryLiteral()))); 363 } 364 365 TEST_P(ImportExpr, ImportCompoundLiteralExpr) { 366 MatchVerifier<Decl> Verifier; 367 testImport("void declToImport() {" 368 " struct s { int x; long y; unsigned z; }; " 369 " (void)(struct s){ 42, 0L, 1U }; }", 370 Lang_CXX03, "", Lang_CXX03, Verifier, 371 functionDecl(hasDescendant(compoundLiteralExpr( 372 hasType(asString("struct s")), 373 has(initListExpr( 374 hasType(asString("struct s")), 375 has(integerLiteral(equals(42), hasType(asString("int")))), 376 has(integerLiteral(equals(0), hasType(asString("long")))), 377 has(integerLiteral( 378 equals(1), hasType(asString("unsigned int")))))))))); 379 } 380 381 TEST_P(ImportExpr, ImportCXXThisExpr) { 382 MatchVerifier<Decl> Verifier; 383 testImport("class declToImport { void f() { (void)this; } };", Lang_CXX03, "", 384 Lang_CXX03, Verifier, 385 cxxRecordDecl(hasMethod(hasDescendant( 386 cxxThisExpr(hasType(asString("class declToImport *"))))))); 387 } 388 389 TEST_P(ImportExpr, ImportAtomicExpr) { 390 MatchVerifier<Decl> Verifier; 391 testImport("void declToImport() { int *ptr; __atomic_load_n(ptr, 1); }", 392 Lang_C99, "", Lang_C99, Verifier, 393 functionDecl(hasDescendant(atomicExpr( 394 has(ignoringParenImpCasts( 395 declRefExpr(hasDeclaration(varDecl(hasName("ptr"))), 396 hasType(asString("int *"))))), 397 has(integerLiteral(equals(1), hasType(asString("int")))))))); 398 } 399 400 TEST_P(ImportExpr, ImportLabelDeclAndAddrLabelExpr) { 401 MatchVerifier<Decl> Verifier; 402 testImport("void declToImport() { loop: goto loop; (void)&&loop; }", Lang_C99, 403 "", Lang_C99, Verifier, 404 functionDecl(hasDescendant(labelStmt( 405 hasDeclaration(labelDecl(hasName("loop"))))), 406 hasDescendant(addrLabelExpr( 407 hasDeclaration(labelDecl(hasName("loop"))))))); 408 } 409 410 AST_MATCHER_P(TemplateDecl, hasTemplateDecl, 411 internal::Matcher<NamedDecl>, InnerMatcher) { 412 const NamedDecl *Template = Node.getTemplatedDecl(); 413 return Template && InnerMatcher.matches(*Template, Finder, Builder); 414 } 415 416 TEST_P(ImportExpr, ImportParenListExpr) { 417 MatchVerifier<Decl> Verifier; 418 testImport( 419 "template<typename T> class dummy { void f() { dummy X(*this); } };" 420 "typedef dummy<int> declToImport;" 421 "template class dummy<int>;", 422 Lang_CXX03, "", Lang_CXX03, Verifier, 423 typedefDecl(hasType(templateSpecializationType( 424 hasDeclaration(classTemplateSpecializationDecl(hasSpecializedTemplate( 425 classTemplateDecl(hasTemplateDecl(cxxRecordDecl(hasMethod(allOf( 426 hasName("f"), 427 hasBody(compoundStmt(has(declStmt(hasSingleDecl( 428 varDecl(hasInitializer(parenListExpr(has(unaryOperator( 429 hasOperatorName("*"), 430 hasUnaryOperand(cxxThisExpr()))))))))))))))))))))))); 431 } 432 433 TEST_P(ImportExpr, ImportSwitch) { 434 MatchVerifier<Decl> Verifier; 435 testImport("void declToImport() { int b; switch (b) { case 1: break; } }", 436 Lang_C99, "", Lang_C99, Verifier, 437 functionDecl(hasDescendant( 438 switchStmt(has(compoundStmt(has(caseStmt()))))))); 439 } 440 441 TEST_P(ImportExpr, ImportStmtExpr) { 442 MatchVerifier<Decl> Verifier; 443 testImport( 444 "void declToImport() { int b; int a = b ?: 1; int C = ({int X=4; X;}); }", 445 Lang_C99, "", Lang_C99, Verifier, 446 traverse(TK_AsIs, 447 functionDecl(hasDescendant(varDecl( 448 hasName("C"), hasType(asString("int")), 449 hasInitializer(stmtExpr( 450 hasAnySubstatement(declStmt(hasSingleDecl(varDecl( 451 hasName("X"), hasType(asString("int")), 452 hasInitializer(integerLiteral(equals(4))))))), 453 hasDescendant(implicitCastExpr())))))))); 454 } 455 456 TEST_P(ImportExpr, ImportConditionalOperator) { 457 MatchVerifier<Decl> Verifier; 458 testImport("void declToImport() { (void)(true ? 1 : -5); }", Lang_CXX03, "", 459 Lang_CXX03, Verifier, 460 functionDecl(hasDescendant(conditionalOperator( 461 hasCondition(cxxBoolLiteral(equals(true))), 462 hasTrueExpression(integerLiteral(equals(1))), 463 hasFalseExpression(unaryOperator( 464 hasUnaryOperand(integerLiteral(equals(5))))))))); 465 } 466 467 TEST_P(ImportExpr, ImportBinaryConditionalOperator) { 468 MatchVerifier<Decl> Verifier; 469 testImport( 470 "void declToImport() { (void)(1 ?: -5); }", Lang_CXX03, "", Lang_CXX03, 471 Verifier, 472 traverse(TK_AsIs, 473 functionDecl(hasDescendant(binaryConditionalOperator( 474 hasCondition(implicitCastExpr( 475 hasSourceExpression(opaqueValueExpr( 476 hasSourceExpression(integerLiteral(equals(1))))), 477 hasType(booleanType()))), 478 hasTrueExpression(opaqueValueExpr( 479 hasSourceExpression(integerLiteral(equals(1))))), 480 hasFalseExpression(unaryOperator( 481 hasOperatorName("-"), 482 hasUnaryOperand(integerLiteral(equals(5)))))))))); 483 } 484 485 TEST_P(ImportExpr, ImportDesignatedInitExpr) { 486 MatchVerifier<Decl> Verifier; 487 testImport( 488 "void declToImport() {" 489 " struct point { double x; double y; };" 490 " struct point ptarray[10] = " 491 "{ [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }", 492 Lang_C99, "", Lang_C99, Verifier, 493 functionDecl(hasDescendant(initListExpr( 494 has(designatedInitExpr(designatorCountIs(2), 495 hasDescendant(floatLiteral(equals(1.0))), 496 hasDescendant(integerLiteral(equals(2))))), 497 has(designatedInitExpr(designatorCountIs(2), 498 hasDescendant(floatLiteral(equals(2.0))), 499 hasDescendant(integerLiteral(equals(2))))), 500 has(designatedInitExpr(designatorCountIs(2), 501 hasDescendant(floatLiteral(equals(1.0))), 502 hasDescendant(integerLiteral(equals(0))))))))); 503 } 504 505 TEST_P(ImportExpr, ImportPredefinedExpr) { 506 MatchVerifier<Decl> Verifier; 507 // __func__ expands as StringLiteral("declToImport") 508 testImport("void declToImport() { (void)__func__; }", Lang_CXX03, "", 509 Lang_CXX03, Verifier, 510 functionDecl(hasDescendant(predefinedExpr( 511 hasType(asString("const char[13]")), 512 has(stringLiteral(hasType(asString("const char[13]")))))))); 513 } 514 515 TEST_P(ImportExpr, ImportInitListExpr) { 516 MatchVerifier<Decl> Verifier; 517 testImport( 518 "void declToImport() {" 519 " struct point { double x; double y; };" 520 " point ptarray[10] = { [2].y = 1.0, [2].x = 2.0," 521 " [0].x = 1.0 }; }", 522 Lang_CXX03, "", Lang_CXX03, Verifier, 523 functionDecl(hasDescendant(initListExpr( 524 has(cxxConstructExpr(requiresZeroInitialization())), 525 has(initListExpr( 526 hasType(asString("struct point")), has(floatLiteral(equals(1.0))), 527 has(implicitValueInitExpr(hasType(asString("double")))))), 528 has(initListExpr(hasType(asString("struct point")), 529 has(floatLiteral(equals(2.0))), 530 has(floatLiteral(equals(1.0))))))))); 531 } 532 533 const internal::VariadicDynCastAllOfMatcher<Expr, CXXDefaultInitExpr> 534 cxxDefaultInitExpr; 535 536 TEST_P(ImportExpr, ImportCXXDefaultInitExpr) { 537 MatchVerifier<Decl> Verifier; 538 testImport("class declToImport { int DefInit = 5; }; declToImport X;", 539 Lang_CXX11, "", Lang_CXX11, Verifier, 540 cxxRecordDecl(hasDescendant(cxxConstructorDecl( 541 hasAnyConstructorInitializer(cxxCtorInitializer( 542 withInitializer(cxxDefaultInitExpr()))))))); 543 testImport( 544 "struct X { int A = 5; }; X declToImport{};", Lang_CXX17, "", Lang_CXX17, 545 Verifier, 546 varDecl(hasInitializer(initListExpr(hasInit(0, cxxDefaultInitExpr()))))); 547 } 548 549 const internal::VariadicDynCastAllOfMatcher<Expr, VAArgExpr> vaArgExpr; 550 551 TEST_P(ImportExpr, ImportVAArgExpr) { 552 MatchVerifier<Decl> Verifier; 553 testImport("void declToImport(__builtin_va_list list, ...) {" 554 " (void)__builtin_va_arg(list, int); }", 555 Lang_CXX03, "", Lang_CXX03, Verifier, 556 functionDecl(hasDescendant( 557 cStyleCastExpr(hasSourceExpression(vaArgExpr()))))); 558 } 559 560 TEST_P(ImportExpr, CXXTemporaryObjectExpr) { 561 MatchVerifier<Decl> Verifier; 562 testImport( 563 "struct C {};" 564 "void declToImport() { C c = C(); }", 565 Lang_CXX03, "", Lang_CXX03, Verifier, 566 traverse(TK_AsIs, 567 functionDecl(hasDescendant(exprWithCleanups(has(cxxConstructExpr( 568 has(materializeTemporaryExpr(has(implicitCastExpr( 569 has(cxxTemporaryObjectExpr())))))))))))); 570 } 571 572 TEST_P(ImportType, ImportAtomicType) { 573 MatchVerifier<Decl> Verifier; 574 testImport( 575 "void declToImport() { typedef _Atomic(int) a_int; }", 576 Lang_CXX11, "", Lang_CXX11, Verifier, 577 functionDecl(hasDescendant(typedefDecl(has(atomicType()))))); 578 } 579 580 TEST_P(ImportType, ImportUsingType) { 581 MatchVerifier<Decl> Verifier; 582 testImport("struct C {};" 583 "void declToImport() { using ::C; new C{}; }", 584 Lang_CXX11, "", Lang_CXX11, Verifier, 585 functionDecl(hasDescendant( 586 cxxNewExpr(hasType(pointerType(pointee(usingType()))))))); 587 } 588 589 TEST_P(ImportDecl, ImportFunctionTemplateDecl) { 590 MatchVerifier<Decl> Verifier; 591 testImport("template <typename T> void declToImport() { };", Lang_CXX03, "", 592 Lang_CXX03, Verifier, functionTemplateDecl()); 593 } 594 595 TEST_P(ImportExpr, ImportCXXDependentScopeMemberExpr) { 596 MatchVerifier<Decl> Verifier; 597 testImport("template <typename T> struct C { T t; };" 598 "template <typename T> void declToImport() {" 599 " C<T> d;" 600 " (void)d.t;" 601 "}" 602 "void instantiate() { declToImport<int>(); }", 603 Lang_CXX03, "", Lang_CXX03, Verifier, 604 functionTemplateDecl(hasDescendant( 605 cStyleCastExpr(has(cxxDependentScopeMemberExpr()))))); 606 testImport("template <typename T> struct C { T t; };" 607 "template <typename T> void declToImport() {" 608 " C<T> d;" 609 " (void)(&d)->t;" 610 "}" 611 "void instantiate() { declToImport<int>(); }", 612 Lang_CXX03, "", Lang_CXX03, Verifier, 613 functionTemplateDecl(hasDescendant( 614 cStyleCastExpr(has(cxxDependentScopeMemberExpr()))))); 615 } 616 617 TEST_P(ImportType, ImportTypeAliasTemplate) { 618 MatchVerifier<Decl> Verifier; 619 testImport( 620 "template <int K>" 621 "struct dummy { static const int i = K; };" 622 "template <int K> using dummy2 = dummy<K>;" 623 "int declToImport() { return dummy2<3>::i; }", 624 Lang_CXX11, "", Lang_CXX11, Verifier, 625 traverse(TK_AsIs, 626 functionDecl(hasDescendant(implicitCastExpr(has(declRefExpr()))), 627 unless(hasAncestor( 628 translationUnitDecl(has(typeAliasDecl()))))))); 629 } 630 631 const internal::VariadicDynCastAllOfMatcher<Decl, VarTemplateSpecializationDecl> 632 varTemplateSpecializationDecl; 633 634 TEST_P(ImportDecl, ImportVarTemplate) { 635 MatchVerifier<Decl> Verifier; 636 testImport( 637 "template <typename T>" 638 "T pi = T(3.1415926535897932385L);" 639 "void declToImport() { (void)pi<int>; }", 640 Lang_CXX14, "", Lang_CXX14, Verifier, 641 functionDecl( 642 hasDescendant(declRefExpr(to(varTemplateSpecializationDecl()))), 643 unless(hasAncestor(translationUnitDecl(has(varDecl( 644 hasName("pi"), unless(varTemplateSpecializationDecl())))))))); 645 } 646 647 TEST_P(ImportType, ImportPackExpansion) { 648 MatchVerifier<Decl> Verifier; 649 testImport("template <typename... Args>" 650 "struct dummy {" 651 " dummy(Args... args) {}" 652 " static const int i = 4;" 653 "};" 654 "int declToImport() { return dummy<int>::i; }", 655 Lang_CXX11, "", Lang_CXX11, Verifier, 656 traverse(TK_AsIs, functionDecl(hasDescendant(returnStmt(has( 657 implicitCastExpr(has(declRefExpr())))))))); 658 } 659 660 const internal::VariadicDynCastAllOfMatcher<Type, 661 DependentTemplateSpecializationType> 662 dependentTemplateSpecializationType; 663 664 TEST_P(ImportType, ImportDependentTemplateSpecialization) { 665 MatchVerifier<Decl> Verifier; 666 testImport("template<typename T>" 667 "struct A;" 668 "template<typename T>" 669 "struct declToImport {" 670 " typename A<T>::template B<T> a;" 671 "};", 672 Lang_CXX03, "", Lang_CXX03, Verifier, 673 classTemplateDecl(has(cxxRecordDecl(has( 674 fieldDecl(hasType(dependentTemplateSpecializationType()))))))); 675 } 676 677 TEST_P(ImportType, ImportDeducedTemplateSpecialization) { 678 MatchVerifier<Decl> Verifier; 679 testImport("template <typename T>" 680 "class C { public: C(T); };" 681 "C declToImport(123);", 682 Lang_CXX17, "", Lang_CXX17, Verifier, 683 varDecl(hasType(deducedTemplateSpecializationType()))); 684 } 685 686 const internal::VariadicDynCastAllOfMatcher<Stmt, SizeOfPackExpr> 687 sizeOfPackExpr; 688 689 TEST_P(ImportExpr, ImportSizeOfPackExpr) { 690 MatchVerifier<Decl> Verifier; 691 testImport( 692 "template <typename... Ts>" 693 "void declToImport() {" 694 " const int i = sizeof...(Ts);" 695 "};" 696 "void g() { declToImport<int>(); }", 697 Lang_CXX11, "", Lang_CXX11, Verifier, 698 functionTemplateDecl(hasDescendant(sizeOfPackExpr()))); 699 testImport( 700 "template <typename... Ts>" 701 "using X = int[sizeof...(Ts)];" 702 "template <typename... Us>" 703 "struct Y {" 704 " X<Us..., int, double, int, Us...> f;" 705 "};" 706 "Y<float, int> declToImport;", 707 Lang_CXX11, "", Lang_CXX11, Verifier, 708 varDecl(hasType(classTemplateSpecializationDecl(has(fieldDecl(hasType( 709 hasUnqualifiedDesugaredType(constantArrayType(hasSize(7)))))))))); 710 } 711 712 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFoldExpr> cxxFoldExpr; 713 714 AST_MATCHER_P(CXXFoldExpr, hasOperator, BinaryOperatorKind, Op) { 715 return Node.getOperator() == Op; 716 } 717 AST_MATCHER(CXXFoldExpr, hasInit) { return Node.getInit(); } 718 AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); } 719 AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); } 720 721 TEST_P(ImportExpr, ImportCXXFoldExpr) { 722 auto Match1 = 723 cxxFoldExpr(hasOperator(BO_Add), isLeftFold(), unless(hasInit())); 724 auto Match2 = cxxFoldExpr(hasOperator(BO_Sub), isLeftFold(), hasInit()); 725 auto Match3 = 726 cxxFoldExpr(hasOperator(BO_Mul), isRightFold(), unless(hasInit())); 727 auto Match4 = cxxFoldExpr(hasOperator(BO_Div), isRightFold(), hasInit()); 728 729 MatchVerifier<Decl> Verifier; 730 testImport("template <typename... Ts>" 731 "void declToImport(Ts... args) {" 732 " const int i1 = (... + args);" 733 " const int i2 = (1 - ... - args);" 734 " const int i3 = (args * ...);" 735 " const int i4 = (args / ... / 1);" 736 "};" 737 "void g() { declToImport(1, 2, 3, 4, 5); }", 738 Lang_CXX17, "", Lang_CXX17, Verifier, 739 functionTemplateDecl(hasDescendant(Match1), hasDescendant(Match2), 740 hasDescendant(Match3), 741 hasDescendant(Match4))); 742 } 743 744 /// \brief Matches __builtin_types_compatible_p: 745 /// GNU extension to check equivalent types 746 /// Given 747 /// \code 748 /// __builtin_types_compatible_p(int, int) 749 /// \endcode 750 // will generate TypeTraitExpr <...> 'int' 751 const internal::VariadicDynCastAllOfMatcher<Stmt, TypeTraitExpr> typeTraitExpr; 752 753 TEST_P(ImportExpr, ImportTypeTraitExpr) { 754 MatchVerifier<Decl> Verifier; 755 testImport( 756 "void declToImport() { " 757 " (void)__builtin_types_compatible_p(int, int);" 758 "}", 759 Lang_C99, "", Lang_C99, Verifier, 760 functionDecl(hasDescendant(typeTraitExpr(hasType(asString("int")))))); 761 } 762 763 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr> cxxTypeidExpr; 764 765 TEST_P(ImportExpr, ImportCXXTypeidExpr) { 766 MatchVerifier<Decl> Verifier; 767 testImport( 768 "namespace std { class type_info {}; }" 769 "void declToImport() {" 770 " int x;" 771 " auto a = typeid(int); auto b = typeid(x);" 772 "}", 773 Lang_CXX11, "", Lang_CXX11, Verifier, 774 traverse( 775 TK_AsIs, 776 functionDecl( 777 hasDescendant(varDecl(hasName("a"), hasInitializer(hasDescendant( 778 cxxTypeidExpr())))), 779 hasDescendant(varDecl(hasName("b"), hasInitializer(hasDescendant( 780 cxxTypeidExpr()))))))); 781 } 782 783 TEST_P(ImportExpr, ImportTypeTraitExprValDep) { 784 MatchVerifier<Decl> Verifier; 785 testImport( 786 "template<typename T> struct declToImport {" 787 " void m() { (void)__is_pod(T); }" 788 "};" 789 "void f() { declToImport<int>().m(); }", 790 Lang_CXX11, "", Lang_CXX11, Verifier, 791 classTemplateDecl(has(cxxRecordDecl(has( 792 functionDecl(hasDescendant( 793 typeTraitExpr(hasType(booleanType()))))))))); 794 } 795 796 TEST_P(ImportDecl, ImportRecordDeclInFunc) { 797 MatchVerifier<Decl> Verifier; 798 testImport("int declToImport() { " 799 " struct data_t {int a;int b;};" 800 " struct data_t d;" 801 " return 0;" 802 "}", 803 Lang_C99, "", Lang_C99, Verifier, 804 functionDecl(hasBody(compoundStmt( 805 has(declStmt(hasSingleDecl(varDecl(hasName("d"))))))))); 806 } 807 808 TEST_P(ImportDecl, ImportedVarDeclPreservesThreadLocalStorage) { 809 MatchVerifier<Decl> Verifier; 810 testImport("thread_local int declToImport;", Lang_CXX11, "", Lang_CXX11, 811 Verifier, varDecl(hasThreadStorageDuration())); 812 } 813 814 TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordTypeInFunc) { 815 Decl *FromTU = getTuDecl("int declToImport() { " 816 " struct data_t {int a;int b;};" 817 " struct data_t d;" 818 " return 0;" 819 "}", 820 Lang_C99, "input.c"); 821 auto *FromVar = 822 FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("d"))); 823 ASSERT_TRUE(FromVar); 824 auto ToType = 825 ImportType(FromVar->getType().getCanonicalType(), FromVar, Lang_C99); 826 EXPECT_FALSE(ToType.isNull()); 827 } 828 829 TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordDeclInFuncParams) { 830 // This construct is not supported by ASTImporter. 831 Decl *FromTU = getTuDecl( 832 "int declToImport(struct data_t{int a;int b;} ***d){ return 0; }", 833 Lang_C99, "input.c"); 834 auto *From = FirstDeclMatcher<FunctionDecl>().match( 835 FromTU, functionDecl(hasName("declToImport"))); 836 ASSERT_TRUE(From); 837 auto *To = Import(From, Lang_C99); 838 EXPECT_EQ(To, nullptr); 839 } 840 841 TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordDeclInFuncFromMacro) { 842 Decl *FromTU = 843 getTuDecl("#define NONAME_SIZEOF(type) sizeof(struct{type *dummy;}) \n" 844 "int declToImport(){ return NONAME_SIZEOF(int); }", 845 Lang_C99, "input.c"); 846 auto *From = FirstDeclMatcher<FunctionDecl>().match( 847 FromTU, functionDecl(hasName("declToImport"))); 848 ASSERT_TRUE(From); 849 auto *To = Import(From, Lang_C99); 850 ASSERT_TRUE(To); 851 EXPECT_TRUE(MatchVerifier<FunctionDecl>().match( 852 To, functionDecl(hasName("declToImport"), 853 hasDescendant(unaryExprOrTypeTraitExpr())))); 854 } 855 856 TEST_P(ASTImporterOptionSpecificTestBase, 857 ImportRecordDeclInFuncParamsFromMacro) { 858 // This construct is not supported by ASTImporter. 859 Decl *FromTU = 860 getTuDecl("#define PAIR_STRUCT(type) struct data_t{type a;type b;} \n" 861 "int declToImport(PAIR_STRUCT(int) ***d){ return 0; }", 862 Lang_C99, "input.c"); 863 auto *From = FirstDeclMatcher<FunctionDecl>().match( 864 FromTU, functionDecl(hasName("declToImport"))); 865 ASSERT_TRUE(From); 866 auto *To = Import(From, Lang_C99); 867 EXPECT_EQ(To, nullptr); 868 } 869 870 const internal::VariadicDynCastAllOfMatcher<Expr, CXXPseudoDestructorExpr> 871 cxxPseudoDestructorExpr; 872 873 TEST_P(ImportExpr, ImportCXXPseudoDestructorExpr) { 874 MatchVerifier<Decl> Verifier; 875 testImport( 876 "typedef int T;" 877 "void declToImport(int *p) {" 878 " T t;" 879 " p->T::~T();" 880 "}", 881 Lang_CXX03, "", Lang_CXX03, Verifier, 882 functionDecl(hasDescendant(callExpr(has(cxxPseudoDestructorExpr()))))); 883 } 884 885 TEST_P(ImportDecl, ImportUsingDecl) { 886 MatchVerifier<Decl> Verifier; 887 testImport("namespace foo { int bar; }" 888 "void declToImport() { using foo::bar; }", 889 Lang_CXX03, "", Lang_CXX03, Verifier, 890 functionDecl(hasDescendant(usingDecl(hasName("bar"))))); 891 } 892 893 TEST_P(ImportDecl, ImportUsingEnumDecl) { 894 MatchVerifier<Decl> Verifier; 895 testImport("namespace foo { enum bar { baz, toto, quux }; }" 896 "void declToImport() { using enum foo::bar; }", 897 Lang_CXX20, "", Lang_CXX20, Verifier, 898 functionDecl(hasDescendant(usingEnumDecl(hasName("bar"))))); 899 } 900 901 /// \brief Matches shadow declarations introduced into a scope by a 902 /// (resolved) using declaration. 903 /// 904 /// Given 905 /// \code 906 /// namespace n { int f; } 907 /// namespace declToImport { using n::f; } 908 /// \endcode 909 /// usingShadowDecl() 910 /// matches \code f \endcode 911 const internal::VariadicDynCastAllOfMatcher<Decl, 912 UsingShadowDecl> usingShadowDecl; 913 914 TEST_P(ImportDecl, ImportUsingShadowDecl) { 915 MatchVerifier<Decl> Verifier; 916 // from using-decl 917 testImport("namespace foo { int bar; }" 918 "namespace declToImport { using foo::bar; }", 919 Lang_CXX03, "", Lang_CXX03, Verifier, 920 namespaceDecl(has(usingShadowDecl(hasName("bar"))))); 921 // from using-enum-decl 922 testImport("namespace foo { enum bar {baz, toto, quux }; }" 923 "namespace declToImport { using enum foo::bar; }", 924 Lang_CXX20, "", Lang_CXX20, Verifier, 925 namespaceDecl(has(usingShadowDecl(hasName("baz"))))); 926 } 927 928 TEST_P(ImportExpr, ImportUnresolvedLookupExpr) { 929 MatchVerifier<Decl> Verifier; 930 testImport("template<typename T> int foo();" 931 "template <typename T> void declToImport() {" 932 " (void)::foo<T>;" 933 " (void)::template foo<T>;" 934 "}" 935 "void instantiate() { declToImport<int>(); }", 936 Lang_CXX03, "", Lang_CXX03, Verifier, 937 functionTemplateDecl(hasDescendant(unresolvedLookupExpr()))); 938 } 939 940 TEST_P(ImportExpr, ImportCXXUnresolvedConstructExpr) { 941 MatchVerifier<Decl> Verifier; 942 testImport("template <typename T> struct C { T t; };" 943 "template <typename T> void declToImport() {" 944 " C<T> d;" 945 " d.t = T();" 946 "}" 947 "void instantiate() { declToImport<int>(); }", 948 Lang_CXX03, "", Lang_CXX03, Verifier, 949 functionTemplateDecl(hasDescendant( 950 binaryOperator(has(cxxUnresolvedConstructExpr()))))); 951 testImport("template <typename T> struct C { T t; };" 952 "template <typename T> void declToImport() {" 953 " C<T> d;" 954 " (&d)->t = T();" 955 "}" 956 "void instantiate() { declToImport<int>(); }", 957 Lang_CXX03, "", Lang_CXX03, Verifier, 958 functionTemplateDecl(hasDescendant( 959 binaryOperator(has(cxxUnresolvedConstructExpr()))))); 960 } 961 962 /// Check that function "declToImport()" (which is the templated function 963 /// for corresponding FunctionTemplateDecl) is not added into DeclContext. 964 /// Same for class template declarations. 965 TEST_P(ImportDecl, ImportTemplatedDeclForTemplate) { 966 MatchVerifier<Decl> Verifier; 967 testImport("template <typename T> void declToImport() { T a = 1; }" 968 "void instantiate() { declToImport<int>(); }", 969 Lang_CXX03, "", Lang_CXX03, Verifier, 970 functionTemplateDecl(hasAncestor(translationUnitDecl( 971 unless(has(functionDecl(hasName("declToImport")))))))); 972 testImport("template <typename T> struct declToImport { T t; };" 973 "void instantiate() { declToImport<int>(); }", 974 Lang_CXX03, "", Lang_CXX03, Verifier, 975 classTemplateDecl(hasAncestor(translationUnitDecl( 976 unless(has(cxxRecordDecl(hasName("declToImport")))))))); 977 } 978 979 TEST_P(ImportDecl, ImportClassTemplatePartialSpecialization) { 980 MatchVerifier<Decl> Verifier; 981 auto Code = 982 R"s( 983 struct declToImport { 984 template <typename T0> struct X; 985 template <typename T0> struct X<T0 *> {}; 986 }; 987 )s"; 988 testImport(Code, Lang_CXX03, "", Lang_CXX03, Verifier, 989 recordDecl(has(classTemplateDecl()), 990 has(classTemplateSpecializationDecl()))); 991 } 992 993 TEST_P(ImportExpr, CXXOperatorCallExpr) { 994 MatchVerifier<Decl> Verifier; 995 testImport( 996 "class declToImport {" 997 " void f() { *this = declToImport(); }" 998 "};", 999 Lang_CXX03, "", Lang_CXX03, Verifier, 1000 cxxRecordDecl(has(cxxMethodDecl(hasDescendant(cxxOperatorCallExpr()))))); 1001 } 1002 1003 TEST_P(ImportExpr, DependentSizedArrayType) { 1004 MatchVerifier<Decl> Verifier; 1005 testImport("template<typename T, int Size> class declToImport {" 1006 " T data[Size];" 1007 "};", 1008 Lang_CXX03, "", Lang_CXX03, Verifier, 1009 classTemplateDecl(has(cxxRecordDecl( 1010 has(fieldDecl(hasType(dependentSizedArrayType()))))))); 1011 } 1012 1013 TEST_P(ASTImporterOptionSpecificTestBase, TemplateTypeParmDeclNoDefaultArg) { 1014 Decl *FromTU = getTuDecl("template<typename T> struct X {};", Lang_CXX03); 1015 auto From = FirstDeclMatcher<TemplateTypeParmDecl>().match( 1016 FromTU, templateTypeParmDecl(hasName("T"))); 1017 TemplateTypeParmDecl *To = Import(From, Lang_CXX03); 1018 ASSERT_FALSE(To->hasDefaultArgument()); 1019 } 1020 1021 TEST_P(ASTImporterOptionSpecificTestBase, TemplateTypeParmDeclDefaultArg) { 1022 Decl *FromTU = 1023 getTuDecl("template<typename T = int> struct X {};", Lang_CXX03); 1024 auto From = FirstDeclMatcher<TemplateTypeParmDecl>().match( 1025 FromTU, templateTypeParmDecl(hasName("T"))); 1026 TemplateTypeParmDecl *To = Import(From, Lang_CXX03); 1027 ASSERT_TRUE(To->hasDefaultArgument()); 1028 QualType ToArg = To->getDefaultArgument(); 1029 ASSERT_EQ(ToArg, QualType(To->getASTContext().IntTy)); 1030 } 1031 1032 TEST_P(ASTImporterOptionSpecificTestBase, ImportBeginLocOfDeclRefExpr) { 1033 Decl *FromTU = 1034 getTuDecl("class A { public: static int X; }; void f() { (void)A::X; }", 1035 Lang_CXX03); 1036 auto From = FirstDeclMatcher<FunctionDecl>().match( 1037 FromTU, functionDecl(hasName("f"))); 1038 ASSERT_TRUE(From); 1039 ASSERT_TRUE( 1040 cast<CStyleCastExpr>(cast<CompoundStmt>(From->getBody())->body_front()) 1041 ->getSubExpr() 1042 ->getBeginLoc() 1043 .isValid()); 1044 FunctionDecl *To = Import(From, Lang_CXX03); 1045 ASSERT_TRUE(To); 1046 ASSERT_TRUE( 1047 cast<CStyleCastExpr>(cast<CompoundStmt>(To->getBody())->body_front()) 1048 ->getSubExpr() 1049 ->getBeginLoc() 1050 .isValid()); 1051 } 1052 1053 TEST_P(ASTImporterOptionSpecificTestBase, 1054 TemplateTemplateParmDeclNoDefaultArg) { 1055 Decl *FromTU = getTuDecl(R"( 1056 template<template<typename> typename TT> struct Y {}; 1057 )", 1058 Lang_CXX17); 1059 auto From = FirstDeclMatcher<TemplateTemplateParmDecl>().match( 1060 FromTU, templateTemplateParmDecl(hasName("TT"))); 1061 TemplateTemplateParmDecl *To = Import(From, Lang_CXX17); 1062 ASSERT_FALSE(To->hasDefaultArgument()); 1063 } 1064 1065 TEST_P(ASTImporterOptionSpecificTestBase, TemplateTemplateParmDeclDefaultArg) { 1066 Decl *FromTU = getTuDecl(R"( 1067 template<typename T> struct X {}; 1068 template<template<typename> typename TT = X> struct Y {}; 1069 )", 1070 Lang_CXX17); 1071 auto From = FirstDeclMatcher<TemplateTemplateParmDecl>().match( 1072 FromTU, templateTemplateParmDecl(hasName("TT"))); 1073 TemplateTemplateParmDecl *To = Import(From, Lang_CXX17); 1074 ASSERT_TRUE(To->hasDefaultArgument()); 1075 const TemplateArgument &ToDefaultArg = To->getDefaultArgument().getArgument(); 1076 ASSERT_TRUE(To->isTemplateDecl()); 1077 TemplateDecl *ToTemplate = ToDefaultArg.getAsTemplate().getAsTemplateDecl(); 1078 1079 // Find the default argument template 'X' in the AST and compare it against 1080 // the default argument we got. 1081 auto ToExpectedDecl = FirstDeclMatcher<ClassTemplateDecl>().match( 1082 To->getTranslationUnitDecl(), classTemplateDecl(hasName("X"))); 1083 ASSERT_EQ(ToTemplate, ToExpectedDecl); 1084 } 1085 1086 TEST_P(ASTImporterOptionSpecificTestBase, NonTypeTemplateParmDeclNoDefaultArg) { 1087 Decl *FromTU = getTuDecl("template<int N> struct X {};", Lang_CXX03); 1088 auto From = FirstDeclMatcher<NonTypeTemplateParmDecl>().match( 1089 FromTU, nonTypeTemplateParmDecl(hasName("N"))); 1090 NonTypeTemplateParmDecl *To = Import(From, Lang_CXX03); 1091 ASSERT_FALSE(To->hasDefaultArgument()); 1092 } 1093 1094 TEST_P(ASTImporterOptionSpecificTestBase, NonTypeTemplateParmDeclDefaultArg) { 1095 Decl *FromTU = getTuDecl("template<int S = 1> struct X {};", Lang_CXX03); 1096 auto From = FirstDeclMatcher<NonTypeTemplateParmDecl>().match( 1097 FromTU, nonTypeTemplateParmDecl(hasName("S"))); 1098 NonTypeTemplateParmDecl *To = Import(From, Lang_CXX03); 1099 ASSERT_TRUE(To->hasDefaultArgument()); 1100 Stmt *ToArg = To->getDefaultArgument(); 1101 ASSERT_TRUE(isa<ConstantExpr>(ToArg)); 1102 ToArg = *ToArg->child_begin(); 1103 ASSERT_TRUE(isa<IntegerLiteral>(ToArg)); 1104 ASSERT_EQ(cast<IntegerLiteral>(ToArg)->getValue().getLimitedValue(), 1U); 1105 } 1106 1107 TEST_P(ASTImporterOptionSpecificTestBase, 1108 ImportOfTemplatedDeclOfClassTemplateDecl) { 1109 Decl *FromTU = getTuDecl("template<class X> struct S{};", Lang_CXX03); 1110 auto From = 1111 FirstDeclMatcher<ClassTemplateDecl>().match(FromTU, classTemplateDecl()); 1112 ASSERT_TRUE(From); 1113 auto To = cast<ClassTemplateDecl>(Import(From, Lang_CXX03)); 1114 ASSERT_TRUE(To); 1115 Decl *ToTemplated = To->getTemplatedDecl(); 1116 Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX03); 1117 EXPECT_TRUE(ToTemplated1); 1118 EXPECT_EQ(ToTemplated1, ToTemplated); 1119 } 1120 1121 TEST_P(ASTImporterOptionSpecificTestBase, 1122 ImportOfTemplatedDeclOfFunctionTemplateDecl) { 1123 Decl *FromTU = getTuDecl("template<class X> void f(){}", Lang_CXX03); 1124 auto From = FirstDeclMatcher<FunctionTemplateDecl>().match( 1125 FromTU, functionTemplateDecl()); 1126 ASSERT_TRUE(From); 1127 auto To = cast<FunctionTemplateDecl>(Import(From, Lang_CXX03)); 1128 ASSERT_TRUE(To); 1129 Decl *ToTemplated = To->getTemplatedDecl(); 1130 Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX03); 1131 EXPECT_TRUE(ToTemplated1); 1132 EXPECT_EQ(ToTemplated1, ToTemplated); 1133 } 1134 1135 TEST_P(ASTImporterOptionSpecificTestBase, 1136 ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { 1137 Decl *FromTU = getTuDecl("template<class X> struct S{};", Lang_CXX03); 1138 auto FromFT = 1139 FirstDeclMatcher<ClassTemplateDecl>().match(FromTU, classTemplateDecl()); 1140 ASSERT_TRUE(FromFT); 1141 1142 auto ToTemplated = 1143 cast<CXXRecordDecl>(Import(FromFT->getTemplatedDecl(), Lang_CXX03)); 1144 EXPECT_TRUE(ToTemplated); 1145 auto ToTU = ToTemplated->getTranslationUnitDecl(); 1146 auto ToFT = 1147 FirstDeclMatcher<ClassTemplateDecl>().match(ToTU, classTemplateDecl()); 1148 EXPECT_TRUE(ToFT); 1149 } 1150 1151 TEST_P(ASTImporterOptionSpecificTestBase, 1152 ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { 1153 Decl *FromTU = getTuDecl("template<class X> void f(){}", Lang_CXX03); 1154 auto FromFT = FirstDeclMatcher<FunctionTemplateDecl>().match( 1155 FromTU, functionTemplateDecl()); 1156 ASSERT_TRUE(FromFT); 1157 1158 auto ToTemplated = 1159 cast<FunctionDecl>(Import(FromFT->getTemplatedDecl(), Lang_CXX03)); 1160 EXPECT_TRUE(ToTemplated); 1161 auto ToTU = ToTemplated->getTranslationUnitDecl(); 1162 auto ToFT = FirstDeclMatcher<FunctionTemplateDecl>().match( 1163 ToTU, functionTemplateDecl()); 1164 EXPECT_TRUE(ToFT); 1165 } 1166 1167 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplatedDecl) { 1168 auto Code = 1169 R"( 1170 namespace x { 1171 template<class X> struct S1{}; 1172 template<class X> struct S2{}; 1173 template<class X> struct S3{}; 1174 } 1175 )"; 1176 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 1177 auto FromNs = 1178 FirstDeclMatcher<NamespaceDecl>().match(FromTU, namespaceDecl()); 1179 auto ToNs = cast<NamespaceDecl>(Import(FromNs, Lang_CXX03)); 1180 ASSERT_TRUE(ToNs); 1181 auto From = 1182 FirstDeclMatcher<ClassTemplateDecl>().match(FromTU, 1183 classTemplateDecl( 1184 hasName("S2"))); 1185 auto To = 1186 FirstDeclMatcher<ClassTemplateDecl>().match(ToNs, 1187 classTemplateDecl( 1188 hasName("S2"))); 1189 ASSERT_TRUE(From); 1190 ASSERT_TRUE(To); 1191 auto ToTemplated = To->getTemplatedDecl(); 1192 auto ToTemplated1 = 1193 cast<CXXRecordDecl>(Import(From->getTemplatedDecl(), Lang_CXX03)); 1194 EXPECT_TRUE(ToTemplated1); 1195 ASSERT_EQ(ToTemplated1, ToTemplated); 1196 } 1197 1198 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) { 1199 // This tests the import of isConditionTrue directly to make sure the importer 1200 // gets it right. 1201 Decl *From, *To; 1202 std::tie(From, To) = getImportedDecl( 1203 "void declToImport() { (void)__builtin_choose_expr(1, 0, 1); }", Lang_C99, 1204 "", Lang_C99); 1205 1206 auto ToResults = match(chooseExpr().bind("choose"), To->getASTContext()); 1207 auto FromResults = match(chooseExpr().bind("choose"), From->getASTContext()); 1208 1209 const ChooseExpr *FromChooseExpr = 1210 selectFirst<ChooseExpr>("choose", FromResults); 1211 ASSERT_TRUE(FromChooseExpr); 1212 1213 const ChooseExpr *ToChooseExpr = selectFirst<ChooseExpr>("choose", ToResults); 1214 ASSERT_TRUE(ToChooseExpr); 1215 1216 EXPECT_EQ(FromChooseExpr->isConditionTrue(), ToChooseExpr->isConditionTrue()); 1217 EXPECT_EQ(FromChooseExpr->isConditionDependent(), 1218 ToChooseExpr->isConditionDependent()); 1219 } 1220 1221 TEST_P(ASTImporterOptionSpecificTestBase, ImportGenericSelectionExpr) { 1222 Decl *From, *To; 1223 std::tie(From, To) = getImportedDecl( 1224 R"( 1225 int declToImport() { 1226 int x; 1227 return _Generic(x, int: 0, default: 1); 1228 } 1229 )", 1230 Lang_C99, "", Lang_C99); 1231 1232 auto ToResults = 1233 match(genericSelectionExpr().bind("expr"), To->getASTContext()); 1234 auto FromResults = 1235 match(genericSelectionExpr().bind("expr"), From->getASTContext()); 1236 1237 const GenericSelectionExpr *FromGenericSelectionExpr = 1238 selectFirst<GenericSelectionExpr>("expr", FromResults); 1239 ASSERT_TRUE(FromGenericSelectionExpr); 1240 1241 const GenericSelectionExpr *ToGenericSelectionExpr = 1242 selectFirst<GenericSelectionExpr>("expr", ToResults); 1243 ASSERT_TRUE(ToGenericSelectionExpr); 1244 1245 EXPECT_EQ(FromGenericSelectionExpr->isResultDependent(), 1246 ToGenericSelectionExpr->isResultDependent()); 1247 EXPECT_EQ(FromGenericSelectionExpr->getResultIndex(), 1248 ToGenericSelectionExpr->getResultIndex()); 1249 } 1250 1251 TEST_P(ASTImporterOptionSpecificTestBase, 1252 ImportFunctionWithBackReferringParameter) { 1253 Decl *From, *To; 1254 std::tie(From, To) = getImportedDecl( 1255 R"( 1256 template <typename T> struct X {}; 1257 1258 void declToImport(int y, X<int> &x) {} 1259 1260 template <> struct X<int> { 1261 void g() { 1262 X<int> x; 1263 declToImport(0, x); 1264 } 1265 }; 1266 )", 1267 Lang_CXX03, "", Lang_CXX03); 1268 1269 MatchVerifier<Decl> Verifier; 1270 auto Matcher = functionDecl(hasName("declToImport"), 1271 parameterCountIs(2), 1272 hasParameter(0, hasName("y")), 1273 hasParameter(1, hasName("x")), 1274 hasParameter(1, hasType(asString("X<int> &")))); 1275 ASSERT_TRUE(Verifier.match(From, Matcher)); 1276 EXPECT_TRUE(Verifier.match(To, Matcher)); 1277 } 1278 1279 TEST_P(ASTImporterOptionSpecificTestBase, 1280 TUshouldNotContainTemplatedDeclOfFunctionTemplates) { 1281 Decl *From, *To; 1282 std::tie(From, To) = 1283 getImportedDecl("template <typename T> void declToImport() { T a = 1; }" 1284 "void instantiate() { declToImport<int>(); }", 1285 Lang_CXX03, "", Lang_CXX03); 1286 1287 auto Check = [](Decl *D) -> bool { 1288 auto TU = D->getTranslationUnitDecl(); 1289 for (auto Child : TU->decls()) { 1290 if (auto *FD = dyn_cast<FunctionDecl>(Child)) { 1291 if (FD->getNameAsString() == "declToImport") { 1292 GTEST_NONFATAL_FAILURE_( 1293 "TU should not contain any FunctionDecl with name declToImport"); 1294 return false; 1295 } 1296 } 1297 } 1298 return true; 1299 }; 1300 1301 ASSERT_TRUE(Check(From)); 1302 EXPECT_TRUE(Check(To)); 1303 } 1304 1305 TEST_P(ASTImporterOptionSpecificTestBase, 1306 TUshouldNotContainTemplatedDeclOfClassTemplates) { 1307 Decl *From, *To; 1308 std::tie(From, To) = 1309 getImportedDecl("template <typename T> struct declToImport { T t; };" 1310 "void instantiate() { declToImport<int>(); }", 1311 Lang_CXX03, "", Lang_CXX03); 1312 1313 auto Check = [](Decl *D) -> bool { 1314 auto TU = D->getTranslationUnitDecl(); 1315 for (auto Child : TU->decls()) { 1316 if (auto *RD = dyn_cast<CXXRecordDecl>(Child)) { 1317 if (RD->getNameAsString() == "declToImport") { 1318 GTEST_NONFATAL_FAILURE_( 1319 "TU should not contain any CXXRecordDecl with name declToImport"); 1320 return false; 1321 } 1322 } 1323 } 1324 return true; 1325 }; 1326 1327 ASSERT_TRUE(Check(From)); 1328 EXPECT_TRUE(Check(To)); 1329 } 1330 1331 TEST_P(ASTImporterOptionSpecificTestBase, 1332 TUshouldNotContainTemplatedDeclOfTypeAlias) { 1333 Decl *From, *To; 1334 std::tie(From, To) = 1335 getImportedDecl( 1336 "template <typename T> struct X {};" 1337 "template <typename T> using declToImport = X<T>;" 1338 "void instantiate() { declToImport<int> a; }", 1339 Lang_CXX11, "", Lang_CXX11); 1340 1341 auto Check = [](Decl *D) -> bool { 1342 auto TU = D->getTranslationUnitDecl(); 1343 for (auto Child : TU->decls()) { 1344 if (auto *AD = dyn_cast<TypeAliasDecl>(Child)) { 1345 if (AD->getNameAsString() == "declToImport") { 1346 GTEST_NONFATAL_FAILURE_( 1347 "TU should not contain any TypeAliasDecl with name declToImport"); 1348 return false; 1349 } 1350 } 1351 } 1352 return true; 1353 }; 1354 1355 ASSERT_TRUE(Check(From)); 1356 EXPECT_TRUE(Check(To)); 1357 } 1358 1359 TEST_P(ASTImporterOptionSpecificTestBase, 1360 TUshouldNotContainClassTemplateSpecializationOfImplicitInstantiation) { 1361 1362 Decl *From, *To; 1363 std::tie(From, To) = getImportedDecl( 1364 R"( 1365 template<class T> 1366 class Base {}; 1367 class declToImport : public Base<declToImport> {}; 1368 )", 1369 Lang_CXX03, "", Lang_CXX03); 1370 1371 // Check that the ClassTemplateSpecializationDecl is NOT the child of the TU. 1372 auto Pattern = 1373 translationUnitDecl(unless(has(classTemplateSpecializationDecl()))); 1374 ASSERT_TRUE( 1375 MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern)); 1376 EXPECT_TRUE( 1377 MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern)); 1378 1379 // Check that the ClassTemplateSpecializationDecl is the child of the 1380 // ClassTemplateDecl. 1381 Pattern = translationUnitDecl(has(classTemplateDecl( 1382 hasName("Base"), has(classTemplateSpecializationDecl())))); 1383 ASSERT_TRUE( 1384 MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern)); 1385 EXPECT_TRUE( 1386 MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern)); 1387 } 1388 1389 AST_MATCHER_P(RecordDecl, hasFieldOrder, std::vector<StringRef>, Order) { 1390 size_t Index = 0; 1391 for (Decl *D : Node.decls()) { 1392 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) { 1393 auto *ND = cast<NamedDecl>(D); 1394 if (Index == Order.size()) 1395 return false; 1396 if (ND->getName() != Order[Index]) 1397 return false; 1398 ++Index; 1399 } 1400 } 1401 return Index == Order.size(); 1402 } 1403 1404 TEST_P(ASTImporterOptionSpecificTestBase, 1405 TUshouldContainClassTemplateSpecializationOfExplicitInstantiation) { 1406 Decl *From, *To; 1407 std::tie(From, To) = getImportedDecl( 1408 R"( 1409 namespace NS { 1410 template<class T> 1411 class X {}; 1412 template class X<int>; 1413 } 1414 )", 1415 Lang_CXX03, "", Lang_CXX03, "NS"); 1416 1417 // Check that the ClassTemplateSpecializationDecl is NOT the child of the 1418 // ClassTemplateDecl. 1419 auto Pattern = namespaceDecl(has(classTemplateDecl( 1420 hasName("X"), unless(has(classTemplateSpecializationDecl()))))); 1421 ASSERT_TRUE(MatchVerifier<Decl>{}.match(From, Pattern)); 1422 EXPECT_TRUE(MatchVerifier<Decl>{}.match(To, Pattern)); 1423 1424 // Check that the ClassTemplateSpecializationDecl is the child of the 1425 // NamespaceDecl. 1426 Pattern = namespaceDecl(has(classTemplateSpecializationDecl(hasName("X")))); 1427 ASSERT_TRUE(MatchVerifier<Decl>{}.match(From, Pattern)); 1428 EXPECT_TRUE(MatchVerifier<Decl>{}.match(To, Pattern)); 1429 } 1430 1431 TEST_P(ASTImporterOptionSpecificTestBase, 1432 CXXRecordDeclFieldsShouldBeInCorrectOrder) { 1433 Decl *From, *To; 1434 std::tie(From, To) = 1435 getImportedDecl( 1436 "struct declToImport { int a; int b; };", 1437 Lang_CXX11, "", Lang_CXX11); 1438 1439 MatchVerifier<Decl> Verifier; 1440 ASSERT_TRUE(Verifier.match(From, cxxRecordDecl(hasFieldOrder({"a", "b"})))); 1441 EXPECT_TRUE(Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b"})))); 1442 } 1443 1444 TEST_P(ASTImporterOptionSpecificTestBase, 1445 CXXRecordDeclFieldOrderShouldNotDependOnImportOrder) { 1446 Decl *From, *To; 1447 std::tie(From, To) = getImportedDecl( 1448 // The original recursive algorithm of ASTImporter first imports 'c' then 1449 // 'b' and lastly 'a'. Therefore we must restore the order somehow. 1450 R"s( 1451 struct declToImport { 1452 int a = c + b; 1453 int b = 1; 1454 int c = 2; 1455 }; 1456 )s", 1457 Lang_CXX11, "", Lang_CXX11); 1458 1459 MatchVerifier<Decl> Verifier; 1460 ASSERT_TRUE( 1461 Verifier.match(From, cxxRecordDecl(hasFieldOrder({"a", "b", "c"})))); 1462 EXPECT_TRUE( 1463 Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b", "c"})))); 1464 } 1465 1466 TEST_P(ASTImporterOptionSpecificTestBase, 1467 CXXRecordDeclFieldAndIndirectFieldOrder) { 1468 Decl *From, *To; 1469 std::tie(From, To) = getImportedDecl( 1470 // First field is "a", then the field for unnamed union, then "b" and "c" 1471 // from it (indirect fields), then "d". 1472 R"s( 1473 struct declToImport { 1474 int a = d; 1475 union { 1476 int b; 1477 int c; 1478 }; 1479 int d; 1480 }; 1481 )s", 1482 Lang_CXX11, "", Lang_CXX11); 1483 1484 MatchVerifier<Decl> Verifier; 1485 ASSERT_TRUE(Verifier.match( 1486 From, cxxRecordDecl(hasFieldOrder({"a", "", "b", "c", "d"})))); 1487 EXPECT_TRUE(Verifier.match( 1488 To, cxxRecordDecl(hasFieldOrder({"a", "", "b", "c", "d"})))); 1489 } 1490 1491 TEST_P(ASTImporterOptionSpecificTestBase, ShouldImportImplicitCXXRecordDecl) { 1492 Decl *From, *To; 1493 std::tie(From, To) = getImportedDecl( 1494 R"( 1495 struct declToImport { 1496 }; 1497 )", 1498 Lang_CXX03, "", Lang_CXX03); 1499 1500 MatchVerifier<Decl> Verifier; 1501 // Match the implicit Decl. 1502 auto Matcher = cxxRecordDecl(has(cxxRecordDecl())); 1503 ASSERT_TRUE(Verifier.match(From, Matcher)); 1504 EXPECT_TRUE(Verifier.match(To, Matcher)); 1505 } 1506 1507 TEST_P(ASTImporterOptionSpecificTestBase, 1508 ShouldImportImplicitCXXRecordDeclOfClassTemplate) { 1509 Decl *From, *To; 1510 std::tie(From, To) = getImportedDecl( 1511 R"( 1512 template <typename U> 1513 struct declToImport { 1514 }; 1515 )", 1516 Lang_CXX03, "", Lang_CXX03); 1517 1518 MatchVerifier<Decl> Verifier; 1519 // Match the implicit Decl. 1520 auto Matcher = classTemplateDecl(has(cxxRecordDecl(has(cxxRecordDecl())))); 1521 ASSERT_TRUE(Verifier.match(From, Matcher)); 1522 EXPECT_TRUE(Verifier.match(To, Matcher)); 1523 } 1524 1525 TEST_P(ASTImporterOptionSpecificTestBase, 1526 ShouldImportImplicitCXXRecordDeclOfClassTemplateSpecializationDecl) { 1527 Decl *From, *To; 1528 std::tie(From, To) = getImportedDecl( 1529 R"( 1530 template<class T> 1531 class Base {}; 1532 class declToImport : public Base<declToImport> {}; 1533 )", 1534 Lang_CXX03, "", Lang_CXX03); 1535 1536 auto hasImplicitClass = has(cxxRecordDecl()); 1537 auto Pattern = translationUnitDecl(has(classTemplateDecl( 1538 hasName("Base"), 1539 has(classTemplateSpecializationDecl(hasImplicitClass))))); 1540 ASSERT_TRUE( 1541 MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern)); 1542 EXPECT_TRUE( 1543 MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern)); 1544 } 1545 1546 TEST_P(ASTImporterOptionSpecificTestBase, IDNSOrdinary) { 1547 Decl *From, *To; 1548 std::tie(From, To) = 1549 getImportedDecl("void declToImport() {}", Lang_CXX03, "", Lang_CXX03); 1550 1551 MatchVerifier<Decl> Verifier; 1552 auto Matcher = functionDecl(); 1553 ASSERT_TRUE(Verifier.match(From, Matcher)); 1554 EXPECT_TRUE(Verifier.match(To, Matcher)); 1555 EXPECT_EQ(From->getIdentifierNamespace(), To->getIdentifierNamespace()); 1556 } 1557 1558 TEST_P(ASTImporterOptionSpecificTestBase, IDNSOfNonmemberOperator) { 1559 Decl *FromTU = getTuDecl( 1560 R"( 1561 struct X {}; 1562 void operator<<(int, X); 1563 )", 1564 Lang_CXX03); 1565 Decl *From = LastDeclMatcher<Decl>{}.match(FromTU, functionDecl()); 1566 const Decl *To = Import(From, Lang_CXX03); 1567 EXPECT_EQ(From->getIdentifierNamespace(), To->getIdentifierNamespace()); 1568 } 1569 1570 TEST_P(ASTImporterOptionSpecificTestBase, 1571 ShouldImportMembersOfClassTemplateSpecializationDecl) { 1572 Decl *From, *To; 1573 std::tie(From, To) = getImportedDecl( 1574 R"( 1575 template<class T> 1576 class Base { int a; }; 1577 class declToImport : Base<declToImport> {}; 1578 )", 1579 Lang_CXX03, "", Lang_CXX03); 1580 1581 auto Pattern = translationUnitDecl(has(classTemplateDecl( 1582 hasName("Base"), 1583 has(classTemplateSpecializationDecl(has(fieldDecl(hasName("a")))))))); 1584 ASSERT_TRUE( 1585 MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern)); 1586 EXPECT_TRUE( 1587 MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern)); 1588 } 1589 1590 TEST_P(ASTImporterOptionSpecificTestBase, 1591 ImportDefinitionOfClassTemplateAfterFwdDecl) { 1592 { 1593 Decl *FromTU = getTuDecl( 1594 R"( 1595 template <typename T> 1596 struct B; 1597 )", 1598 Lang_CXX03, "input0.cc"); 1599 auto *FromD = FirstDeclMatcher<ClassTemplateDecl>().match( 1600 FromTU, classTemplateDecl(hasName("B"))); 1601 1602 Import(FromD, Lang_CXX03); 1603 } 1604 1605 { 1606 Decl *FromTU = getTuDecl( 1607 R"( 1608 template <typename T> 1609 struct B { 1610 void f(); 1611 }; 1612 )", 1613 Lang_CXX03, "input1.cc"); 1614 FunctionDecl *FromD = FirstDeclMatcher<FunctionDecl>().match( 1615 FromTU, functionDecl(hasName("f"))); 1616 Import(FromD, Lang_CXX03); 1617 auto *FromCTD = FirstDeclMatcher<ClassTemplateDecl>().match( 1618 FromTU, classTemplateDecl(hasName("B"))); 1619 auto *ToCTD = cast<ClassTemplateDecl>(Import(FromCTD, Lang_CXX03)); 1620 EXPECT_TRUE(ToCTD->isThisDeclarationADefinition()); 1621 } 1622 } 1623 1624 TEST_P(ASTImporterOptionSpecificTestBase, 1625 ImportDefinitionOfClassTemplateIfThereIsAnExistingFwdDeclAndDefinition) { 1626 Decl *ToTU = getToTuDecl( 1627 R"( 1628 template <typename T> 1629 struct B { 1630 void f(); 1631 }; 1632 1633 template <typename T> 1634 struct B; 1635 )", 1636 Lang_CXX03); 1637 ASSERT_EQ(1u, DeclCounterWithPredicate<ClassTemplateDecl>( 1638 [](const ClassTemplateDecl *T) { 1639 return T->isThisDeclarationADefinition(); 1640 }) 1641 .match(ToTU, classTemplateDecl())); 1642 1643 Decl *FromTU = getTuDecl( 1644 R"( 1645 template <typename T> 1646 struct B { 1647 void f(); 1648 }; 1649 )", 1650 Lang_CXX03, "input1.cc"); 1651 ClassTemplateDecl *FromD = FirstDeclMatcher<ClassTemplateDecl>().match( 1652 FromTU, classTemplateDecl(hasName("B"))); 1653 1654 Import(FromD, Lang_CXX03); 1655 1656 // We should have only one definition. 1657 EXPECT_EQ(1u, DeclCounterWithPredicate<ClassTemplateDecl>( 1658 [](const ClassTemplateDecl *T) { 1659 return T->isThisDeclarationADefinition(); 1660 }) 1661 .match(ToTU, classTemplateDecl())); 1662 } 1663 1664 TEST_P(ASTImporterOptionSpecificTestBase, 1665 ImportDefinitionOfClassIfThereIsAnExistingFwdDeclAndDefinition) { 1666 Decl *ToTU = getToTuDecl( 1667 R"( 1668 struct B { 1669 void f(); 1670 }; 1671 1672 struct B; 1673 )", 1674 Lang_CXX03); 1675 ASSERT_EQ(2u, DeclCounter<CXXRecordDecl>().match( 1676 ToTU, cxxRecordDecl(unless(isImplicit())))); 1677 1678 Decl *FromTU = getTuDecl( 1679 R"( 1680 struct B { 1681 void f(); 1682 }; 1683 )", 1684 Lang_CXX03, "input1.cc"); 1685 auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match( 1686 FromTU, cxxRecordDecl(hasName("B"))); 1687 1688 Import(FromD, Lang_CXX03); 1689 1690 EXPECT_EQ(2u, DeclCounter<CXXRecordDecl>().match( 1691 ToTU, cxxRecordDecl(unless(isImplicit())))); 1692 } 1693 1694 static void CompareSourceLocs(FullSourceLoc Loc1, FullSourceLoc Loc2) { 1695 EXPECT_EQ(Loc1.getExpansionLineNumber(), Loc2.getExpansionLineNumber()); 1696 EXPECT_EQ(Loc1.getExpansionColumnNumber(), Loc2.getExpansionColumnNumber()); 1697 EXPECT_EQ(Loc1.getSpellingLineNumber(), Loc2.getSpellingLineNumber()); 1698 EXPECT_EQ(Loc1.getSpellingColumnNumber(), Loc2.getSpellingColumnNumber()); 1699 } 1700 static void CompareSourceRanges(SourceRange Range1, SourceRange Range2, 1701 SourceManager &SM1, SourceManager &SM2) { 1702 CompareSourceLocs(FullSourceLoc{ Range1.getBegin(), SM1 }, 1703 FullSourceLoc{ Range2.getBegin(), SM2 }); 1704 CompareSourceLocs(FullSourceLoc{ Range1.getEnd(), SM1 }, 1705 FullSourceLoc{ Range2.getEnd(), SM2 }); 1706 } 1707 TEST_P(ASTImporterOptionSpecificTestBase, ImportSourceLocs) { 1708 Decl *FromTU = getTuDecl( 1709 R"( 1710 #define MFOO(arg) arg = arg + 1 1711 1712 void foo() { 1713 int a = 5; 1714 MFOO(a); 1715 } 1716 )", 1717 Lang_CXX03); 1718 auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 1719 auto ToD = Import(FromD, Lang_CXX03); 1720 1721 auto ToLHS = LastDeclMatcher<DeclRefExpr>().match(ToD, declRefExpr()); 1722 auto FromLHS = LastDeclMatcher<DeclRefExpr>().match(FromTU, declRefExpr()); 1723 auto ToRHS = LastDeclMatcher<IntegerLiteral>().match(ToD, integerLiteral()); 1724 auto FromRHS = 1725 LastDeclMatcher<IntegerLiteral>().match(FromTU, integerLiteral()); 1726 1727 SourceManager &ToSM = ToAST->getASTContext().getSourceManager(); 1728 SourceManager &FromSM = FromD->getASTContext().getSourceManager(); 1729 CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM, 1730 FromSM); 1731 CompareSourceRanges(ToLHS->getSourceRange(), FromLHS->getSourceRange(), ToSM, 1732 FromSM); 1733 CompareSourceRanges(ToRHS->getSourceRange(), FromRHS->getSourceRange(), ToSM, 1734 FromSM); 1735 } 1736 1737 TEST_P(ASTImporterOptionSpecificTestBase, ImportNestedMacro) { 1738 Decl *FromTU = getTuDecl( 1739 R"( 1740 #define FUNC_INT void declToImport 1741 #define FUNC FUNC_INT 1742 FUNC(int a); 1743 )", 1744 Lang_CXX03); 1745 auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 1746 auto ToD = Import(FromD, Lang_CXX03); 1747 1748 SourceManager &ToSM = ToAST->getASTContext().getSourceManager(); 1749 SourceManager &FromSM = FromD->getASTContext().getSourceManager(); 1750 CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM, 1751 FromSM); 1752 } 1753 1754 TEST_P( 1755 ASTImporterOptionSpecificTestBase, 1756 ImportDefinitionOfClassTemplateSpecIfThereIsAnExistingFwdDeclAndDefinition) { 1757 Decl *ToTU = getToTuDecl( 1758 R"( 1759 template <typename T> 1760 struct B; 1761 1762 template <> 1763 struct B<int> {}; 1764 1765 template <> 1766 struct B<int>; 1767 )", 1768 Lang_CXX03); 1769 // We should have only one definition. 1770 ASSERT_EQ(1u, DeclCounterWithPredicate<ClassTemplateSpecializationDecl>( 1771 [](const ClassTemplateSpecializationDecl *T) { 1772 return T->isThisDeclarationADefinition(); 1773 }) 1774 .match(ToTU, classTemplateSpecializationDecl())); 1775 1776 Decl *FromTU = getTuDecl( 1777 R"( 1778 template <typename T> 1779 struct B; 1780 1781 template <> 1782 struct B<int> {}; 1783 )", 1784 Lang_CXX03, "input1.cc"); 1785 auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 1786 FromTU, classTemplateSpecializationDecl(hasName("B"))); 1787 1788 Import(FromD, Lang_CXX03); 1789 1790 // We should have only one definition. 1791 EXPECT_EQ(1u, DeclCounterWithPredicate<ClassTemplateSpecializationDecl>( 1792 [](const ClassTemplateSpecializationDecl *T) { 1793 return T->isThisDeclarationADefinition(); 1794 }) 1795 .match(ToTU, classTemplateSpecializationDecl())); 1796 } 1797 1798 TEST_P(ASTImporterOptionSpecificTestBase, ObjectsWithUnnamedStructType) { 1799 Decl *FromTU = getTuDecl( 1800 R"( 1801 struct { int a; int b; } object0 = { 2, 3 }; 1802 struct { int x; int y; int z; } object1; 1803 )", 1804 Lang_CXX03, "input0.cc"); 1805 1806 auto *Obj0 = 1807 FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("object0"))); 1808 auto *From0 = getRecordDecl(Obj0); 1809 auto *Obj1 = 1810 FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("object1"))); 1811 auto *From1 = getRecordDecl(Obj1); 1812 1813 auto *To0 = Import(From0, Lang_CXX03); 1814 auto *To1 = Import(From1, Lang_CXX03); 1815 1816 EXPECT_TRUE(To0); 1817 EXPECT_TRUE(To1); 1818 EXPECT_NE(To0, To1); 1819 EXPECT_NE(To0->getCanonicalDecl(), To1->getCanonicalDecl()); 1820 } 1821 1822 TEST_P(ASTImporterOptionSpecificTestBase, AnonymousRecords) { 1823 auto *Code = 1824 R"( 1825 struct X { 1826 struct { int a; }; 1827 struct { int b; }; 1828 }; 1829 )"; 1830 Decl *FromTU0 = getTuDecl(Code, Lang_C99, "input0.c"); 1831 1832 Decl *FromTU1 = getTuDecl(Code, Lang_C99, "input1.c"); 1833 1834 auto *X0 = 1835 FirstDeclMatcher<RecordDecl>().match(FromTU0, recordDecl(hasName("X"))); 1836 auto *X1 = 1837 FirstDeclMatcher<RecordDecl>().match(FromTU1, recordDecl(hasName("X"))); 1838 Import(X0, Lang_C99); 1839 Import(X1, Lang_C99); 1840 1841 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 1842 // We expect no (ODR) warning during the import. 1843 EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings()); 1844 EXPECT_EQ(1u, 1845 DeclCounter<RecordDecl>().match(ToTU, recordDecl(hasName("X")))); 1846 } 1847 1848 TEST_P(ASTImporterOptionSpecificTestBase, AnonymousRecordsReversed) { 1849 Decl *FromTU0 = getTuDecl( 1850 R"( 1851 struct X { 1852 struct { int a; }; 1853 struct { int b; }; 1854 }; 1855 )", 1856 Lang_C99, "input0.c"); 1857 1858 Decl *FromTU1 = getTuDecl( 1859 R"( 1860 struct X { // reversed order 1861 struct { int b; }; 1862 struct { int a; }; 1863 }; 1864 )", 1865 Lang_C99, "input1.c"); 1866 1867 auto *X0 = 1868 FirstDeclMatcher<RecordDecl>().match(FromTU0, recordDecl(hasName("X"))); 1869 auto *X1 = 1870 FirstDeclMatcher<RecordDecl>().match(FromTU1, recordDecl(hasName("X"))); 1871 Import(X0, Lang_C99); 1872 Import(X1, Lang_C99); 1873 1874 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 1875 // We expect one (ODR) warning during the import. 1876 EXPECT_EQ(1u, ToTU->getASTContext().getDiagnostics().getNumWarnings()); 1877 EXPECT_EQ(1u, 1878 DeclCounter<RecordDecl>().match(ToTU, recordDecl(hasName("X")))); 1879 } 1880 1881 TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag) { 1882 auto Pattern = varDecl(hasName("x")); 1883 VarDecl *Imported1; 1884 { 1885 Decl *FromTU = getTuDecl("extern int x;", Lang_CXX03, "input0.cc"); 1886 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 1887 Imported1 = cast<VarDecl>(Import(FromD, Lang_CXX03)); 1888 } 1889 VarDecl *Imported2; 1890 { 1891 Decl *FromTU = getTuDecl("int x;", Lang_CXX03, "input1.cc"); 1892 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 1893 Imported2 = cast<VarDecl>(Import(FromD, Lang_CXX03)); 1894 } 1895 EXPECT_EQ(Imported1->getCanonicalDecl(), Imported2->getCanonicalDecl()); 1896 EXPECT_FALSE(Imported2->isUsed(false)); 1897 { 1898 Decl *FromTU = getTuDecl("extern int x; int f() { return x; }", Lang_CXX03, 1899 "input2.cc"); 1900 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 1901 FromTU, functionDecl(hasName("f"))); 1902 Import(FromD, Lang_CXX03); 1903 } 1904 EXPECT_TRUE(Imported2->isUsed(false)); 1905 } 1906 1907 TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag2) { 1908 auto Pattern = varDecl(hasName("x")); 1909 VarDecl *ExistingD; 1910 { 1911 Decl *ToTU = getToTuDecl("int x = 1;", Lang_CXX03); 1912 ExistingD = FirstDeclMatcher<VarDecl>().match(ToTU, Pattern); 1913 } 1914 EXPECT_FALSE(ExistingD->isUsed(false)); 1915 { 1916 Decl *FromTU = 1917 getTuDecl("int x = 1; int f() { return x; }", Lang_CXX03, "input1.cc"); 1918 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 1919 FromTU, functionDecl(hasName("f"))); 1920 Import(FromD, Lang_CXX03); 1921 } 1922 EXPECT_TRUE(ExistingD->isUsed(false)); 1923 } 1924 1925 TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag3) { 1926 auto Pattern = varDecl(hasName("a")); 1927 VarDecl *ExistingD; 1928 { 1929 Decl *ToTU = getToTuDecl( 1930 R"( 1931 struct A { 1932 static const int a = 1; 1933 }; 1934 )", 1935 Lang_CXX03); 1936 ExistingD = FirstDeclMatcher<VarDecl>().match(ToTU, Pattern); 1937 } 1938 EXPECT_FALSE(ExistingD->isUsed(false)); 1939 { 1940 Decl *FromTU = getTuDecl( 1941 R"( 1942 struct A { 1943 static const int a = 1; 1944 }; 1945 const int *f() { return &A::a; } // requires storage, 1946 // thus used flag will be set 1947 )", 1948 Lang_CXX03, "input1.cc"); 1949 auto *FromFunD = FirstDeclMatcher<FunctionDecl>().match( 1950 FromTU, functionDecl(hasName("f"))); 1951 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 1952 ASSERT_TRUE(FromD->isUsed(false)); 1953 Import(FromFunD, Lang_CXX03); 1954 } 1955 EXPECT_TRUE(ExistingD->isUsed(false)); 1956 } 1957 1958 TEST_P(ASTImporterOptionSpecificTestBase, ReimportWithUsedFlag) { 1959 auto Pattern = varDecl(hasName("x")); 1960 1961 Decl *FromTU = getTuDecl("int x;", Lang_CXX03, "input0.cc"); 1962 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 1963 1964 auto *Imported1 = cast<VarDecl>(Import(FromD, Lang_CXX03)); 1965 1966 ASSERT_FALSE(Imported1->isUsed(false)); 1967 1968 FromD->setIsUsed(); 1969 auto *Imported2 = cast<VarDecl>(Import(FromD, Lang_CXX03)); 1970 1971 EXPECT_EQ(Imported1, Imported2); 1972 EXPECT_TRUE(Imported2->isUsed(false)); 1973 } 1974 1975 struct ImportFunctions : ASTImporterOptionSpecificTestBase {}; 1976 1977 TEST_P(ImportFunctions, ImportPrototypeOfRecursiveFunction) { 1978 Decl *FromTU = getTuDecl("void f(); void f() { f(); }", Lang_CXX03); 1979 auto Pattern = functionDecl(hasName("f")); 1980 auto *From = 1981 FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); // Proto 1982 1983 Decl *ImportedD = Import(From, Lang_CXX03); 1984 Decl *ToTU = ImportedD->getTranslationUnitDecl(); 1985 1986 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 1987 auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 1988 auto *To1 = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 1989 EXPECT_TRUE(ImportedD == To0); 1990 EXPECT_FALSE(To0->doesThisDeclarationHaveABody()); 1991 EXPECT_TRUE(To1->doesThisDeclarationHaveABody()); 1992 EXPECT_EQ(To1->getPreviousDecl(), To0); 1993 } 1994 1995 TEST_P(ImportFunctions, ImportDefinitionOfRecursiveFunction) { 1996 Decl *FromTU = getTuDecl("void f(); void f() { f(); }", Lang_CXX03); 1997 auto Pattern = functionDecl(hasName("f")); 1998 auto *From = 1999 LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); // Def 2000 2001 Decl *ImportedD = Import(From, Lang_CXX03); 2002 Decl *ToTU = ImportedD->getTranslationUnitDecl(); 2003 2004 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2005 auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2006 auto *To1 = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2007 EXPECT_TRUE(ImportedD == To1); 2008 EXPECT_FALSE(To0->doesThisDeclarationHaveABody()); 2009 EXPECT_TRUE(To1->doesThisDeclarationHaveABody()); 2010 EXPECT_EQ(To1->getPreviousDecl(), To0); 2011 } 2012 2013 TEST_P(ImportFunctions, OverriddenMethodsShouldBeImported) { 2014 auto Code = 2015 R"( 2016 struct B { virtual void f(); }; 2017 void B::f() {} 2018 struct D : B { void f(); }; 2019 )"; 2020 auto Pattern = 2021 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D")))); 2022 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 2023 CXXMethodDecl *Proto = 2024 FirstDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern); 2025 2026 ASSERT_EQ(Proto->size_overridden_methods(), 1u); 2027 CXXMethodDecl *To = cast<CXXMethodDecl>(Import(Proto, Lang_CXX03)); 2028 EXPECT_EQ(To->size_overridden_methods(), 1u); 2029 } 2030 2031 TEST_P(ImportFunctions, VirtualFlagShouldBePreservedWhenImportingPrototype) { 2032 auto Code = 2033 R"( 2034 struct B { virtual void f(); }; 2035 void B::f() {} 2036 )"; 2037 auto Pattern = 2038 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B")))); 2039 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 2040 CXXMethodDecl *Proto = 2041 FirstDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern); 2042 CXXMethodDecl *Def = LastDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern); 2043 2044 ASSERT_TRUE(Proto->isVirtual()); 2045 ASSERT_TRUE(Def->isVirtual()); 2046 CXXMethodDecl *To = cast<CXXMethodDecl>(Import(Proto, Lang_CXX03)); 2047 EXPECT_TRUE(To->isVirtual()); 2048 } 2049 2050 TEST_P(ImportFunctions, 2051 ImportDefinitionIfThereIsAnExistingDefinitionAndFwdDecl) { 2052 Decl *ToTU = getToTuDecl( 2053 R"( 2054 void f() {} 2055 void f(); 2056 )", 2057 Lang_CXX03); 2058 ASSERT_EQ(1u, 2059 DeclCounterWithPredicate<FunctionDecl>([](const FunctionDecl *FD) { 2060 return FD->doesThisDeclarationHaveABody(); 2061 }).match(ToTU, functionDecl())); 2062 2063 Decl *FromTU = getTuDecl("void f() {}", Lang_CXX03, "input0.cc"); 2064 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 2065 2066 Import(FromD, Lang_CXX03); 2067 2068 EXPECT_EQ(1u, 2069 DeclCounterWithPredicate<FunctionDecl>([](const FunctionDecl *FD) { 2070 return FD->doesThisDeclarationHaveABody(); 2071 }).match(ToTU, functionDecl())); 2072 } 2073 2074 TEST_P(ImportFunctions, ImportOverriddenMethodTwice) { 2075 auto Code = 2076 R"( 2077 struct B { virtual void f(); }; 2078 struct D:B { void f(); }; 2079 )"; 2080 auto BFP = 2081 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B")))); 2082 auto DFP = 2083 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D")))); 2084 2085 Decl *FromTU0 = getTuDecl(Code, Lang_CXX03); 2086 auto *DF = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP); 2087 Import(DF, Lang_CXX03); 2088 2089 Decl *FromTU1 = getTuDecl(Code, Lang_CXX03, "input1.cc"); 2090 auto *BF = FirstDeclMatcher<CXXMethodDecl>().match(FromTU1, BFP); 2091 Import(BF, Lang_CXX03); 2092 2093 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2094 2095 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u); 2096 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u); 2097 } 2098 2099 TEST_P(ImportFunctions, ImportOverriddenMethodTwiceDefinitionFirst) { 2100 auto CodeWithoutDef = 2101 R"( 2102 struct B { virtual void f(); }; 2103 struct D:B { void f(); }; 2104 )"; 2105 auto CodeWithDef = 2106 R"( 2107 struct B { virtual void f(){}; }; 2108 struct D:B { void f(){}; }; 2109 )"; 2110 auto BFP = 2111 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B")))); 2112 auto DFP = 2113 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D")))); 2114 auto BFDefP = cxxMethodDecl( 2115 hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition()); 2116 auto DFDefP = cxxMethodDecl( 2117 hasName("f"), hasParent(cxxRecordDecl(hasName("D"))), isDefinition()); 2118 auto FDefAllP = cxxMethodDecl(hasName("f"), isDefinition()); 2119 2120 { 2121 Decl *FromTU = getTuDecl(CodeWithDef, Lang_CXX03, "input0.cc"); 2122 auto *FromD = FirstDeclMatcher<CXXMethodDecl>().match(FromTU, DFP); 2123 Import(FromD, Lang_CXX03); 2124 } 2125 { 2126 Decl *FromTU = getTuDecl(CodeWithoutDef, Lang_CXX03, "input1.cc"); 2127 auto *FromB = FirstDeclMatcher<CXXMethodDecl>().match(FromTU, BFP); 2128 Import(FromB, Lang_CXX03); 2129 } 2130 2131 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2132 2133 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u); 2134 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u); 2135 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 1u); 2136 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFDefP), 1u); 2137 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FDefAllP), 2u); 2138 } 2139 2140 TEST_P(ImportFunctions, ImportOverriddenMethodTwiceOutOfClassDef) { 2141 auto Code = 2142 R"( 2143 struct B { virtual void f(); }; 2144 struct D:B { void f(); }; 2145 void B::f(){}; 2146 )"; 2147 2148 auto BFP = 2149 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B")))); 2150 auto BFDefP = cxxMethodDecl( 2151 hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition()); 2152 auto DFP = cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))), 2153 unless(isDefinition())); 2154 2155 Decl *FromTU0 = getTuDecl(Code, Lang_CXX03); 2156 auto *D = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP); 2157 Import(D, Lang_CXX03); 2158 2159 Decl *FromTU1 = getTuDecl(Code, Lang_CXX03, "input1.cc"); 2160 auto *B = FirstDeclMatcher<CXXMethodDecl>().match(FromTU1, BFP); 2161 Import(B, Lang_CXX03); 2162 2163 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2164 2165 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u); 2166 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 0u); 2167 2168 auto *ToB = FirstDeclMatcher<CXXRecordDecl>().match( 2169 ToTU, cxxRecordDecl(hasName("B"))); 2170 auto *ToBFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, BFP); 2171 auto *ToBFOutOfClass = FirstDeclMatcher<CXXMethodDecl>().match( 2172 ToTU, cxxMethodDecl(hasName("f"), isDefinition())); 2173 2174 // The definition should be out-of-class. 2175 EXPECT_NE(ToBFInClass, ToBFOutOfClass); 2176 EXPECT_NE(ToBFInClass->getLexicalDeclContext(), 2177 ToBFOutOfClass->getLexicalDeclContext()); 2178 EXPECT_EQ(ToBFOutOfClass->getDeclContext(), ToB); 2179 EXPECT_EQ(ToBFOutOfClass->getLexicalDeclContext(), ToTU); 2180 2181 // Check that the redecl chain is intact. 2182 EXPECT_EQ(ToBFOutOfClass->getPreviousDecl(), ToBFInClass); 2183 } 2184 2185 TEST_P(ImportFunctions, 2186 ImportOverriddenMethodTwiceOutOfClassDefInSeparateCode) { 2187 auto CodeTU0 = 2188 R"( 2189 struct B { virtual void f(); }; 2190 struct D:B { void f(); }; 2191 )"; 2192 auto CodeTU1 = 2193 R"( 2194 struct B { virtual void f(); }; 2195 struct D:B { void f(); }; 2196 void B::f(){} 2197 void D::f(){} 2198 void foo(B &b, D &d) { b.f(); d.f(); } 2199 )"; 2200 2201 auto BFP = 2202 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B")))); 2203 auto BFDefP = cxxMethodDecl( 2204 hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition()); 2205 auto DFP = 2206 cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D")))); 2207 auto DFDefP = cxxMethodDecl( 2208 hasName("f"), hasParent(cxxRecordDecl(hasName("D"))), isDefinition()); 2209 auto FooDef = functionDecl(hasName("foo")); 2210 2211 { 2212 Decl *FromTU0 = getTuDecl(CodeTU0, Lang_CXX03, "input0.cc"); 2213 auto *D = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP); 2214 Import(D, Lang_CXX03); 2215 } 2216 2217 { 2218 Decl *FromTU1 = getTuDecl(CodeTU1, Lang_CXX03, "input1.cc"); 2219 auto *Foo = FirstDeclMatcher<FunctionDecl>().match(FromTU1, FooDef); 2220 Import(Foo, Lang_CXX03); 2221 } 2222 2223 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2224 2225 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u); 2226 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u); 2227 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 0u); 2228 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFDefP), 0u); 2229 2230 auto *ToB = FirstDeclMatcher<CXXRecordDecl>().match( 2231 ToTU, cxxRecordDecl(hasName("B"))); 2232 auto *ToD = FirstDeclMatcher<CXXRecordDecl>().match( 2233 ToTU, cxxRecordDecl(hasName("D"))); 2234 auto *ToBFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, BFP); 2235 auto *ToBFOutOfClass = FirstDeclMatcher<CXXMethodDecl>().match( 2236 ToTU, cxxMethodDecl(hasName("f"), isDefinition())); 2237 auto *ToDFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, DFP); 2238 auto *ToDFOutOfClass = LastDeclMatcher<CXXMethodDecl>().match( 2239 ToTU, cxxMethodDecl(hasName("f"), isDefinition())); 2240 2241 // The definition should be out-of-class. 2242 EXPECT_NE(ToBFInClass, ToBFOutOfClass); 2243 EXPECT_NE(ToBFInClass->getLexicalDeclContext(), 2244 ToBFOutOfClass->getLexicalDeclContext()); 2245 EXPECT_EQ(ToBFOutOfClass->getDeclContext(), ToB); 2246 EXPECT_EQ(ToBFOutOfClass->getLexicalDeclContext(), ToTU); 2247 2248 EXPECT_NE(ToDFInClass, ToDFOutOfClass); 2249 EXPECT_NE(ToDFInClass->getLexicalDeclContext(), 2250 ToDFOutOfClass->getLexicalDeclContext()); 2251 EXPECT_EQ(ToDFOutOfClass->getDeclContext(), ToD); 2252 EXPECT_EQ(ToDFOutOfClass->getLexicalDeclContext(), ToTU); 2253 2254 // Check that the redecl chain is intact. 2255 EXPECT_EQ(ToBFOutOfClass->getPreviousDecl(), ToBFInClass); 2256 EXPECT_EQ(ToDFOutOfClass->getPreviousDecl(), ToDFInClass); 2257 } 2258 2259 TEST_P(ASTImporterOptionSpecificTestBase, ImportVariableChainInC) { 2260 std::string Code = "static int v; static int v = 0;"; 2261 auto Pattern = varDecl(hasName("v")); 2262 2263 TranslationUnitDecl *FromTu = getTuDecl(Code, Lang_C99, "input0.c"); 2264 2265 auto *From0 = FirstDeclMatcher<VarDecl>().match(FromTu, Pattern); 2266 auto *From1 = LastDeclMatcher<VarDecl>().match(FromTu, Pattern); 2267 2268 auto *To0 = Import(From0, Lang_C99); 2269 auto *To1 = Import(From1, Lang_C99); 2270 2271 EXPECT_TRUE(To0); 2272 ASSERT_TRUE(To1); 2273 EXPECT_NE(To0, To1); 2274 EXPECT_EQ(To1->getPreviousDecl(), To0); 2275 } 2276 2277 TEST_P(ImportFunctions, ImportFromDifferentScopedAnonNamespace) { 2278 TranslationUnitDecl *FromTu = 2279 getTuDecl("namespace NS0 { namespace { void f(); } }" 2280 "namespace NS1 { namespace { void f(); } }", 2281 Lang_CXX03, "input0.cc"); 2282 auto Pattern = functionDecl(hasName("f")); 2283 2284 auto *FromF0 = FirstDeclMatcher<FunctionDecl>().match(FromTu, Pattern); 2285 auto *FromF1 = LastDeclMatcher<FunctionDecl>().match(FromTu, Pattern); 2286 2287 auto *ToF0 = Import(FromF0, Lang_CXX03); 2288 auto *ToF1 = Import(FromF1, Lang_CXX03); 2289 2290 EXPECT_TRUE(ToF0); 2291 ASSERT_TRUE(ToF1); 2292 EXPECT_NE(ToF0, ToF1); 2293 EXPECT_FALSE(ToF1->getPreviousDecl()); 2294 } 2295 2296 TEST_P(ImportFunctions, ImportFunctionFromUnnamedNamespace) { 2297 { 2298 Decl *FromTU = getTuDecl("namespace { void f() {} } void g0() { f(); }", 2299 Lang_CXX03, "input0.cc"); 2300 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2301 FromTU, functionDecl(hasName("g0"))); 2302 2303 Import(FromD, Lang_CXX03); 2304 } 2305 { 2306 Decl *FromTU = 2307 getTuDecl("namespace { void f() { int a; } } void g1() { f(); }", 2308 Lang_CXX03, "input1.cc"); 2309 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2310 FromTU, functionDecl(hasName("g1"))); 2311 Import(FromD, Lang_CXX03); 2312 } 2313 2314 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2315 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))), 2316 2u); 2317 } 2318 2319 TEST_P(ImportFunctions, ImportImplicitFunctionsInLambda) { 2320 Decl *FromTU = getTuDecl( 2321 R"( 2322 void foo() { 2323 (void)[]() { ; }; 2324 } 2325 )", 2326 Lang_CXX11); 2327 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2328 FromTU, functionDecl(hasName("foo"))); 2329 auto *ToD = Import(FromD, Lang_CXX03); 2330 EXPECT_TRUE(ToD); 2331 CXXRecordDecl *LambdaRec = 2332 cast<LambdaExpr>(cast<CStyleCastExpr>( 2333 *cast<CompoundStmt>(ToD->getBody())->body_begin()) 2334 ->getSubExpr()) 2335 ->getLambdaClass(); 2336 EXPECT_TRUE(LambdaRec->getDestructor()); 2337 } 2338 2339 TEST_P(ImportFunctions, 2340 CallExprOfMemberFunctionTemplateWithExplicitTemplateArgs) { 2341 Decl *FromTU = getTuDecl( 2342 R"( 2343 struct X { 2344 template <typename T> 2345 void foo(){} 2346 }; 2347 void f() { 2348 X x; 2349 x.foo<int>(); 2350 } 2351 )", 2352 Lang_CXX03); 2353 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2354 FromTU, functionDecl(hasName("f"))); 2355 auto *ToD = Import(FromD, Lang_CXX03); 2356 EXPECT_TRUE(ToD); 2357 EXPECT_TRUE(MatchVerifier<FunctionDecl>().match( 2358 ToD, functionDecl(hasName("f"), hasDescendant(declRefExpr())))); 2359 } 2360 2361 TEST_P(ImportFunctions, 2362 DependentCallExprOfMemberFunctionTemplateWithExplicitTemplateArgs) { 2363 Decl *FromTU = getTuDecl( 2364 R"( 2365 struct X { 2366 template <typename T> 2367 void foo(){} 2368 }; 2369 template <typename T> 2370 void f() { 2371 X x; 2372 x.foo<T>(); 2373 } 2374 void g() { 2375 f<int>(); 2376 } 2377 )", 2378 Lang_CXX03); 2379 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2380 FromTU, functionDecl(hasName("g"))); 2381 auto *ToD = Import(FromD, Lang_CXX03); 2382 EXPECT_TRUE(ToD); 2383 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2384 EXPECT_TRUE(MatchVerifier<TranslationUnitDecl>().match( 2385 ToTU, translationUnitDecl(hasDescendant( 2386 functionDecl(hasName("f"), hasDescendant(declRefExpr())))))); 2387 } 2388 2389 struct ImportFunctionTemplates : ASTImporterOptionSpecificTestBase {}; 2390 2391 TEST_P(ImportFunctionTemplates, ImportFunctionTemplateInRecordDeclTwice) { 2392 auto Code = 2393 R"( 2394 class X { 2395 template <class T> 2396 void f(T t); 2397 }; 2398 )"; 2399 Decl *FromTU1 = getTuDecl(Code, Lang_CXX03, "input1.cc"); 2400 auto *FromD1 = FirstDeclMatcher<FunctionTemplateDecl>().match( 2401 FromTU1, functionTemplateDecl(hasName("f"))); 2402 auto *ToD1 = Import(FromD1, Lang_CXX03); 2403 Decl *FromTU2 = getTuDecl(Code, Lang_CXX03, "input2.cc"); 2404 auto *FromD2 = FirstDeclMatcher<FunctionTemplateDecl>().match( 2405 FromTU2, functionTemplateDecl(hasName("f"))); 2406 auto *ToD2 = Import(FromD2, Lang_CXX03); 2407 EXPECT_EQ(ToD1, ToD2); 2408 } 2409 2410 TEST_P(ImportFunctionTemplates, 2411 ImportFunctionTemplateWithDefInRecordDeclTwice) { 2412 auto Code = 2413 R"( 2414 class X { 2415 template <class T> 2416 void f(T t); 2417 }; 2418 template <class T> 2419 void X::f(T t) {}; 2420 )"; 2421 Decl *FromTU1 = getTuDecl(Code, Lang_CXX03, "input1.cc"); 2422 auto *FromD1 = FirstDeclMatcher<FunctionTemplateDecl>().match( 2423 FromTU1, functionTemplateDecl(hasName("f"))); 2424 auto *ToD1 = Import(FromD1, Lang_CXX03); 2425 Decl *FromTU2 = getTuDecl(Code, Lang_CXX03, "input2.cc"); 2426 auto *FromD2 = FirstDeclMatcher<FunctionTemplateDecl>().match( 2427 FromTU2, functionTemplateDecl(hasName("f"))); 2428 auto *ToD2 = Import(FromD2, Lang_CXX03); 2429 EXPECT_EQ(ToD1, ToD2); 2430 } 2431 2432 TEST_P(ImportFunctionTemplates, 2433 ImportFunctionWhenThereIsAFunTemplateWithSameName) { 2434 getToTuDecl( 2435 R"( 2436 template <typename T> 2437 void foo(T) {} 2438 void foo(); 2439 )", 2440 Lang_CXX03); 2441 Decl *FromTU = getTuDecl("void foo();", Lang_CXX03); 2442 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 2443 FromTU, functionDecl(hasName("foo"))); 2444 auto *ImportedD = Import(FromD, Lang_CXX03); 2445 EXPECT_TRUE(ImportedD); 2446 } 2447 2448 TEST_P(ImportFunctionTemplates, 2449 ImportConstructorWhenThereIsAFunTemplateWithSameName) { 2450 auto Code = 2451 R"( 2452 struct Foo { 2453 template <typename T> 2454 Foo(T) {} 2455 Foo(); 2456 }; 2457 )"; 2458 getToTuDecl(Code, Lang_CXX03); 2459 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 2460 auto *FromD = 2461 LastDeclMatcher<CXXConstructorDecl>().match(FromTU, cxxConstructorDecl()); 2462 auto *ImportedD = Import(FromD, Lang_CXX03); 2463 EXPECT_TRUE(ImportedD); 2464 } 2465 2466 TEST_P(ImportFunctionTemplates, 2467 ImportOperatorWhenThereIsAFunTemplateWithSameName) { 2468 getToTuDecl( 2469 R"( 2470 template <typename T> 2471 void operator<(T,T) {} 2472 struct X{}; 2473 void operator<(X, X); 2474 )", 2475 Lang_CXX03); 2476 Decl *FromTU = getTuDecl( 2477 R"( 2478 struct X{}; 2479 void operator<(X, X); 2480 )", 2481 Lang_CXX03); 2482 auto *FromD = LastDeclMatcher<FunctionDecl>().match( 2483 FromTU, functionDecl(hasOverloadedOperatorName("<"))); 2484 auto *ImportedD = Import(FromD, Lang_CXX03); 2485 EXPECT_TRUE(ImportedD); 2486 } 2487 2488 struct ImportFriendFunctions : ImportFunctions {}; 2489 2490 TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainProto) { 2491 auto Pattern = functionDecl(hasName("f")); 2492 2493 Decl *FromTU = getTuDecl("struct X { friend void f(); };" 2494 "void f();", 2495 Lang_CXX03, "input0.cc"); 2496 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2497 2498 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2499 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2500 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2501 EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody()); 2502 auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2503 EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody()); 2504 EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD); 2505 } 2506 2507 TEST_P(ImportFriendFunctions, 2508 ImportFriendFunctionRedeclChainProto_OutOfClassProtoFirst) { 2509 auto Pattern = functionDecl(hasName("f")); 2510 2511 Decl *FromTU = getTuDecl("void f();" 2512 "struct X { friend void f(); };", 2513 Lang_CXX03, "input0.cc"); 2514 auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2515 2516 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2517 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2518 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2519 EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody()); 2520 auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2521 EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody()); 2522 EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD); 2523 } 2524 2525 TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainDef) { 2526 auto Pattern = functionDecl(hasName("f")); 2527 2528 Decl *FromTU = getTuDecl("struct X { friend void f(){} };" 2529 "void f();", 2530 Lang_CXX03, "input0.cc"); 2531 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2532 2533 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2534 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2535 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2536 EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody()); 2537 auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2538 EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody()); 2539 EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD); 2540 } 2541 2542 TEST_P(ImportFriendFunctions, 2543 ImportFriendFunctionRedeclChainDef_OutOfClassDef) { 2544 auto Pattern = functionDecl(hasName("f")); 2545 2546 Decl *FromTU = getTuDecl("struct X { friend void f(); };" 2547 "void f(){}", 2548 Lang_CXX03, "input0.cc"); 2549 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2550 2551 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2552 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2553 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2554 EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody()); 2555 auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern); 2556 EXPECT_TRUE(ToFD->doesThisDeclarationHaveABody()); 2557 EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD); 2558 } 2559 2560 TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainDefWithClass) { 2561 auto Pattern = functionDecl(hasName("f")); 2562 2563 Decl *FromTU = getTuDecl( 2564 R"( 2565 class X; 2566 void f(X *x){} 2567 class X{ 2568 friend void f(X *x); 2569 }; 2570 )", 2571 Lang_CXX03, "input0.cc"); 2572 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2573 2574 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2575 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2576 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2577 EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody()); 2578 auto *InClassFD = cast<FunctionDecl>(FirstDeclMatcher<FriendDecl>() 2579 .match(ToTU, friendDecl()) 2580 ->getFriendDecl()); 2581 EXPECT_FALSE(InClassFD->doesThisDeclarationHaveABody()); 2582 EXPECT_EQ(InClassFD->getPreviousDecl(), ImportedD); 2583 // The parameters must refer the same type 2584 EXPECT_EQ((*InClassFD->param_begin())->getOriginalType(), 2585 (*ImportedD->param_begin())->getOriginalType()); 2586 } 2587 2588 TEST_P(ImportFriendFunctions, 2589 ImportFriendFunctionRedeclChainDefWithClass_ImportTheProto) { 2590 auto Pattern = functionDecl(hasName("f")); 2591 2592 Decl *FromTU = getTuDecl( 2593 R"( 2594 class X; 2595 void f(X *x){} 2596 class X{ 2597 friend void f(X *x); 2598 }; 2599 )", 2600 Lang_CXX03, "input0.cc"); 2601 auto *FromD = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2602 2603 auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2604 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2605 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2606 EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody()); 2607 auto *OutOfClassFD = FirstDeclMatcher<FunctionDecl>().match( 2608 ToTU, functionDecl(unless(hasParent(friendDecl())))); 2609 2610 EXPECT_TRUE(OutOfClassFD->doesThisDeclarationHaveABody()); 2611 EXPECT_EQ(ImportedD->getPreviousDecl(), OutOfClassFD); 2612 // The parameters must refer the same type 2613 EXPECT_EQ((*OutOfClassFD->param_begin())->getOriginalType(), 2614 (*ImportedD->param_begin())->getOriginalType()); 2615 } 2616 2617 TEST_P(ImportFriendFunctions, ImportFriendFunctionFromMultipleTU) { 2618 auto Pattern = functionDecl(hasName("f")); 2619 2620 FunctionDecl *ImportedD; 2621 { 2622 Decl *FromTU = 2623 getTuDecl("struct X { friend void f(){} };", Lang_CXX03, "input0.cc"); 2624 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2625 ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2626 } 2627 FunctionDecl *ImportedD1; 2628 { 2629 Decl *FromTU = getTuDecl("void f();", Lang_CXX03, "input1.cc"); 2630 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); 2631 ImportedD1 = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2632 } 2633 2634 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2635 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2636 EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody()); 2637 EXPECT_FALSE(ImportedD1->doesThisDeclarationHaveABody()); 2638 EXPECT_EQ(ImportedD1->getPreviousDecl(), ImportedD); 2639 } 2640 2641 TEST_P(ImportFriendFunctions, Lookup) { 2642 auto FunctionPattern = functionDecl(hasName("f")); 2643 auto ClassPattern = cxxRecordDecl(hasName("X")); 2644 2645 TranslationUnitDecl *FromTU = 2646 getTuDecl("struct X { friend void f(); };", Lang_CXX03, "input0.cc"); 2647 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern); 2648 ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2649 ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2650 { 2651 auto FromName = FromD->getDeclName(); 2652 auto *Class = FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern); 2653 auto LookupRes = Class->noload_lookup(FromName); 2654 ASSERT_TRUE(LookupRes.empty()); 2655 LookupRes = FromTU->noload_lookup(FromName); 2656 ASSERT_TRUE(LookupRes.isSingleResult()); 2657 } 2658 2659 auto *ToD = cast<FunctionDecl>(Import(FromD, Lang_CXX03)); 2660 auto ToName = ToD->getDeclName(); 2661 2662 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2663 auto *Class = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern); 2664 auto LookupRes = Class->noload_lookup(ToName); 2665 EXPECT_TRUE(LookupRes.empty()); 2666 LookupRes = ToTU->noload_lookup(ToName); 2667 EXPECT_TRUE(LookupRes.isSingleResult()); 2668 2669 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 1u); 2670 auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern); 2671 EXPECT_TRUE(To0->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2672 EXPECT_FALSE(To0->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2673 } 2674 2675 TEST_P(ImportFriendFunctions, LookupWithProtoAfter) { 2676 auto FunctionPattern = functionDecl(hasName("f")); 2677 auto ClassPattern = cxxRecordDecl(hasName("X")); 2678 2679 TranslationUnitDecl *FromTU = 2680 getTuDecl("struct X { friend void f(); };" 2681 // This proto decl makes f available to normal 2682 // lookup, otherwise it is hidden. 2683 // Normal C++ lookup (implemented in 2684 // `clang::Sema::CppLookupName()` and in `LookupDirect()`) 2685 // returns the found `NamedDecl` only if the set IDNS is matched 2686 "void f();", 2687 Lang_CXX03, "input0.cc"); 2688 auto *FromFriend = 2689 FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern); 2690 auto *FromNormal = 2691 LastDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern); 2692 ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2693 ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2694 ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2695 ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2696 2697 auto FromName = FromFriend->getDeclName(); 2698 auto *FromClass = 2699 FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern); 2700 auto LookupRes = FromClass->noload_lookup(FromName); 2701 ASSERT_TRUE(LookupRes.empty()); 2702 LookupRes = FromTU->noload_lookup(FromName); 2703 ASSERT_TRUE(LookupRes.isSingleResult()); 2704 2705 auto *ToFriend = cast<FunctionDecl>(Import(FromFriend, Lang_CXX03)); 2706 auto ToName = ToFriend->getDeclName(); 2707 2708 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2709 auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern); 2710 LookupRes = ToClass->noload_lookup(ToName); 2711 EXPECT_TRUE(LookupRes.empty()); 2712 LookupRes = ToTU->noload_lookup(ToName); 2713 // Test is disabled because this result is 2. 2714 EXPECT_TRUE(LookupRes.isSingleResult()); 2715 2716 ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 2u); 2717 ToFriend = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern); 2718 auto *ToNormal = LastDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern); 2719 EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2720 EXPECT_FALSE(ToFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2721 EXPECT_FALSE(ToNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2722 EXPECT_TRUE(ToNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2723 } 2724 2725 TEST_P(ImportFriendFunctions, LookupWithProtoBefore) { 2726 auto FunctionPattern = functionDecl(hasName("f")); 2727 auto ClassPattern = cxxRecordDecl(hasName("X")); 2728 2729 TranslationUnitDecl *FromTU = getTuDecl("void f();" 2730 "struct X { friend void f(); };", 2731 Lang_CXX03, "input0.cc"); 2732 auto *FromNormal = 2733 FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern); 2734 auto *FromFriend = 2735 LastDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern); 2736 ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2737 ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2738 ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2739 ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2740 2741 auto FromName = FromNormal->getDeclName(); 2742 auto *FromClass = 2743 FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern); 2744 auto LookupRes = FromClass->noload_lookup(FromName); 2745 ASSERT_TRUE(LookupRes.empty()); 2746 LookupRes = FromTU->noload_lookup(FromName); 2747 ASSERT_TRUE(LookupRes.isSingleResult()); 2748 2749 auto *ToNormal = cast<FunctionDecl>(Import(FromNormal, Lang_CXX03)); 2750 auto ToName = ToNormal->getDeclName(); 2751 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2752 2753 auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern); 2754 LookupRes = ToClass->noload_lookup(ToName); 2755 EXPECT_TRUE(LookupRes.empty()); 2756 LookupRes = ToTU->noload_lookup(ToName); 2757 EXPECT_TRUE(LookupRes.isSingleResult()); 2758 2759 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 2u); 2760 ToNormal = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern); 2761 auto *ToFriend = LastDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern); 2762 EXPECT_FALSE(ToNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2763 EXPECT_TRUE(ToNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2764 EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2765 EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2766 } 2767 2768 TEST_P(ImportFriendFunctions, ImportFriendChangesLookup) { 2769 auto Pattern = functionDecl(hasName("f")); 2770 2771 TranslationUnitDecl *FromNormalTU = 2772 getTuDecl("void f();", Lang_CXX03, "input0.cc"); 2773 auto *FromNormalF = 2774 FirstDeclMatcher<FunctionDecl>().match(FromNormalTU, Pattern); 2775 TranslationUnitDecl *FromFriendTU = 2776 getTuDecl("class X { friend void f(); };", Lang_CXX03, "input1.cc"); 2777 auto *FromFriendF = 2778 FirstDeclMatcher<FunctionDecl>().match(FromFriendTU, Pattern); 2779 auto FromNormalName = FromNormalF->getDeclName(); 2780 auto FromFriendName = FromFriendF->getDeclName(); 2781 2782 ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2783 ASSERT_FALSE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2784 ASSERT_FALSE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2785 ASSERT_TRUE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2786 auto LookupRes = FromNormalTU->noload_lookup(FromNormalName); 2787 ASSERT_TRUE(LookupRes.isSingleResult()); 2788 LookupRes = FromFriendTU->noload_lookup(FromFriendName); 2789 ASSERT_TRUE(LookupRes.isSingleResult()); 2790 2791 auto *ToNormalF = cast<FunctionDecl>(Import(FromNormalF, Lang_CXX03)); 2792 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2793 auto ToName = ToNormalF->getDeclName(); 2794 EXPECT_TRUE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2795 EXPECT_FALSE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2796 LookupRes = ToTU->noload_lookup(ToName); 2797 EXPECT_TRUE(LookupRes.isSingleResult()); 2798 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 1u); 2799 2800 auto *ToFriendF = cast<FunctionDecl>(Import(FromFriendF, Lang_CXX03)); 2801 LookupRes = ToTU->noload_lookup(ToName); 2802 EXPECT_TRUE(LookupRes.isSingleResult()); 2803 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u); 2804 2805 EXPECT_TRUE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2806 EXPECT_FALSE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2807 2808 EXPECT_TRUE(ToFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary)); 2809 EXPECT_TRUE(ToFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)); 2810 } 2811 2812 TEST_P(ImportFriendFunctions, ImportFriendList) { 2813 TranslationUnitDecl *FromTU = getTuDecl("struct X { friend void f(); };" 2814 "void f();", 2815 Lang_CXX03, "input0.cc"); 2816 auto *FromFriendF = FirstDeclMatcher<FunctionDecl>().match( 2817 FromTU, functionDecl(hasName("f"))); 2818 2819 auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match( 2820 FromTU, cxxRecordDecl(hasName("X"))); 2821 auto *FromFriend = FirstDeclMatcher<FriendDecl>().match(FromTU, friendDecl()); 2822 auto FromFriends = FromClass->friends(); 2823 unsigned int FrN = 0; 2824 for (auto Fr : FromFriends) { 2825 ASSERT_EQ(Fr, FromFriend); 2826 ++FrN; 2827 } 2828 ASSERT_EQ(FrN, 1u); 2829 2830 Import(FromFriendF, Lang_CXX03); 2831 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 2832 auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match( 2833 ToTU, cxxRecordDecl(hasName("X"))); 2834 auto *ToFriend = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl()); 2835 auto ToFriends = ToClass->friends(); 2836 FrN = 0; 2837 for (auto Fr : ToFriends) { 2838 EXPECT_EQ(Fr, ToFriend); 2839 ++FrN; 2840 } 2841 EXPECT_EQ(FrN, 1u); 2842 } 2843 2844 AST_MATCHER_P(TagDecl, hasTypedefForAnonDecl, Matcher<TypedefNameDecl>, 2845 InnerMatcher) { 2846 if (auto *Typedef = Node.getTypedefNameForAnonDecl()) 2847 return InnerMatcher.matches(*Typedef, Finder, Builder); 2848 return false; 2849 } 2850 2851 TEST_P(ImportDecl, ImportEnumSequential) { 2852 CodeFiles Samples{{"main.c", 2853 {"void foo();" 2854 "void moo();" 2855 "int main() { foo(); moo(); }", 2856 Lang_C99}}, 2857 2858 {"foo.c", 2859 {"typedef enum { THING_VALUE } thing_t;" 2860 "void conflict(thing_t type);" 2861 "void foo() { (void)THING_VALUE; }" 2862 "void conflict(thing_t type) {}", 2863 Lang_C99}}, 2864 2865 {"moo.c", 2866 {"typedef enum { THING_VALUE } thing_t;" 2867 "void conflict(thing_t type);" 2868 "void moo() { conflict(THING_VALUE); }", 2869 Lang_C99}}}; 2870 2871 auto VerificationMatcher = 2872 enumDecl(has(enumConstantDecl(hasName("THING_VALUE"))), 2873 hasTypedefForAnonDecl(hasName("thing_t"))); 2874 2875 ImportAction ImportFoo{"foo.c", "main.c", functionDecl(hasName("foo"))}, 2876 ImportMoo{"moo.c", "main.c", functionDecl(hasName("moo"))}; 2877 2878 testImportSequence( 2879 Samples, {ImportFoo, ImportMoo}, // "foo", them "moo". 2880 // Just check that there is only one enum decl in the result AST. 2881 "main.c", enumDecl(), VerificationMatcher); 2882 2883 // For different import order, result should be the same. 2884 testImportSequence( 2885 Samples, {ImportMoo, ImportFoo}, // "moo", them "foo". 2886 // Check that there is only one enum decl in the result AST. 2887 "main.c", enumDecl(), VerificationMatcher); 2888 } 2889 2890 TEST_P(ImportDecl, ImportFieldOrder) { 2891 MatchVerifier<Decl> Verifier; 2892 testImport("struct declToImport {" 2893 " int b = a + 2;" 2894 " int a = 5;" 2895 "};", 2896 Lang_CXX11, "", Lang_CXX11, Verifier, 2897 recordDecl(hasFieldOrder({"b", "a"}))); 2898 } 2899 2900 const internal::VariadicDynCastAllOfMatcher<Expr, DependentScopeDeclRefExpr> 2901 dependentScopeDeclRefExpr; 2902 2903 TEST_P(ImportExpr, DependentScopeDeclRefExpr) { 2904 MatchVerifier<Decl> Verifier; 2905 testImport("template <typename T> struct S { static T foo; };" 2906 "template <typename T> void declToImport() {" 2907 " (void) S<T>::foo;" 2908 "}" 2909 "void instantiate() { declToImport<int>(); }" 2910 "template <typename T> T S<T>::foo;", 2911 Lang_CXX11, "", Lang_CXX11, Verifier, 2912 functionTemplateDecl(has(functionDecl(has(compoundStmt( 2913 has(cStyleCastExpr(has(dependentScopeDeclRefExpr()))))))))); 2914 2915 testImport("template <typename T> struct S {" 2916 "template<typename S> static void foo(){};" 2917 "};" 2918 "template <typename T> void declToImport() {" 2919 " S<T>::template foo<T>();" 2920 "}" 2921 "void instantiate() { declToImport<int>(); }", 2922 Lang_CXX11, "", Lang_CXX11, Verifier, 2923 functionTemplateDecl(has(functionDecl(has(compoundStmt( 2924 has(callExpr(has(dependentScopeDeclRefExpr()))))))))); 2925 } 2926 2927 const internal::VariadicDynCastAllOfMatcher<Type, DependentNameType> 2928 dependentNameType; 2929 2930 TEST_P(ImportExpr, DependentNameType) { 2931 MatchVerifier<Decl> Verifier; 2932 testImport("template <typename T> struct declToImport {" 2933 " typedef typename T::type dependent_name;" 2934 "};", 2935 Lang_CXX11, "", Lang_CXX11, Verifier, 2936 classTemplateDecl(has( 2937 cxxRecordDecl(has(typedefDecl(has(dependentNameType()))))))); 2938 } 2939 2940 TEST_P(ImportExpr, UnresolvedMemberExpr) { 2941 MatchVerifier<Decl> Verifier; 2942 testImport("struct S { template <typename T> void mem(); };" 2943 "template <typename U> void declToImport() {" 2944 " S s;" 2945 " s.mem<U>();" 2946 "}" 2947 "void instantiate() { declToImport<int>(); }", 2948 Lang_CXX11, "", Lang_CXX11, Verifier, 2949 functionTemplateDecl(has(functionDecl(has( 2950 compoundStmt(has(callExpr(has(unresolvedMemberExpr()))))))))); 2951 } 2952 2953 class ImportImplicitMethods : public ASTImporterOptionSpecificTestBase { 2954 public: 2955 static constexpr auto DefaultCode = R"( 2956 struct A { int x; }; 2957 void f() { 2958 A a; 2959 A a1(a); 2960 A a2(A{}); 2961 a = a1; 2962 a = A{}; 2963 a.~A(); 2964 })"; 2965 2966 template <typename MatcherType> 2967 void testImportOf( 2968 const MatcherType &MethodMatcher, const char *Code = DefaultCode) { 2969 test(MethodMatcher, Code, /*ExpectedCount=*/1u); 2970 } 2971 2972 template <typename MatcherType> 2973 void testNoImportOf( 2974 const MatcherType &MethodMatcher, const char *Code = DefaultCode) { 2975 test(MethodMatcher, Code, /*ExpectedCount=*/0u); 2976 } 2977 2978 private: 2979 template <typename MatcherType> 2980 void test(const MatcherType &MethodMatcher, 2981 const char *Code, unsigned int ExpectedCount) { 2982 auto ClassMatcher = cxxRecordDecl(unless(isImplicit())); 2983 2984 Decl *ToTU = getToTuDecl(Code, Lang_CXX11); 2985 auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match( 2986 ToTU, ClassMatcher); 2987 2988 ASSERT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher), 1u); 2989 2990 { 2991 CXXMethodDecl *Method = 2992 FirstDeclMatcher<CXXMethodDecl>().match(ToClass, MethodMatcher); 2993 ToClass->removeDecl(Method); 2994 SharedStatePtr->getLookupTable()->remove(Method); 2995 } 2996 2997 ASSERT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher), 0u); 2998 2999 Decl *ImportedClass = nullptr; 3000 { 3001 Decl *FromTU = getTuDecl(Code, Lang_CXX11, "input1.cc"); 3002 auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match( 3003 FromTU, ClassMatcher); 3004 ImportedClass = Import(FromClass, Lang_CXX11); 3005 } 3006 3007 EXPECT_EQ(ToClass, ImportedClass); 3008 EXPECT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher), 3009 ExpectedCount); 3010 } 3011 }; 3012 3013 TEST_P(ImportImplicitMethods, DefaultConstructor) { 3014 testImportOf(cxxConstructorDecl(isDefaultConstructor())); 3015 } 3016 3017 TEST_P(ImportImplicitMethods, CopyConstructor) { 3018 testImportOf(cxxConstructorDecl(isCopyConstructor())); 3019 } 3020 3021 TEST_P(ImportImplicitMethods, MoveConstructor) { 3022 testImportOf(cxxConstructorDecl(isMoveConstructor())); 3023 } 3024 3025 TEST_P(ImportImplicitMethods, Destructor) { 3026 testImportOf(cxxDestructorDecl()); 3027 } 3028 3029 TEST_P(ImportImplicitMethods, CopyAssignment) { 3030 testImportOf(cxxMethodDecl(isCopyAssignmentOperator())); 3031 } 3032 3033 TEST_P(ImportImplicitMethods, MoveAssignment) { 3034 testImportOf(cxxMethodDecl(isMoveAssignmentOperator())); 3035 } 3036 3037 TEST_P(ImportImplicitMethods, DoNotImportUserProvided) { 3038 auto Code = R"( 3039 struct A { A() { int x; } }; 3040 )"; 3041 testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code); 3042 } 3043 3044 TEST_P(ImportImplicitMethods, DoNotImportDefault) { 3045 auto Code = R"( 3046 struct A { A() = default; }; 3047 )"; 3048 testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code); 3049 } 3050 3051 TEST_P(ImportImplicitMethods, DoNotImportDeleted) { 3052 auto Code = R"( 3053 struct A { A() = delete; }; 3054 )"; 3055 testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code); 3056 } 3057 3058 TEST_P(ImportImplicitMethods, DoNotImportOtherMethod) { 3059 auto Code = R"( 3060 struct A { void f() { } }; 3061 )"; 3062 testNoImportOf(cxxMethodDecl(hasName("f")), Code); 3063 } 3064 3065 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentRecord) { 3066 Decl *ToR1; 3067 { 3068 Decl *FromTU = getTuDecl("struct A { };", Lang_CXX03, "input0.cc"); 3069 auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match( 3070 FromTU, cxxRecordDecl(hasName("A"))); 3071 3072 ToR1 = Import(FromR, Lang_CXX03); 3073 } 3074 3075 Decl *ToR2; 3076 { 3077 Decl *FromTU = getTuDecl("struct A { };", Lang_CXX03, "input1.cc"); 3078 auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match( 3079 FromTU, cxxRecordDecl(hasName("A"))); 3080 3081 ToR2 = Import(FromR, Lang_CXX03); 3082 } 3083 3084 EXPECT_EQ(ToR1, ToR2); 3085 } 3086 3087 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentRecord) { 3088 Decl *ToR1; 3089 { 3090 Decl *FromTU = getTuDecl("struct A { int x; };", Lang_CXX03, "input0.cc"); 3091 auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match( 3092 FromTU, cxxRecordDecl(hasName("A"))); 3093 ToR1 = Import(FromR, Lang_CXX03); 3094 } 3095 Decl *ToR2; 3096 { 3097 Decl *FromTU = 3098 getTuDecl("struct A { unsigned x; };", Lang_CXX03, "input1.cc"); 3099 auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match( 3100 FromTU, cxxRecordDecl(hasName("A"))); 3101 ToR2 = Import(FromR, Lang_CXX03); 3102 } 3103 EXPECT_NE(ToR1, ToR2); 3104 } 3105 3106 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentField) { 3107 Decl *ToF1; 3108 { 3109 Decl *FromTU = getTuDecl("struct A { int x; };", Lang_CXX03, "input0.cc"); 3110 auto *FromF = FirstDeclMatcher<FieldDecl>().match( 3111 FromTU, fieldDecl(hasName("x"))); 3112 ToF1 = Import(FromF, Lang_CXX03); 3113 } 3114 Decl *ToF2; 3115 { 3116 Decl *FromTU = getTuDecl("struct A { int x; };", Lang_CXX03, "input1.cc"); 3117 auto *FromF = FirstDeclMatcher<FieldDecl>().match( 3118 FromTU, fieldDecl(hasName("x"))); 3119 ToF2 = Import(FromF, Lang_CXX03); 3120 } 3121 EXPECT_EQ(ToF1, ToF2); 3122 } 3123 3124 TEST_P(ASTImporterOptionSpecificTestBase, ImportBitfields) { 3125 Decl *FromTU = getTuDecl("struct A { unsigned x : 3; };", Lang_CXX03); 3126 auto *FromF = 3127 FirstDeclMatcher<FieldDecl>().match(FromTU, fieldDecl(hasName("x"))); 3128 3129 ASSERT_TRUE(FromF->isBitField()); 3130 ASSERT_EQ(3u, FromF->getBitWidthValue(FromTU->getASTContext())); 3131 auto *ToField = Import(FromF, Lang_CXX03); 3132 auto *ToTU = ToField->getTranslationUnitDecl(); 3133 3134 EXPECT_TRUE(ToField->isBitField()); 3135 EXPECT_EQ(3u, ToField->getBitWidthValue(ToTU->getASTContext())); 3136 3137 const auto *FromBT = FromF->getBitWidth()->getType()->getAs<BuiltinType>(); 3138 const auto *ToBT = ToField->getBitWidth()->getType()->getAs<BuiltinType>(); 3139 ASSERT_TRUE(FromBT); 3140 ASSERT_EQ(BuiltinType::Int, FromBT->getKind()); 3141 EXPECT_TRUE(ToBT); 3142 EXPECT_EQ(BuiltinType::Int, ToBT->getKind()); 3143 } 3144 3145 struct ImportBlock : ASTImporterOptionSpecificTestBase {}; 3146 TEST_P(ImportBlock, ImportBlocksAreUnsupported) { 3147 const auto *Code = R"( 3148 void test_block__capture_null() { 3149 int *p = 0; 3150 ^(){ 3151 *p = 1; 3152 }(); 3153 })"; 3154 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 3155 auto *FromBlock = FirstDeclMatcher<BlockDecl>().match(FromTU, blockDecl()); 3156 ASSERT_TRUE(FromBlock); 3157 3158 auto ToBlockOrError = importOrError(FromBlock, Lang_CXX03); 3159 3160 const auto ExpectUnsupportedConstructError = [](const ImportError &Error) { 3161 EXPECT_EQ(ImportError::UnsupportedConstruct, Error.Error); 3162 }; 3163 llvm::handleAllErrors(ToBlockOrError.takeError(), 3164 ExpectUnsupportedConstructError); 3165 } 3166 3167 TEST_P(ASTImporterOptionSpecificTestBase, ImportParmVarDecl) { 3168 const auto *Code = R"( 3169 template <typename T> struct Wrapper { 3170 Wrapper(T Value = {}) {} 3171 }; 3172 template class Wrapper<int>; 3173 )"; 3174 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 3175 auto *FromVar = FirstDeclMatcher<ParmVarDecl>().match( 3176 FromTU, parmVarDecl(hasType(asString("int")))); 3177 ASSERT_TRUE(FromVar); 3178 ASSERT_TRUE(FromVar->hasUninstantiatedDefaultArg()); 3179 ASSERT_TRUE(FromVar->getUninstantiatedDefaultArg()); 3180 3181 const auto *ToVar = Import(FromVar, Lang_CXX11); 3182 EXPECT_TRUE(ToVar); 3183 EXPECT_TRUE(ToVar->hasUninstantiatedDefaultArg()); 3184 EXPECT_TRUE(ToVar->getUninstantiatedDefaultArg()); 3185 EXPECT_NE(FromVar->getUninstantiatedDefaultArg(), 3186 ToVar->getUninstantiatedDefaultArg()); 3187 } 3188 3189 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentField) { 3190 Decl *ToF1; 3191 { 3192 Decl *FromTU = getTuDecl("struct A { int x; };", Lang_CXX03, "input0.cc"); 3193 auto *FromF = FirstDeclMatcher<FieldDecl>().match( 3194 FromTU, fieldDecl(hasName("x"))); 3195 ToF1 = Import(FromF, Lang_CXX03); 3196 } 3197 Decl *ToF2; 3198 { 3199 Decl *FromTU = 3200 getTuDecl("struct A { unsigned x; };", Lang_CXX03, "input1.cc"); 3201 auto *FromF = FirstDeclMatcher<FieldDecl>().match( 3202 FromTU, fieldDecl(hasName("x"))); 3203 ToF2 = Import(FromF, Lang_CXX03); 3204 } 3205 EXPECT_NE(ToF1, ToF2); 3206 } 3207 3208 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentMethod) { 3209 Decl *ToM1; 3210 { 3211 Decl *FromTU = getTuDecl("struct A { void x(); }; void A::x() { }", 3212 Lang_CXX03, "input0.cc"); 3213 auto *FromM = FirstDeclMatcher<FunctionDecl>().match( 3214 FromTU, functionDecl(hasName("x"), isDefinition())); 3215 ToM1 = Import(FromM, Lang_CXX03); 3216 } 3217 Decl *ToM2; 3218 { 3219 Decl *FromTU = getTuDecl("struct A { void x(); }; void A::x() { }", 3220 Lang_CXX03, "input1.cc"); 3221 auto *FromM = FirstDeclMatcher<FunctionDecl>().match( 3222 FromTU, functionDecl(hasName("x"), isDefinition())); 3223 ToM2 = Import(FromM, Lang_CXX03); 3224 } 3225 EXPECT_EQ(ToM1, ToM2); 3226 } 3227 3228 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentMethod) { 3229 Decl *ToM1; 3230 { 3231 Decl *FromTU = getTuDecl("struct A { void x(); }; void A::x() { }", 3232 Lang_CXX03, "input0.cc"); 3233 auto *FromM = FirstDeclMatcher<FunctionDecl>().match( 3234 FromTU, functionDecl(hasName("x"), isDefinition())); 3235 ToM1 = Import(FromM, Lang_CXX03); 3236 } 3237 Decl *ToM2; 3238 { 3239 Decl *FromTU = 3240 getTuDecl("struct A { void x() const; }; void A::x() const { }", 3241 Lang_CXX03, "input1.cc"); 3242 auto *FromM = FirstDeclMatcher<FunctionDecl>().match( 3243 FromTU, functionDecl(hasName("x"), isDefinition())); 3244 ToM2 = Import(FromM, Lang_CXX03); 3245 } 3246 EXPECT_NE(ToM1, ToM2); 3247 } 3248 3249 TEST_P(ASTImporterOptionSpecificTestBase, 3250 ImportUnnamedStructsWithRecursingField) { 3251 Decl *FromTU = getTuDecl( 3252 R"( 3253 struct A { 3254 struct { 3255 struct A *next; 3256 } entry0; 3257 struct { 3258 struct A *next; 3259 } entry1; 3260 }; 3261 )", 3262 Lang_C99, "input0.cc"); 3263 auto *From = 3264 FirstDeclMatcher<RecordDecl>().match(FromTU, recordDecl(hasName("A"))); 3265 3266 Import(From, Lang_C99); 3267 3268 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 3269 auto *Entry0 = 3270 FirstDeclMatcher<FieldDecl>().match(ToTU, fieldDecl(hasName("entry0"))); 3271 auto *Entry1 = 3272 FirstDeclMatcher<FieldDecl>().match(ToTU, fieldDecl(hasName("entry1"))); 3273 auto *R0 = getRecordDecl(Entry0); 3274 auto *R1 = getRecordDecl(Entry1); 3275 EXPECT_NE(R0, R1); 3276 EXPECT_TRUE(MatchVerifier<RecordDecl>().match( 3277 R0, recordDecl(has(fieldDecl(hasName("next")))))); 3278 EXPECT_TRUE(MatchVerifier<RecordDecl>().match( 3279 R1, recordDecl(has(fieldDecl(hasName("next")))))); 3280 } 3281 3282 TEST_P(ASTImporterOptionSpecificTestBase, ImportUnnamedFieldsInCorrectOrder) { 3283 Decl *FromTU = getTuDecl( 3284 R"( 3285 void f(int X, int Y, bool Z) { 3286 (void)[X, Y, Z] { (void)Z; }; 3287 } 3288 )", 3289 Lang_CXX11, "input0.cc"); 3290 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 3291 FromTU, functionDecl(hasName("f"))); 3292 auto *ToF = cast_or_null<FunctionDecl>(Import(FromF, Lang_CXX11)); 3293 EXPECT_TRUE(ToF); 3294 3295 CXXRecordDecl *FromLambda = 3296 cast<LambdaExpr>(cast<CStyleCastExpr>(cast<CompoundStmt>( 3297 FromF->getBody())->body_front())->getSubExpr())->getLambdaClass(); 3298 3299 auto *ToLambda = cast_or_null<CXXRecordDecl>(Import(FromLambda, Lang_CXX11)); 3300 EXPECT_TRUE(ToLambda); 3301 3302 // Check if the fields of the lambda class are imported in correct order. 3303 unsigned FromIndex = 0u; 3304 for (auto *FromField : FromLambda->fields()) { 3305 ASSERT_FALSE(FromField->getDeclName()); 3306 auto *ToField = cast_or_null<FieldDecl>(Import(FromField, Lang_CXX11)); 3307 EXPECT_TRUE(ToField); 3308 Optional<unsigned> ToIndex = ASTImporter::getFieldIndex(ToField); 3309 EXPECT_TRUE(ToIndex); 3310 EXPECT_EQ(*ToIndex, FromIndex); 3311 ++FromIndex; 3312 } 3313 3314 EXPECT_EQ(FromIndex, 3u); 3315 } 3316 3317 TEST_P(ASTImporterOptionSpecificTestBase, 3318 MergeFieldDeclsOfClassTemplateSpecialization) { 3319 std::string ClassTemplate = 3320 R"( 3321 template <typename T> 3322 struct X { 3323 int a{0}; // FieldDecl with InitListExpr 3324 X(char) : a(3) {} // (1) 3325 X(int) {} // (2) 3326 }; 3327 )"; 3328 Decl *ToTU = getToTuDecl(ClassTemplate + 3329 R"( 3330 void foo() { 3331 // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr 3332 X<char> xc('c'); 3333 } 3334 )", Lang_CXX11); 3335 auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3336 ToTU, classTemplateSpecializationDecl(hasName("X"))); 3337 // FieldDecl without InitlistExpr: 3338 auto *ToField = *ToSpec->field_begin(); 3339 ASSERT_TRUE(ToField); 3340 ASSERT_FALSE(ToField->getInClassInitializer()); 3341 Decl *FromTU = getTuDecl(ClassTemplate + 3342 R"( 3343 void bar() { 3344 // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr 3345 X<char> xc(1); 3346 } 3347 )", Lang_CXX11); 3348 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3349 FromTU, classTemplateSpecializationDecl(hasName("X"))); 3350 // FieldDecl with InitlistExpr: 3351 auto *FromField = *FromSpec->field_begin(); 3352 ASSERT_TRUE(FromField); 3353 ASSERT_TRUE(FromField->getInClassInitializer()); 3354 3355 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3356 ASSERT_TRUE(ImportedSpec); 3357 EXPECT_EQ(ImportedSpec, ToSpec); 3358 // After the import, the FieldDecl has to be merged, thus it should have the 3359 // InitListExpr. 3360 EXPECT_TRUE(ToField->getInClassInitializer()); 3361 } 3362 3363 TEST_P(ASTImporterOptionSpecificTestBase, 3364 MergeFunctionOfClassTemplateSpecialization) { 3365 std::string ClassTemplate = 3366 R"( 3367 template <typename T> 3368 struct X { 3369 void f() {} 3370 void g() {} 3371 }; 3372 )"; 3373 Decl *ToTU = getToTuDecl(ClassTemplate + 3374 R"( 3375 void foo() { 3376 X<char> x; 3377 x.f(); 3378 } 3379 )", Lang_CXX11); 3380 Decl *FromTU = getTuDecl(ClassTemplate + 3381 R"( 3382 void bar() { 3383 X<char> x; 3384 x.g(); 3385 } 3386 )", Lang_CXX11); 3387 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3388 FromTU, classTemplateSpecializationDecl(hasName("X"))); 3389 auto FunPattern = functionDecl(hasName("g"), 3390 hasParent(classTemplateSpecializationDecl())); 3391 auto *FromFun = 3392 FirstDeclMatcher<FunctionDecl>().match(FromTU, FunPattern); 3393 auto *ToFun = 3394 FirstDeclMatcher<FunctionDecl>().match(ToTU, FunPattern); 3395 ASSERT_TRUE(FromFun->hasBody()); 3396 ASSERT_FALSE(ToFun->hasBody()); 3397 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3398 ASSERT_TRUE(ImportedSpec); 3399 auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3400 ToTU, classTemplateSpecializationDecl(hasName("X"))); 3401 EXPECT_EQ(ImportedSpec, ToSpec); 3402 EXPECT_TRUE(ToFun->hasBody()); 3403 } 3404 3405 TEST_P(ASTImporterOptionSpecificTestBase, MergeTemplateSpecWithForwardDecl) { 3406 std::string ClassTemplate = 3407 R"( 3408 template<typename T> 3409 struct X { int m; }; 3410 template<> 3411 struct X<int> { int m; }; 3412 )"; 3413 // Append a forward decl for our template specialization. 3414 getToTuDecl(ClassTemplate + "template<> struct X<int>;", Lang_CXX11); 3415 Decl *FromTU = getTuDecl(ClassTemplate, Lang_CXX11); 3416 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3417 FromTU, classTemplateSpecializationDecl(hasName("X"), isDefinition())); 3418 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3419 // Check that our definition got merged with the existing definition. 3420 EXPECT_TRUE(FromSpec->isThisDeclarationADefinition()); 3421 EXPECT_TRUE(ImportedSpec->isThisDeclarationADefinition()); 3422 } 3423 3424 TEST_P(ASTImporterOptionSpecificTestBase, 3425 ODRViolationOfClassTemplateSpecializationsShouldBeReported) { 3426 std::string ClassTemplate = 3427 R"( 3428 template <typename T> 3429 struct X {}; 3430 )"; 3431 Decl *ToTU = getToTuDecl(ClassTemplate + 3432 R"( 3433 template <> 3434 struct X<char> { 3435 int a; 3436 }; 3437 void foo() { 3438 X<char> x; 3439 } 3440 )", 3441 Lang_CXX11); 3442 Decl *FromTU = getTuDecl(ClassTemplate + 3443 R"( 3444 template <> 3445 struct X<char> { 3446 int b; 3447 }; 3448 void foo() { 3449 X<char> x; 3450 } 3451 )", 3452 Lang_CXX11); 3453 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3454 FromTU, classTemplateSpecializationDecl(hasName("X"))); 3455 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3456 3457 // We expect one (ODR) warning during the import. 3458 EXPECT_EQ(1u, ToTU->getASTContext().getDiagnostics().getNumWarnings()); 3459 3460 // The second specialization is different from the first, thus it violates 3461 // ODR, consequently we expect to keep the first specialization only, which is 3462 // already in the "To" context. 3463 EXPECT_FALSE(ImportedSpec); 3464 EXPECT_EQ(1u, 3465 DeclCounter<ClassTemplateSpecializationDecl>().match( 3466 ToTU, classTemplateSpecializationDecl(hasName("X")))); 3467 } 3468 3469 TEST_P(ASTImporterOptionSpecificTestBase, 3470 MergeCtorOfClassTemplateSpecialization) { 3471 std::string ClassTemplate = 3472 R"( 3473 template <typename T> 3474 struct X { 3475 X(char) {} 3476 X(int) {} 3477 }; 3478 )"; 3479 Decl *ToTU = getToTuDecl(ClassTemplate + 3480 R"( 3481 void foo() { 3482 X<char> x('c'); 3483 } 3484 )", Lang_CXX11); 3485 Decl *FromTU = getTuDecl(ClassTemplate + 3486 R"( 3487 void bar() { 3488 X<char> x(1); 3489 } 3490 )", Lang_CXX11); 3491 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3492 FromTU, classTemplateSpecializationDecl(hasName("X"))); 3493 // Match the void(int) ctor. 3494 auto CtorPattern = 3495 cxxConstructorDecl(hasParameter(0, varDecl(hasType(asString("int")))), 3496 hasParent(classTemplateSpecializationDecl())); 3497 auto *FromCtor = 3498 FirstDeclMatcher<CXXConstructorDecl>().match(FromTU, CtorPattern); 3499 auto *ToCtor = 3500 FirstDeclMatcher<CXXConstructorDecl>().match(ToTU, CtorPattern); 3501 ASSERT_TRUE(FromCtor->hasBody()); 3502 ASSERT_FALSE(ToCtor->hasBody()); 3503 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3504 ASSERT_TRUE(ImportedSpec); 3505 auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3506 ToTU, classTemplateSpecializationDecl(hasName("X"))); 3507 EXPECT_EQ(ImportedSpec, ToSpec); 3508 EXPECT_TRUE(ToCtor->hasBody()); 3509 } 3510 3511 TEST_P(ASTImporterOptionSpecificTestBase, ClassTemplateFriendDecl) { 3512 const auto *Code = 3513 R"( 3514 template <class T> class X { friend T; }; 3515 struct Y {}; 3516 template class X<Y>; 3517 )"; 3518 Decl *ToTU = getToTuDecl(Code, Lang_CXX11); 3519 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 3520 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3521 FromTU, classTemplateSpecializationDecl()); 3522 auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3523 ToTU, classTemplateSpecializationDecl()); 3524 3525 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3526 EXPECT_EQ(ImportedSpec, ToSpec); 3527 EXPECT_EQ(1u, DeclCounter<ClassTemplateSpecializationDecl>().match( 3528 ToTU, classTemplateSpecializationDecl())); 3529 } 3530 3531 TEST_P(ASTImporterOptionSpecificTestBase, 3532 ClassTemplatePartialSpecializationsShouldNotBeDuplicated) { 3533 auto Code = 3534 R"( 3535 // primary template 3536 template<class T1, class T2, int I> 3537 class A {}; 3538 3539 // partial specialization 3540 template<class T, int I> 3541 class A<T, T*, I> {}; 3542 )"; 3543 Decl *ToTU = getToTuDecl(Code, Lang_CXX11); 3544 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 3545 auto *FromSpec = 3546 FirstDeclMatcher<ClassTemplatePartialSpecializationDecl>().match( 3547 FromTU, classTemplatePartialSpecializationDecl()); 3548 auto *ToSpec = 3549 FirstDeclMatcher<ClassTemplatePartialSpecializationDecl>().match( 3550 ToTU, classTemplatePartialSpecializationDecl()); 3551 3552 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3553 EXPECT_EQ(ImportedSpec, ToSpec); 3554 EXPECT_EQ(1u, DeclCounter<ClassTemplatePartialSpecializationDecl>().match( 3555 ToTU, classTemplatePartialSpecializationDecl())); 3556 } 3557 3558 TEST_P(ASTImporterOptionSpecificTestBase, 3559 ClassTemplateSpecializationsShouldNotBeDuplicated) { 3560 auto Code = 3561 R"( 3562 // primary template 3563 template<class T1, class T2, int I> 3564 class A {}; 3565 3566 // full specialization 3567 template<> 3568 class A<int, int, 1> {}; 3569 )"; 3570 Decl *ToTU = getToTuDecl(Code, Lang_CXX11); 3571 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 3572 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3573 FromTU, classTemplateSpecializationDecl()); 3574 auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3575 ToTU, classTemplateSpecializationDecl()); 3576 3577 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3578 EXPECT_EQ(ImportedSpec, ToSpec); 3579 EXPECT_EQ(1u, DeclCounter<ClassTemplateSpecializationDecl>().match( 3580 ToTU, classTemplateSpecializationDecl())); 3581 } 3582 3583 TEST_P(ASTImporterOptionSpecificTestBase, 3584 ClassTemplateFullAndPartialSpecsShouldNotBeMixed) { 3585 std::string PrimaryTemplate = 3586 R"( 3587 template<class T1, class T2, int I> 3588 class A {}; 3589 )"; 3590 auto PartialSpec = 3591 R"( 3592 template<class T, int I> 3593 class A<T, T*, I> {}; 3594 )"; 3595 auto FullSpec = 3596 R"( 3597 template<> 3598 class A<int, int, 1> {}; 3599 )"; 3600 Decl *ToTU = getToTuDecl(PrimaryTemplate + FullSpec, Lang_CXX11); 3601 Decl *FromTU = getTuDecl(PrimaryTemplate + PartialSpec, Lang_CXX11); 3602 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3603 FromTU, classTemplateSpecializationDecl()); 3604 3605 auto *ImportedSpec = Import(FromSpec, Lang_CXX11); 3606 EXPECT_TRUE(ImportedSpec); 3607 // Check the number of partial specializations. 3608 EXPECT_EQ(1u, DeclCounter<ClassTemplatePartialSpecializationDecl>().match( 3609 ToTU, classTemplatePartialSpecializationDecl())); 3610 // Check the number of full specializations. 3611 EXPECT_EQ(1u, DeclCounter<ClassTemplateSpecializationDecl>().match( 3612 ToTU, classTemplateSpecializationDecl( 3613 unless(classTemplatePartialSpecializationDecl())))); 3614 } 3615 3616 TEST_P(ASTImporterOptionSpecificTestBase, 3617 InitListExprValueKindShouldBeImported) { 3618 Decl *TU = getTuDecl( 3619 R"( 3620 const int &init(); 3621 void foo() { const int &a{init()}; } 3622 )", Lang_CXX11, "input0.cc"); 3623 auto *FromD = FirstDeclMatcher<VarDecl>().match(TU, varDecl(hasName("a"))); 3624 ASSERT_TRUE(FromD->getAnyInitializer()); 3625 auto *InitExpr = FromD->getAnyInitializer(); 3626 ASSERT_TRUE(InitExpr); 3627 ASSERT_TRUE(InitExpr->isGLValue()); 3628 3629 auto *ToD = Import(FromD, Lang_CXX11); 3630 EXPECT_TRUE(ToD); 3631 auto *ToInitExpr = cast<VarDecl>(ToD)->getAnyInitializer(); 3632 EXPECT_TRUE(ToInitExpr); 3633 EXPECT_TRUE(ToInitExpr->isGLValue()); 3634 } 3635 3636 struct ImportVariables : ASTImporterOptionSpecificTestBase {}; 3637 3638 TEST_P(ImportVariables, ImportOfOneDeclBringsInTheWholeChain) { 3639 Decl *FromTU = getTuDecl( 3640 R"( 3641 struct A { 3642 static const int a = 1 + 2; 3643 }; 3644 const int A::a; 3645 )", 3646 Lang_CXX03, "input1.cc"); 3647 3648 auto *FromDWithInit = FirstDeclMatcher<VarDecl>().match( 3649 FromTU, varDecl(hasName("a"))); // Decl with init 3650 auto *FromDWithDef = LastDeclMatcher<VarDecl>().match( 3651 FromTU, varDecl(hasName("a"))); // Decl with definition 3652 ASSERT_NE(FromDWithInit, FromDWithDef); 3653 ASSERT_EQ(FromDWithDef->getPreviousDecl(), FromDWithInit); 3654 3655 auto *ToD0 = cast<VarDecl>(Import(FromDWithInit, Lang_CXX11)); 3656 auto *ToD1 = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11)); 3657 ASSERT_TRUE(ToD0); 3658 ASSERT_TRUE(ToD1); 3659 EXPECT_NE(ToD0, ToD1); 3660 EXPECT_EQ(ToD1->getPreviousDecl(), ToD0); 3661 } 3662 3663 TEST_P(ImportVariables, InitAndDefinitionAreInDifferentTUs) { 3664 auto StructA = 3665 R"( 3666 struct A { 3667 static const int a = 1 + 2; 3668 }; 3669 )"; 3670 Decl *ToTU = getToTuDecl(StructA, Lang_CXX03); 3671 Decl *FromTU = getTuDecl(std::string(StructA) + "const int A::a;", Lang_CXX03, 3672 "input1.cc"); 3673 3674 auto *FromDWithInit = FirstDeclMatcher<VarDecl>().match( 3675 FromTU, varDecl(hasName("a"))); // Decl with init 3676 auto *FromDWithDef = LastDeclMatcher<VarDecl>().match( 3677 FromTU, varDecl(hasName("a"))); // Decl with definition 3678 ASSERT_EQ(FromDWithInit, FromDWithDef->getPreviousDecl()); 3679 ASSERT_TRUE(FromDWithInit->getInit()); 3680 ASSERT_FALSE(FromDWithInit->isThisDeclarationADefinition()); 3681 ASSERT_TRUE(FromDWithDef->isThisDeclarationADefinition()); 3682 ASSERT_FALSE(FromDWithDef->getInit()); 3683 3684 auto *ToD = FirstDeclMatcher<VarDecl>().match( 3685 ToTU, varDecl(hasName("a"))); // Decl with init 3686 ASSERT_TRUE(ToD->getInit()); 3687 ASSERT_FALSE(ToD->getDefinition()); 3688 3689 auto *ImportedD = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11)); 3690 EXPECT_TRUE(ImportedD->getAnyInitializer()); 3691 EXPECT_TRUE(ImportedD->getDefinition()); 3692 } 3693 3694 TEST_P(ImportVariables, InitAndDefinitionAreInTheFromContext) { 3695 auto StructA = 3696 R"( 3697 struct A { 3698 static const int a; 3699 }; 3700 )"; 3701 Decl *ToTU = getToTuDecl(StructA, Lang_CXX03); 3702 Decl *FromTU = getTuDecl(std::string(StructA) + "const int A::a = 1 + 2;", 3703 Lang_CXX03, "input1.cc"); 3704 3705 auto *FromDDeclarationOnly = FirstDeclMatcher<VarDecl>().match( 3706 FromTU, varDecl(hasName("a"))); 3707 auto *FromDWithDef = LastDeclMatcher<VarDecl>().match( 3708 FromTU, varDecl(hasName("a"))); // Decl with definition and with init. 3709 ASSERT_EQ(FromDDeclarationOnly, FromDWithDef->getPreviousDecl()); 3710 ASSERT_FALSE(FromDDeclarationOnly->getInit()); 3711 ASSERT_FALSE(FromDDeclarationOnly->isThisDeclarationADefinition()); 3712 ASSERT_TRUE(FromDWithDef->isThisDeclarationADefinition()); 3713 ASSERT_TRUE(FromDWithDef->getInit()); 3714 3715 auto *ToD = FirstDeclMatcher<VarDecl>().match( 3716 ToTU, varDecl(hasName("a"))); 3717 ASSERT_FALSE(ToD->getInit()); 3718 ASSERT_FALSE(ToD->getDefinition()); 3719 3720 auto *ImportedD = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11)); 3721 EXPECT_TRUE(ImportedD->getAnyInitializer()); 3722 EXPECT_TRUE(ImportedD->getDefinition()); 3723 } 3724 3725 TEST_P(ImportVariables, ImportBindingDecl) { 3726 Decl *From, *To; 3727 std::tie(From, To) = getImportedDecl( 3728 R"( 3729 void declToImport() { 3730 int a[2] = {1,2}; 3731 auto [x1,y1] = a; 3732 auto& [x2,y2] = a; 3733 3734 struct S { 3735 mutable int x1 : 2; 3736 volatile double y1; 3737 }; 3738 S b; 3739 const auto [x3, y3] = b; 3740 }; 3741 )", 3742 Lang_CXX17, "", Lang_CXX17); 3743 3744 TranslationUnitDecl *FromTU = From->getTranslationUnitDecl(); 3745 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 3746 FromTU, functionDecl(hasName("declToImport"))); 3747 auto *ToF = Import(FromF, Lang_CXX17); 3748 EXPECT_TRUE(ToF); 3749 3750 auto VerifyImport = [&](llvm::StringRef BindName) { 3751 auto *FromB = FirstDeclMatcher<BindingDecl>().match( 3752 FromF, bindingDecl(hasName(BindName))); 3753 ASSERT_TRUE(FromB); 3754 auto *ToB = Import(FromB, Lang_CXX17); 3755 EXPECT_TRUE(ToB); 3756 EXPECT_EQ(FromB->getBinding() != nullptr, ToB->getBinding() != nullptr); 3757 EXPECT_EQ(FromB->getDecomposedDecl() != nullptr, 3758 ToB->getDecomposedDecl() != nullptr); 3759 EXPECT_EQ(FromB->getHoldingVar() != nullptr, 3760 ToB->getHoldingVar() != nullptr); 3761 }; 3762 3763 VerifyImport("x1"); 3764 VerifyImport("y1"); 3765 VerifyImport("x2"); 3766 VerifyImport("y2"); 3767 VerifyImport("x3"); 3768 VerifyImport("y3"); 3769 } 3770 3771 TEST_P(ImportVariables, ImportDecompositionDeclArray) { 3772 Decl *From, *To; 3773 std::tie(From, To) = getImportedDecl( 3774 R"( 3775 void declToImport() { 3776 int a[2] = {1,2}; 3777 auto [x1,y1] = a; 3778 }; 3779 )", 3780 Lang_CXX17, "", Lang_CXX17); 3781 3782 TranslationUnitDecl *FromTU = From->getTranslationUnitDecl(); 3783 auto *FromDecomp = 3784 FirstDeclMatcher<DecompositionDecl>().match(FromTU, decompositionDecl()); 3785 auto *ToDecomp = Import(FromDecomp, Lang_CXX17); 3786 EXPECT_TRUE(ToDecomp); 3787 3788 ArrayRef<BindingDecl *> FromB = FromDecomp->bindings(); 3789 ArrayRef<BindingDecl *> ToB = ToDecomp->bindings(); 3790 EXPECT_EQ(FromB.size(), ToB.size()); 3791 for (unsigned int I = 0; I < FromB.size(); ++I) { 3792 auto *ToBI = Import(FromB[I], Lang_CXX17); 3793 EXPECT_EQ(ToBI, ToB[I]); 3794 } 3795 } 3796 3797 struct ImportClasses : ASTImporterOptionSpecificTestBase {}; 3798 3799 TEST_P(ImportClasses, ImportDefinitionWhenProtoIsInNestedToContext) { 3800 Decl *ToTU = getToTuDecl("struct A { struct X *Xp; };", Lang_C99); 3801 Decl *FromTU1 = getTuDecl("struct X {};", Lang_C99, "input1.cc"); 3802 auto Pattern = recordDecl(hasName("X"), unless(isImplicit())); 3803 auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3804 auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern); 3805 3806 Decl *ImportedDef = Import(FromDef, Lang_C99); 3807 3808 EXPECT_NE(ImportedDef, ToProto); 3809 EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u); 3810 auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3811 EXPECT_TRUE(ImportedDef == ToDef); 3812 EXPECT_TRUE(ToDef->isThisDeclarationADefinition()); 3813 EXPECT_FALSE(ToProto->isThisDeclarationADefinition()); 3814 EXPECT_EQ(ToDef->getPreviousDecl(), ToProto); 3815 } 3816 3817 TEST_P(ImportClasses, ImportDefinitionWhenProtoIsInNestedToContextCXX) { 3818 Decl *ToTU = getToTuDecl("struct A { struct X *Xp; };", Lang_CXX03); 3819 Decl *FromTU1 = getTuDecl("struct X {};", Lang_CXX03, "input1.cc"); 3820 auto Pattern = recordDecl(hasName("X"), unless(isImplicit())); 3821 auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3822 auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern); 3823 3824 Decl *ImportedDef = Import(FromDef, Lang_CXX03); 3825 3826 EXPECT_NE(ImportedDef, ToProto); 3827 EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u); 3828 auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3829 EXPECT_TRUE(ImportedDef == ToDef); 3830 EXPECT_TRUE(ToDef->isThisDeclarationADefinition()); 3831 EXPECT_FALSE(ToProto->isThisDeclarationADefinition()); 3832 EXPECT_EQ(ToDef->getPreviousDecl(), ToProto); 3833 } 3834 3835 TEST_P(ImportClasses, ImportNestedPrototypeThenDefinition) { 3836 Decl *FromTU0 = 3837 getTuDecl("struct A { struct X *Xp; };", Lang_C99, "input0.cc"); 3838 Decl *FromTU1 = getTuDecl("struct X {};", Lang_C99, "input1.cc"); 3839 auto Pattern = recordDecl(hasName("X"), unless(isImplicit())); 3840 auto FromProto = FirstDeclMatcher<RecordDecl>().match(FromTU0, Pattern); 3841 auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern); 3842 3843 Decl *ImportedProto = Import(FromProto, Lang_C99); 3844 Decl *ImportedDef = Import(FromDef, Lang_C99); 3845 Decl *ToTU = ImportedDef->getTranslationUnitDecl(); 3846 3847 EXPECT_NE(ImportedDef, ImportedProto); 3848 EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u); 3849 auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3850 auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern); 3851 EXPECT_TRUE(ImportedDef == ToDef); 3852 EXPECT_TRUE(ImportedProto == ToProto); 3853 EXPECT_TRUE(ToDef->isThisDeclarationADefinition()); 3854 EXPECT_FALSE(ToProto->isThisDeclarationADefinition()); 3855 EXPECT_EQ(ToDef->getPreviousDecl(), ToProto); 3856 } 3857 3858 3859 struct ImportFriendClasses : ASTImporterOptionSpecificTestBase {}; 3860 3861 TEST_P(ImportFriendClasses, ImportOfFriendRecordDoesNotMergeDefinition) { 3862 Decl *FromTU = getTuDecl( 3863 R"( 3864 class A { 3865 template <int I> class F {}; 3866 class X { 3867 template <int I> friend class F; 3868 }; 3869 }; 3870 )", 3871 Lang_CXX03, "input0.cc"); 3872 3873 auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match( 3874 FromTU, cxxRecordDecl(hasName("F"), isDefinition())); 3875 auto *FromFriendClass = LastDeclMatcher<CXXRecordDecl>().match( 3876 FromTU, cxxRecordDecl(hasName("F"))); 3877 3878 ASSERT_TRUE(FromClass); 3879 ASSERT_TRUE(FromFriendClass); 3880 ASSERT_NE(FromClass, FromFriendClass); 3881 ASSERT_EQ(FromFriendClass->getDefinition(), FromClass); 3882 ASSERT_EQ(FromFriendClass->getPreviousDecl(), FromClass); 3883 ASSERT_EQ(FromFriendClass->getDescribedClassTemplate()->getPreviousDecl(), 3884 FromClass->getDescribedClassTemplate()); 3885 3886 auto *ToClass = cast<CXXRecordDecl>(Import(FromClass, Lang_CXX03)); 3887 auto *ToFriendClass = 3888 cast<CXXRecordDecl>(Import(FromFriendClass, Lang_CXX03)); 3889 3890 EXPECT_TRUE(ToClass); 3891 EXPECT_TRUE(ToFriendClass); 3892 EXPECT_NE(ToClass, ToFriendClass); 3893 EXPECT_EQ(ToFriendClass->getDefinition(), ToClass); 3894 EXPECT_EQ(ToFriendClass->getPreviousDecl(), ToClass); 3895 EXPECT_EQ(ToFriendClass->getDescribedClassTemplate()->getPreviousDecl(), 3896 ToClass->getDescribedClassTemplate()); 3897 } 3898 3899 TEST_P(ImportFriendClasses, ImportOfRecursiveFriendClass) { 3900 Decl *FromTu = getTuDecl( 3901 R"( 3902 class declToImport { 3903 friend class declToImport; 3904 }; 3905 )", 3906 Lang_CXX03, "input.cc"); 3907 3908 auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match( 3909 FromTu, cxxRecordDecl(hasName("declToImport"))); 3910 auto *ToD = Import(FromD, Lang_CXX03); 3911 auto Pattern = cxxRecordDecl(has(friendDecl())); 3912 ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromD, Pattern)); 3913 EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToD, Pattern)); 3914 } 3915 3916 TEST_P(ImportFriendClasses, UndeclaredFriendClassShouldNotBeVisible) { 3917 Decl *FromTu = 3918 getTuDecl("class X { friend class Y; };", Lang_CXX03, "from.cc"); 3919 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 3920 FromTu, cxxRecordDecl(hasName("X"))); 3921 auto *FromFriend = FirstDeclMatcher<FriendDecl>().match(FromTu, friendDecl()); 3922 RecordDecl *FromRecordOfFriend = 3923 const_cast<RecordDecl *>(getRecordDeclOfFriend(FromFriend)); 3924 3925 ASSERT_EQ(FromRecordOfFriend->getDeclContext(), cast<DeclContext>(FromTu)); 3926 ASSERT_EQ(FromRecordOfFriend->getLexicalDeclContext(), 3927 cast<DeclContext>(FromX)); 3928 ASSERT_FALSE( 3929 FromRecordOfFriend->getDeclContext()->containsDecl(FromRecordOfFriend)); 3930 ASSERT_FALSE(FromRecordOfFriend->getLexicalDeclContext()->containsDecl( 3931 FromRecordOfFriend)); 3932 ASSERT_FALSE(FromRecordOfFriend->getLookupParent() 3933 ->lookup(FromRecordOfFriend->getDeclName()) 3934 .empty()); 3935 3936 auto *ToX = Import(FromX, Lang_CXX03); 3937 ASSERT_TRUE(ToX); 3938 3939 Decl *ToTu = ToX->getTranslationUnitDecl(); 3940 auto *ToFriend = FirstDeclMatcher<FriendDecl>().match(ToTu, friendDecl()); 3941 RecordDecl *ToRecordOfFriend = 3942 const_cast<RecordDecl *>(getRecordDeclOfFriend(ToFriend)); 3943 3944 ASSERT_EQ(ToRecordOfFriend->getDeclContext(), cast<DeclContext>(ToTu)); 3945 ASSERT_EQ(ToRecordOfFriend->getLexicalDeclContext(), cast<DeclContext>(ToX)); 3946 EXPECT_FALSE( 3947 ToRecordOfFriend->getDeclContext()->containsDecl(ToRecordOfFriend)); 3948 EXPECT_FALSE(ToRecordOfFriend->getLexicalDeclContext()->containsDecl( 3949 ToRecordOfFriend)); 3950 EXPECT_FALSE(ToRecordOfFriend->getLookupParent() 3951 ->lookup(ToRecordOfFriend->getDeclName()) 3952 .empty()); 3953 } 3954 3955 TEST_P(ImportFriendClasses, ImportOfRecursiveFriendClassTemplate) { 3956 Decl *FromTu = getTuDecl( 3957 R"( 3958 template<class A> class declToImport { 3959 template<class A1> friend class declToImport; 3960 }; 3961 )", 3962 Lang_CXX03, "input.cc"); 3963 3964 auto *FromD = 3965 FirstDeclMatcher<ClassTemplateDecl>().match(FromTu, classTemplateDecl()); 3966 auto *ToD = Import(FromD, Lang_CXX03); 3967 3968 auto Pattern = classTemplateDecl( 3969 has(cxxRecordDecl(has(friendDecl(has(classTemplateDecl())))))); 3970 ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromD, Pattern)); 3971 EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToD, Pattern)); 3972 3973 auto *Class = 3974 FirstDeclMatcher<ClassTemplateDecl>().match(ToD, classTemplateDecl()); 3975 auto *Friend = FirstDeclMatcher<FriendDecl>().match(ToD, friendDecl()); 3976 EXPECT_NE(Friend->getFriendDecl(), Class); 3977 EXPECT_EQ(Friend->getFriendDecl()->getPreviousDecl(), Class); 3978 } 3979 3980 TEST_P(ImportFriendClasses, ProperPrevDeclForClassTemplateDecls) { 3981 auto Pattern = classTemplateSpecializationDecl(hasName("X")); 3982 3983 ClassTemplateSpecializationDecl *Imported1; 3984 { 3985 Decl *FromTU = getTuDecl("template<class T> class X;" 3986 "struct Y { friend class X<int>; };", 3987 Lang_CXX03, "input0.cc"); 3988 auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 3989 FromTU, Pattern); 3990 3991 Imported1 = 3992 cast<ClassTemplateSpecializationDecl>(Import(FromD, Lang_CXX03)); 3993 } 3994 ClassTemplateSpecializationDecl *Imported2; 3995 { 3996 Decl *FromTU = getTuDecl("template<class T> class X;" 3997 "template<> class X<int>{};" 3998 "struct Z { friend class X<int>; };", 3999 Lang_CXX03, "input1.cc"); 4000 auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 4001 FromTU, Pattern); 4002 4003 Imported2 = 4004 cast<ClassTemplateSpecializationDecl>(Import(FromD, Lang_CXX03)); 4005 } 4006 4007 Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4008 EXPECT_EQ(DeclCounter<ClassTemplateSpecializationDecl>().match(ToTU, Pattern), 4009 2u); 4010 ASSERT_TRUE(Imported2->getPreviousDecl()); 4011 EXPECT_EQ(Imported2->getPreviousDecl(), Imported1); 4012 } 4013 4014 TEST_P(ImportFriendClasses, TypeForDeclShouldBeSetInTemplated) { 4015 Decl *FromTU0 = getTuDecl( 4016 R"( 4017 class X { 4018 class Y; 4019 }; 4020 class X::Y { 4021 template <typename T> 4022 friend class F; // The decl context of F is the global namespace. 4023 }; 4024 )", 4025 Lang_CXX03, "input0.cc"); 4026 auto *Fwd = FirstDeclMatcher<ClassTemplateDecl>().match( 4027 FromTU0, classTemplateDecl(hasName("F"))); 4028 auto *Imported0 = cast<ClassTemplateDecl>(Import(Fwd, Lang_CXX03)); 4029 Decl *FromTU1 = getTuDecl( 4030 R"( 4031 template <typename T> 4032 class F {}; 4033 )", 4034 Lang_CXX03, "input1.cc"); 4035 auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match( 4036 FromTU1, classTemplateDecl(hasName("F"))); 4037 auto *Imported1 = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX03)); 4038 EXPECT_EQ(Imported0->getTemplatedDecl()->getTypeForDecl(), 4039 Imported1->getTemplatedDecl()->getTypeForDecl()); 4040 } 4041 4042 TEST_P(ImportFriendClasses, DeclsFromFriendsShouldBeInRedeclChains) { 4043 Decl *From, *To; 4044 std::tie(From, To) = 4045 getImportedDecl("class declToImport {};", Lang_CXX03, 4046 "class Y { friend class declToImport; };", Lang_CXX03); 4047 auto *Imported = cast<CXXRecordDecl>(To); 4048 4049 EXPECT_TRUE(Imported->getPreviousDecl()); 4050 } 4051 4052 TEST_P(ImportFriendClasses, 4053 ImportOfClassTemplateDefinitionShouldConnectToFwdFriend) { 4054 Decl *ToTU = getToTuDecl( 4055 R"( 4056 class X { 4057 class Y; 4058 }; 4059 class X::Y { 4060 template <typename T> 4061 friend class F; // The decl context of F is the global namespace. 4062 }; 4063 )", 4064 Lang_CXX03); 4065 auto *ToDecl = FirstDeclMatcher<ClassTemplateDecl>().match( 4066 ToTU, classTemplateDecl(hasName("F"))); 4067 Decl *FromTU = getTuDecl( 4068 R"( 4069 template <typename T> 4070 class F {}; 4071 )", 4072 Lang_CXX03, "input0.cc"); 4073 auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match( 4074 FromTU, classTemplateDecl(hasName("F"))); 4075 auto *ImportedDef = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX03)); 4076 EXPECT_TRUE(ImportedDef->getPreviousDecl()); 4077 EXPECT_EQ(ToDecl, ImportedDef->getPreviousDecl()); 4078 EXPECT_EQ(ToDecl->getTemplatedDecl(), 4079 ImportedDef->getTemplatedDecl()->getPreviousDecl()); 4080 } 4081 4082 TEST_P(ImportFriendClasses, 4083 ImportOfClassTemplateDefinitionAndFwdFriendShouldBeLinked) { 4084 Decl *FromTU0 = getTuDecl( 4085 R"( 4086 class X { 4087 class Y; 4088 }; 4089 class X::Y { 4090 template <typename T> 4091 friend class F; // The decl context of F is the global namespace. 4092 }; 4093 )", 4094 Lang_CXX03, "input0.cc"); 4095 auto *Fwd = FirstDeclMatcher<ClassTemplateDecl>().match( 4096 FromTU0, classTemplateDecl(hasName("F"))); 4097 auto *ImportedFwd = cast<ClassTemplateDecl>(Import(Fwd, Lang_CXX03)); 4098 Decl *FromTU1 = getTuDecl( 4099 R"( 4100 template <typename T> 4101 class F {}; 4102 )", 4103 Lang_CXX03, "input1.cc"); 4104 auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match( 4105 FromTU1, classTemplateDecl(hasName("F"))); 4106 auto *ImportedDef = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX03)); 4107 EXPECT_TRUE(ImportedDef->getPreviousDecl()); 4108 EXPECT_EQ(ImportedFwd, ImportedDef->getPreviousDecl()); 4109 EXPECT_EQ(ImportedFwd->getTemplatedDecl(), 4110 ImportedDef->getTemplatedDecl()->getPreviousDecl()); 4111 } 4112 4113 TEST_P(ImportFriendClasses, ImportOfClassDefinitionAndFwdFriendShouldBeLinked) { 4114 Decl *FromTU0 = getTuDecl( 4115 R"( 4116 class X { 4117 class Y; 4118 }; 4119 class X::Y { 4120 friend class F; // The decl context of F is the global namespace. 4121 }; 4122 )", 4123 Lang_CXX03, "input0.cc"); 4124 auto *Friend = FirstDeclMatcher<FriendDecl>().match(FromTU0, friendDecl()); 4125 QualType FT = Friend->getFriendType()->getType(); 4126 FT = FromTU0->getASTContext().getCanonicalType(FT); 4127 auto *Fwd = cast<TagType>(FT)->getDecl(); 4128 auto *ImportedFwd = Import(Fwd, Lang_CXX03); 4129 Decl *FromTU1 = getTuDecl( 4130 R"( 4131 class F {}; 4132 )", 4133 Lang_CXX03, "input1.cc"); 4134 auto *Definition = FirstDeclMatcher<CXXRecordDecl>().match( 4135 FromTU1, cxxRecordDecl(hasName("F"))); 4136 auto *ImportedDef = Import(Definition, Lang_CXX03); 4137 EXPECT_TRUE(ImportedDef->getPreviousDecl()); 4138 EXPECT_EQ(ImportedFwd, ImportedDef->getPreviousDecl()); 4139 } 4140 4141 TEST_P(ImportFriendClasses, ImportOfRepeatedFriendType) { 4142 const char *Code = 4143 R"( 4144 class Container { 4145 friend class X; 4146 friend class X; 4147 }; 4148 )"; 4149 Decl *ToTu = getToTuDecl(Code, Lang_CXX03); 4150 Decl *FromTu = getTuDecl(Code, Lang_CXX03, "from.cc"); 4151 4152 auto *ToFriend1 = FirstDeclMatcher<FriendDecl>().match(ToTu, friendDecl()); 4153 auto *ToFriend2 = LastDeclMatcher<FriendDecl>().match(ToTu, friendDecl()); 4154 auto *FromFriend1 = 4155 FirstDeclMatcher<FriendDecl>().match(FromTu, friendDecl()); 4156 auto *FromFriend2 = LastDeclMatcher<FriendDecl>().match(FromTu, friendDecl()); 4157 4158 FriendDecl *ToImportedFriend1 = Import(FromFriend1, Lang_CXX03); 4159 FriendDecl *ToImportedFriend2 = Import(FromFriend2, Lang_CXX03); 4160 4161 EXPECT_NE(ToImportedFriend1, ToImportedFriend2); 4162 EXPECT_EQ(ToFriend1, ToImportedFriend1); 4163 EXPECT_EQ(ToFriend2, ToImportedFriend2); 4164 } 4165 4166 TEST_P(ImportFriendClasses, ImportOfRepeatedFriendDecl) { 4167 const char *Code = 4168 R"( 4169 class Container { 4170 friend void f(); 4171 friend void f(); 4172 }; 4173 )"; 4174 Decl *ToTu = getToTuDecl(Code, Lang_CXX03); 4175 Decl *FromTu = getTuDecl(Code, Lang_CXX03, "from.cc"); 4176 4177 auto *ToFriend1 = FirstDeclMatcher<FriendDecl>().match(ToTu, friendDecl()); 4178 auto *ToFriend2 = LastDeclMatcher<FriendDecl>().match(ToTu, friendDecl()); 4179 auto *FromFriend1 = 4180 FirstDeclMatcher<FriendDecl>().match(FromTu, friendDecl()); 4181 auto *FromFriend2 = LastDeclMatcher<FriendDecl>().match(FromTu, friendDecl()); 4182 4183 FriendDecl *ToImportedFriend1 = Import(FromFriend1, Lang_CXX03); 4184 FriendDecl *ToImportedFriend2 = Import(FromFriend2, Lang_CXX03); 4185 4186 EXPECT_NE(ToImportedFriend1, ToImportedFriend2); 4187 EXPECT_EQ(ToFriend1, ToImportedFriend1); 4188 EXPECT_EQ(ToFriend2, ToImportedFriend2); 4189 } 4190 4191 TEST_P(ASTImporterOptionSpecificTestBase, FriendFunInClassTemplate) { 4192 auto *Code = R"( 4193 template <class T> 4194 struct X { 4195 friend void foo(){} 4196 }; 4197 )"; 4198 TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX03); 4199 auto *ToFoo = FirstDeclMatcher<FunctionDecl>().match( 4200 ToTU, functionDecl(hasName("foo"))); 4201 4202 TranslationUnitDecl *FromTU = getTuDecl(Code, Lang_CXX03, "input.cc"); 4203 auto *FromFoo = FirstDeclMatcher<FunctionDecl>().match( 4204 FromTU, functionDecl(hasName("foo"))); 4205 auto *ImportedFoo = Import(FromFoo, Lang_CXX03); 4206 EXPECT_EQ(ImportedFoo, ToFoo); 4207 } 4208 4209 struct DeclContextTest : ASTImporterOptionSpecificTestBase {}; 4210 4211 TEST_P(DeclContextTest, removeDeclOfClassTemplateSpecialization) { 4212 Decl *TU = getTuDecl( 4213 R"( 4214 namespace NS { 4215 4216 template <typename T> 4217 struct S {}; 4218 template struct S<int>; 4219 4220 inline namespace INS { 4221 template <typename T> 4222 struct S {}; 4223 template struct S<int>; 4224 } 4225 4226 } 4227 )", Lang_CXX11, "input0.cc"); 4228 auto *NS = FirstDeclMatcher<NamespaceDecl>().match( 4229 TU, namespaceDecl()); 4230 auto *Spec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 4231 TU, classTemplateSpecializationDecl()); 4232 ASSERT_TRUE(NS->containsDecl(Spec)); 4233 4234 NS->removeDecl(Spec); 4235 EXPECT_FALSE(NS->containsDecl(Spec)); 4236 } 4237 4238 TEST_P(DeclContextTest, 4239 removeDeclShouldNotFailEvenIfWeHaveExternalVisibleStorage) { 4240 Decl *TU = getTuDecl("extern int A; int A;", Lang_CXX03); 4241 auto *A0 = FirstDeclMatcher<VarDecl>().match(TU, varDecl(hasName("A"))); 4242 auto *A1 = LastDeclMatcher<VarDecl>().match(TU, varDecl(hasName("A"))); 4243 4244 // Investigate the list. 4245 auto *DC = A0->getDeclContext(); 4246 ASSERT_TRUE(DC->containsDecl(A0)); 4247 ASSERT_TRUE(DC->containsDecl(A1)); 4248 4249 // Investigate the lookup table. 4250 auto *Map = DC->getLookupPtr(); 4251 ASSERT_TRUE(Map); 4252 auto I = Map->find(A0->getDeclName()); 4253 ASSERT_NE(I, Map->end()); 4254 StoredDeclsList &L = I->second; 4255 // The lookup table contains the most recent decl of A. 4256 ASSERT_NE(L.getAsDecl(), A0); 4257 ASSERT_EQ(L.getAsDecl(), A1); 4258 4259 ASSERT_TRUE(L.getAsDecl()); 4260 // Simulate the private function DeclContext::reconcileExternalVisibleStorage. 4261 // We do not have a list with one element. 4262 L.setHasExternalDecls(); 4263 ASSERT_FALSE(L.getAsList()); 4264 auto Results = L.getLookupResult(); 4265 ASSERT_EQ(1u, std::distance(Results.begin(), Results.end())); 4266 4267 // This asserts in the old implementation. 4268 DC->removeDecl(A0); 4269 EXPECT_FALSE(DC->containsDecl(A0)); 4270 } 4271 4272 struct ImportFunctionTemplateSpecializations 4273 : ASTImporterOptionSpecificTestBase {}; 4274 4275 TEST_P(ImportFunctionTemplateSpecializations, 4276 TUshouldNotContainFunctionTemplateImplicitInstantiation) { 4277 4278 Decl *FromTU = getTuDecl( 4279 R"( 4280 template<class T> 4281 int f() { return 0; } 4282 void foo() { f<int>(); } 4283 )", 4284 Lang_CXX03, "input0.cc"); 4285 4286 // Check that the function template instantiation is NOT the child of the TU. 4287 auto Pattern = translationUnitDecl( 4288 unless(has(functionDecl(hasName("f"), isTemplateInstantiation())))); 4289 ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern)); 4290 4291 auto *Foo = FirstDeclMatcher<FunctionDecl>().match( 4292 FromTU, functionDecl(hasName("foo"))); 4293 ASSERT_TRUE(Import(Foo, Lang_CXX03)); 4294 4295 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4296 EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern)); 4297 } 4298 4299 TEST_P(ImportFunctionTemplateSpecializations, 4300 TUshouldNotContainFunctionTemplateExplicitInstantiation) { 4301 4302 Decl *FromTU = getTuDecl( 4303 R"( 4304 template<class T> 4305 int f() { return 0; } 4306 template int f<int>(); 4307 )", 4308 Lang_CXX03, "input0.cc"); 4309 4310 // Check that the function template instantiation is NOT the child of the TU. 4311 auto Instantiation = functionDecl(hasName("f"), isTemplateInstantiation()); 4312 auto Pattern = translationUnitDecl(unless(has(Instantiation))); 4313 ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern)); 4314 4315 ASSERT_TRUE(Import(FirstDeclMatcher<Decl>().match(FromTU, Instantiation), 4316 Lang_CXX03)); 4317 4318 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4319 EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern)); 4320 } 4321 4322 TEST_P(ImportFunctionTemplateSpecializations, 4323 TUshouldContainFunctionTemplateSpecialization) { 4324 4325 Decl *FromTU = getTuDecl( 4326 R"( 4327 template<class T> 4328 int f() { return 0; } 4329 template <> int f<int>() { return 4; } 4330 )", 4331 Lang_CXX03, "input0.cc"); 4332 4333 // Check that the function template specialization is the child of the TU. 4334 auto Specialization = 4335 functionDecl(hasName("f"), isExplicitTemplateSpecialization()); 4336 auto Pattern = translationUnitDecl(has(Specialization)); 4337 ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern)); 4338 4339 ASSERT_TRUE(Import(FirstDeclMatcher<Decl>().match(FromTU, Specialization), 4340 Lang_CXX03)); 4341 4342 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4343 EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern)); 4344 } 4345 4346 TEST_P(ImportFunctionTemplateSpecializations, 4347 FunctionTemplateSpecializationRedeclChain) { 4348 4349 Decl *FromTU = getTuDecl( 4350 R"( 4351 template<class T> 4352 int f() { return 0; } 4353 template <> int f<int>() { return 4; } 4354 )", 4355 Lang_CXX03, "input0.cc"); 4356 4357 auto Spec = functionDecl(hasName("f"), isExplicitTemplateSpecialization(), 4358 hasParent(translationUnitDecl())); 4359 auto *FromSpecD = FirstDeclMatcher<Decl>().match(FromTU, Spec); 4360 { 4361 auto *TU = FromTU; 4362 auto *SpecD = FromSpecD; 4363 auto *TemplateD = FirstDeclMatcher<FunctionTemplateDecl>().match( 4364 TU, functionTemplateDecl()); 4365 auto *FirstSpecD = *(TemplateD->spec_begin()); 4366 ASSERT_EQ(SpecD, FirstSpecD); 4367 ASSERT_TRUE(SpecD->getPreviousDecl()); 4368 ASSERT_FALSE(cast<FunctionDecl>(SpecD->getPreviousDecl()) 4369 ->doesThisDeclarationHaveABody()); 4370 } 4371 4372 ASSERT_TRUE(Import(FromSpecD, Lang_CXX03)); 4373 4374 { 4375 auto *TU = ToAST->getASTContext().getTranslationUnitDecl(); 4376 auto *SpecD = FirstDeclMatcher<Decl>().match(TU, Spec); 4377 auto *TemplateD = FirstDeclMatcher<FunctionTemplateDecl>().match( 4378 TU, functionTemplateDecl()); 4379 auto *FirstSpecD = *(TemplateD->spec_begin()); 4380 EXPECT_EQ(SpecD, FirstSpecD); 4381 ASSERT_TRUE(SpecD->getPreviousDecl()); 4382 EXPECT_FALSE(cast<FunctionDecl>(SpecD->getPreviousDecl()) 4383 ->doesThisDeclarationHaveABody()); 4384 } 4385 } 4386 4387 TEST_P(ImportFunctionTemplateSpecializations, 4388 MatchNumberOfFunctionTemplateSpecializations) { 4389 4390 Decl *FromTU = getTuDecl( 4391 R"( 4392 template <typename T> constexpr int f() { return 0; } 4393 template <> constexpr int f<int>() { return 4; } 4394 void foo() { 4395 static_assert(f<char>() == 0, ""); 4396 static_assert(f<int>() == 4, ""); 4397 } 4398 )", 4399 Lang_CXX11, "input0.cc"); 4400 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 4401 FromTU, functionDecl(hasName("foo"))); 4402 4403 Import(FromD, Lang_CXX11); 4404 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4405 EXPECT_EQ( 4406 DeclCounter<FunctionDecl>().match(FromTU, functionDecl(hasName("f"))), 4407 DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f")))); 4408 } 4409 4410 TEST_P(ASTImporterOptionSpecificTestBase, 4411 ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) { 4412 { 4413 Decl *FromTU = getTuDecl( 4414 R"( 4415 template <typename T> 4416 struct B; 4417 )", 4418 Lang_CXX03, "input0.cc"); 4419 auto *FromD = FirstDeclMatcher<ClassTemplateDecl>().match( 4420 FromTU, classTemplateDecl(hasName("B"))); 4421 4422 Import(FromD, Lang_CXX03); 4423 } 4424 4425 { 4426 Decl *FromTU = getTuDecl( 4427 R"( 4428 template <typename T> 4429 struct B { 4430 void f(); 4431 B* b; 4432 }; 4433 )", 4434 Lang_CXX03, "input1.cc"); 4435 FunctionDecl *FromD = FirstDeclMatcher<FunctionDecl>().match( 4436 FromTU, functionDecl(hasName("f"))); 4437 Import(FromD, Lang_CXX03); 4438 auto *FromCTD = FirstDeclMatcher<ClassTemplateDecl>().match( 4439 FromTU, classTemplateDecl(hasName("B"))); 4440 auto *ToCTD = cast<ClassTemplateDecl>(Import(FromCTD, Lang_CXX03)); 4441 EXPECT_TRUE(ToCTD->isThisDeclarationADefinition()); 4442 4443 // We expect no (ODR) warning during the import. 4444 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 4445 EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings()); 4446 } 4447 } 4448 4449 TEST_P(ASTImporterOptionSpecificTestBase, 4450 ImportingTypedefShouldImportTheCompleteType) { 4451 // We already have an incomplete underlying type in the "To" context. 4452 auto Code = 4453 R"( 4454 template <typename T> 4455 struct S { 4456 void foo(); 4457 }; 4458 using U = S<int>; 4459 )"; 4460 Decl *ToTU = getToTuDecl(Code, Lang_CXX11); 4461 auto *ToD = FirstDeclMatcher<TypedefNameDecl>().match(ToTU, 4462 typedefNameDecl(hasName("U"))); 4463 ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType()); 4464 4465 // The "From" context has the same typedef, but the underlying type is 4466 // complete this time. 4467 Decl *FromTU = getTuDecl(std::string(Code) + 4468 R"( 4469 void foo(U* u) { 4470 u->foo(); 4471 } 4472 )", Lang_CXX11); 4473 auto *FromD = FirstDeclMatcher<TypedefNameDecl>().match(FromTU, 4474 typedefNameDecl(hasName("U"))); 4475 ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType()); 4476 4477 // The imported type should be complete. 4478 auto *ImportedD = cast<TypedefNameDecl>(Import(FromD, Lang_CXX11)); 4479 EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType()); 4480 } 4481 4482 TEST_P(ASTImporterOptionSpecificTestBase, ImportTemplateParameterLists) { 4483 auto Code = 4484 R"( 4485 template<class T> 4486 int f() { return 0; } 4487 template <> int f<int>() { return 4; } 4488 )"; 4489 4490 Decl *FromTU = getTuDecl(Code, Lang_CXX03); 4491 auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, 4492 functionDecl(hasName("f"), isExplicitTemplateSpecialization())); 4493 ASSERT_EQ(FromD->getNumTemplateParameterLists(), 1u); 4494 4495 auto *ToD = Import(FromD, Lang_CXX03); 4496 // The template parameter list should exist. 4497 EXPECT_EQ(ToD->getNumTemplateParameterLists(), 1u); 4498 } 4499 4500 const internal::VariadicDynCastAllOfMatcher<Decl, VarTemplateDecl> 4501 varTemplateDecl; 4502 4503 const internal::VariadicDynCastAllOfMatcher< 4504 Decl, VarTemplatePartialSpecializationDecl> 4505 varTemplatePartialSpecializationDecl; 4506 4507 TEST_P(ASTImporterOptionSpecificTestBase, 4508 FunctionTemplateParameterDeclContext) { 4509 constexpr auto Code = 4510 R"( 4511 template<class T> 4512 void f() {}; 4513 )"; 4514 4515 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 4516 4517 auto *FromD = FirstDeclMatcher<FunctionTemplateDecl>().match( 4518 FromTU, functionTemplateDecl(hasName("f"))); 4519 4520 ASSERT_EQ(FromD->getTemplateParameters()->getParam(0)->getDeclContext(), 4521 FromD->getTemplatedDecl()); 4522 4523 auto *ToD = Import(FromD, Lang_CXX11); 4524 EXPECT_EQ(ToD->getTemplateParameters()->getParam(0)->getDeclContext(), 4525 ToD->getTemplatedDecl()); 4526 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4527 ToD->getTemplatedDecl(), ToD->getTemplateParameters()->getParam(0))); 4528 } 4529 4530 TEST_P(ASTImporterOptionSpecificTestBase, ClassTemplateParameterDeclContext) { 4531 constexpr auto Code = 4532 R"( 4533 template<class T1, class T2> 4534 struct S {}; 4535 template<class T2> 4536 struct S<int, T2> {}; 4537 )"; 4538 4539 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 4540 4541 auto *FromD = FirstDeclMatcher<ClassTemplateDecl>().match( 4542 FromTU, classTemplateDecl(hasName("S"))); 4543 auto *FromDPart = 4544 FirstDeclMatcher<ClassTemplatePartialSpecializationDecl>().match( 4545 FromTU, classTemplatePartialSpecializationDecl(hasName("S"))); 4546 4547 ASSERT_EQ(FromD->getTemplateParameters()->getParam(0)->getDeclContext(), 4548 FromD->getTemplatedDecl()); 4549 ASSERT_EQ(FromDPart->getTemplateParameters()->getParam(0)->getDeclContext(), 4550 FromDPart); 4551 4552 auto *ToD = Import(FromD, Lang_CXX11); 4553 auto *ToDPart = Import(FromDPart, Lang_CXX11); 4554 4555 EXPECT_EQ(ToD->getTemplateParameters()->getParam(0)->getDeclContext(), 4556 ToD->getTemplatedDecl()); 4557 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4558 ToD->getTemplatedDecl(), ToD->getTemplateParameters()->getParam(0))); 4559 4560 EXPECT_EQ(ToDPart->getTemplateParameters()->getParam(0)->getDeclContext(), 4561 ToDPart); 4562 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4563 ToDPart, ToDPart->getTemplateParameters()->getParam(0))); 4564 } 4565 4566 TEST_P(ASTImporterOptionSpecificTestBase, 4567 CXXDeductionGuideTemplateParameterDeclContext) { 4568 Decl *FromTU = getTuDecl( 4569 R"( 4570 template <typename T> struct A { 4571 A(T); 4572 }; 4573 A a{(int)0}; 4574 )", 4575 Lang_CXX17, "input.cc"); 4576 // clang-format off 4577 /* 4578 |-ClassTemplateDecl 0x1fe5000 <input.cc:2:7, line:4:7> line:2:36 A 4579 | |-TemplateTypeParmDecl 0x1fe4eb0 <col:17, col:26> col:26 referenced typename depth 0 index 0 T 4580 | |-CXXRecordDecl 0x1fe4f70 <col:29, line:4:7> line:2:36 struct A definition 4581 4582 |-FunctionTemplateDecl 0x1fe5860 <line:2:7, line:3:12> col:9 implicit <deduction guide for A> 4583 | |-TemplateTypeParmDecl 0x1fe4eb0 <line:2:17, col:26> col:26 referenced typename depth 0 index 0 T 4584 | |-CXXDeductionGuideDecl 0x1fe57a8 <line:3:9, col:12> col:9 implicit <deduction guide for A> 'auto (T) -> A<T>' 4585 | | `-ParmVarDecl 0x1fe56b0 <col:11> col:12 'T' 4586 | `-CXXDeductionGuideDecl 0x20515d8 <col:9, col:12> col:9 implicit used <deduction guide for A> 'auto (int) -> A<int>' 4587 | |-TemplateArgument type 'int' 4588 | | `-BuiltinType 0x20587e0 'int' 4589 | `-ParmVarDecl 0x2051388 <col:11> col:12 'int':'int' 4590 `-FunctionTemplateDecl 0x1fe5a78 <line:2:7, col:36> col:36 implicit <deduction guide for A> 4591 |-TemplateTypeParmDecl 0x1fe4eb0 <col:17, col:26> col:26 referenced typename depth 0 index 0 T 4592 `-CXXDeductionGuideDecl 0x1fe59c0 <col:36> col:36 implicit <deduction guide for A> 'auto (A<T>) -> A<T>' 4593 `-ParmVarDecl 0x1fe5958 <col:36> col:36 'A<T>' 4594 */ 4595 // clang-format on 4596 auto *FromD1 = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 4597 FromTU, cxxDeductionGuideDecl()); 4598 auto *FromD2 = LastDeclMatcher<CXXDeductionGuideDecl>().match( 4599 FromTU, cxxDeductionGuideDecl()); 4600 4601 NamedDecl *P1 = 4602 FromD1->getDescribedFunctionTemplate()->getTemplateParameters()->getParam( 4603 0); 4604 NamedDecl *P2 = 4605 FromD2->getDescribedFunctionTemplate()->getTemplateParameters()->getParam( 4606 0); 4607 DeclContext *DC = P1->getDeclContext(); 4608 4609 ASSERT_EQ(P1, P2); 4610 ASSERT_TRUE(DC == FromD1 || DC == FromD2); 4611 4612 auto *ToD1 = Import(FromD1, Lang_CXX17); 4613 auto *ToD2 = Import(FromD2, Lang_CXX17); 4614 ASSERT_TRUE(ToD1 && ToD2); 4615 4616 P1 = ToD1->getDescribedFunctionTemplate()->getTemplateParameters()->getParam( 4617 0); 4618 P2 = ToD2->getDescribedFunctionTemplate()->getTemplateParameters()->getParam( 4619 0); 4620 DC = P1->getDeclContext(); 4621 4622 EXPECT_EQ(P1, P2); 4623 EXPECT_TRUE(DC == ToD1 || DC == ToD2); 4624 4625 ASTImporterLookupTable *Tbl = SharedStatePtr->getLookupTable(); 4626 if (Tbl->contains(ToD1, P1)) { 4627 EXPECT_FALSE(Tbl->contains(ToD2, P1)); 4628 } else { 4629 EXPECT_TRUE(Tbl->contains(ToD2, P1)); 4630 } 4631 } 4632 4633 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) { 4634 constexpr auto Code = 4635 R"( 4636 template<class T1, class T2> 4637 int X1; 4638 template<class T2> 4639 int X1<int, T2>; 4640 4641 namespace Ns { 4642 template<class T1, class T2> 4643 int X2; 4644 template<class T2> 4645 int X2<int, T2>; 4646 } 4647 )"; 4648 4649 Decl *FromTU = getTuDecl(Code, Lang_CXX14); 4650 4651 auto *FromD1 = FirstDeclMatcher<VarTemplateDecl>().match( 4652 FromTU, varTemplateDecl(hasName("X1"))); 4653 auto *FromD1Part = 4654 FirstDeclMatcher<VarTemplatePartialSpecializationDecl>().match( 4655 FromTU, varTemplatePartialSpecializationDecl(hasName("X1"))); 4656 auto *FromD2 = FirstDeclMatcher<VarTemplateDecl>().match( 4657 FromTU, varTemplateDecl(hasName("X2"))); 4658 auto *FromD2Part = 4659 FirstDeclMatcher<VarTemplatePartialSpecializationDecl>().match( 4660 FromTU, varTemplatePartialSpecializationDecl(hasName("X2"))); 4661 4662 ASSERT_EQ(FromD1->getTemplateParameters()->getParam(0)->getDeclContext(), 4663 FromD1->getDeclContext()); 4664 ASSERT_EQ(FromD2->getTemplateParameters()->getParam(0)->getDeclContext(), 4665 FromD2->getDeclContext()); 4666 4667 ASSERT_EQ(FromD1Part->getTemplateParameters()->getParam(0)->getDeclContext(), 4668 FromD1Part->getDeclContext()); 4669 // FIXME: VarTemplatePartialSpecializationDecl does not update ("adopt") 4670 // template parameter decl context 4671 // ASSERT_EQ(FromD2Part->getTemplateParameters()->getParam(0)->getDeclContext(), 4672 // FromD2Part->getDeclContext()); 4673 4674 auto *ToD1 = Import(FromD1, Lang_CXX14); 4675 auto *ToD2 = Import(FromD2, Lang_CXX14); 4676 4677 auto *ToD1Part = Import(FromD1Part, Lang_CXX14); 4678 auto *ToD2Part = Import(FromD2Part, Lang_CXX14); 4679 4680 EXPECT_EQ(ToD1->getTemplateParameters()->getParam(0)->getDeclContext(), 4681 ToD1->getDeclContext()); 4682 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4683 ToD1->getDeclContext(), ToD1->getTemplateParameters()->getParam(0))); 4684 EXPECT_EQ(ToD2->getTemplateParameters()->getParam(0)->getDeclContext(), 4685 ToD2->getDeclContext()); 4686 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4687 ToD2->getDeclContext(), ToD2->getTemplateParameters()->getParam(0))); 4688 4689 EXPECT_EQ(ToD1Part->getTemplateParameters()->getParam(0)->getDeclContext(), 4690 ToD1Part->getDeclContext()); 4691 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4692 ToD1Part->getDeclContext(), 4693 ToD1Part->getTemplateParameters()->getParam(0))); 4694 // EXPECT_EQ(ToD2Part->getTemplateParameters()->getParam(0)->getDeclContext(), 4695 // ToD2Part->getDeclContext()); 4696 // EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4697 // ToD2Part->getDeclContext(), 4698 // ToD2Part->getTemplateParameters()->getParam(0))); 4699 (void)ToD2Part; 4700 } 4701 4702 TEST_P(ASTImporterOptionSpecificTestBase, 4703 TypeAliasTemplateParameterDeclContext) { 4704 constexpr auto Code = 4705 R"( 4706 template<class T1, class T2> 4707 struct S {}; 4708 template<class T> using S1 = S<T, int>; 4709 namespace Ns { 4710 template<class T> using S2 = S<T, int>; 4711 } 4712 )"; 4713 4714 Decl *FromTU = getTuDecl(Code, Lang_CXX11); 4715 4716 auto *FromD1 = FirstDeclMatcher<TypeAliasTemplateDecl>().match( 4717 FromTU, typeAliasTemplateDecl(hasName("S1"))); 4718 auto *FromD2 = FirstDeclMatcher<TypeAliasTemplateDecl>().match( 4719 FromTU, typeAliasTemplateDecl(hasName("S2"))); 4720 4721 ASSERT_EQ(FromD1->getTemplateParameters()->getParam(0)->getDeclContext(), 4722 FromD1->getDeclContext()); 4723 ASSERT_EQ(FromD2->getTemplateParameters()->getParam(0)->getDeclContext(), 4724 FromD2->getDeclContext()); 4725 4726 auto *ToD1 = Import(FromD1, Lang_CXX11); 4727 auto *ToD2 = Import(FromD2, Lang_CXX11); 4728 4729 EXPECT_EQ(ToD1->getTemplateParameters()->getParam(0)->getDeclContext(), 4730 ToD1->getDeclContext()); 4731 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4732 ToD1->getDeclContext(), ToD1->getTemplateParameters()->getParam(0))); 4733 EXPECT_EQ(ToD2->getTemplateParameters()->getParam(0)->getDeclContext(), 4734 ToD2->getDeclContext()); 4735 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 4736 ToD2->getDeclContext(), ToD2->getTemplateParameters()->getParam(0))); 4737 } 4738 4739 const AstTypeMatcher<SubstTemplateTypeParmPackType> 4740 substTemplateTypeParmPackType; 4741 4742 TEST_P(ASTImporterOptionSpecificTestBase, ImportSubstTemplateTypeParmPackType) { 4743 constexpr auto Code = R"( 4744 template<typename ...T> struct D { 4745 template<typename... U> using B = int(int (*...p)(T, U)); 4746 template<typename U1, typename U2> D(B<U1, U2>*); 4747 }; 4748 int f(int(int, int), int(int, int)); 4749 4750 using asd = D<float, double, float>::B<int, long, int>; 4751 )"; 4752 Decl *FromTU = getTuDecl(Code, Lang_CXX11, "input.cpp"); 4753 auto *FromClass = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 4754 FromTU, classTemplateSpecializationDecl()); 4755 4756 { 4757 ASTContext &FromCtx = FromTU->getASTContext(); 4758 const auto *FromSubstPack = selectFirst<SubstTemplateTypeParmPackType>( 4759 "pack", match(substTemplateTypeParmPackType().bind("pack"), FromCtx)); 4760 4761 ASSERT_TRUE(FromSubstPack); 4762 ASSERT_EQ(FromSubstPack->getIdentifier()->getName(), "T"); 4763 ArrayRef<TemplateArgument> FromArgPack = 4764 FromSubstPack->getArgumentPack().pack_elements(); 4765 ASSERT_EQ(FromArgPack.size(), 3u); 4766 ASSERT_EQ(FromArgPack[0].getAsType(), FromCtx.FloatTy); 4767 ASSERT_EQ(FromArgPack[1].getAsType(), FromCtx.DoubleTy); 4768 ASSERT_EQ(FromArgPack[2].getAsType(), FromCtx.FloatTy); 4769 } 4770 { 4771 // Let's do the import. 4772 ClassTemplateSpecializationDecl *ToClass = Import(FromClass, Lang_CXX11); 4773 ASTContext &ToCtx = ToClass->getASTContext(); 4774 4775 const auto *ToSubstPack = selectFirst<SubstTemplateTypeParmPackType>( 4776 "pack", match(substTemplateTypeParmPackType().bind("pack"), ToCtx)); 4777 4778 // Check if it meets the requirements. 4779 ASSERT_TRUE(ToSubstPack); 4780 ASSERT_EQ(ToSubstPack->getIdentifier()->getName(), "T"); 4781 ArrayRef<TemplateArgument> ToArgPack = 4782 ToSubstPack->getArgumentPack().pack_elements(); 4783 ASSERT_EQ(ToArgPack.size(), 3u); 4784 ASSERT_EQ(ToArgPack[0].getAsType(), ToCtx.FloatTy); 4785 ASSERT_EQ(ToArgPack[1].getAsType(), ToCtx.DoubleTy); 4786 ASSERT_EQ(ToArgPack[2].getAsType(), ToCtx.FloatTy); 4787 } 4788 } 4789 4790 struct ASTImporterLookupTableTest : ASTImporterOptionSpecificTestBase {}; 4791 4792 TEST_P(ASTImporterLookupTableTest, OneDecl) { 4793 auto *ToTU = getToTuDecl("int a;", Lang_CXX03); 4794 auto *D = FirstDeclMatcher<VarDecl>().match(ToTU, varDecl(hasName("a"))); 4795 ASTImporterLookupTable LT(*ToTU); 4796 auto Res = LT.lookup(ToTU, D->getDeclName()); 4797 ASSERT_EQ(Res.size(), 1u); 4798 EXPECT_EQ(*Res.begin(), D); 4799 } 4800 4801 static Decl *findInDeclListOfDC(DeclContext *DC, DeclarationName Name) { 4802 for (Decl *D : DC->decls()) { 4803 if (auto *ND = dyn_cast<NamedDecl>(D)) 4804 if (ND->getDeclName() == Name) 4805 return ND; 4806 } 4807 return nullptr; 4808 } 4809 4810 TEST_P(ASTImporterLookupTableTest, 4811 FriendWhichIsnotFoundByNormalLookupShouldBeFoundByImporterSpecificLookup) { 4812 auto *Code = R"( 4813 template <class T> 4814 struct X { 4815 friend void foo(){} 4816 }; 4817 )"; 4818 TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX03); 4819 auto *X = FirstDeclMatcher<ClassTemplateDecl>().match( 4820 ToTU, classTemplateDecl(hasName("X"))); 4821 auto *Foo = FirstDeclMatcher<FunctionDecl>().match( 4822 ToTU, functionDecl(hasName("foo"))); 4823 DeclContext *FooDC = Foo->getDeclContext(); 4824 DeclContext *FooLexicalDC = Foo->getLexicalDeclContext(); 4825 ASSERT_EQ(cast<Decl>(FooLexicalDC), X->getTemplatedDecl()); 4826 ASSERT_EQ(cast<Decl>(FooDC), ToTU); 4827 DeclarationName FooName = Foo->getDeclName(); 4828 4829 // Cannot find in the LookupTable of its DC (TUDecl) 4830 SmallVector<NamedDecl *, 2> FoundDecls; 4831 FooDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls); 4832 EXPECT_EQ(FoundDecls.size(), 0u); 4833 4834 // Cannot find in the LookupTable of its LexicalDC (X) 4835 FooLexicalDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls); 4836 EXPECT_EQ(FoundDecls.size(), 0u); 4837 4838 // Can't find in the list of Decls of the DC. 4839 EXPECT_EQ(findInDeclListOfDC(FooDC, FooName), nullptr); 4840 4841 // Can't find in the list of Decls of the LexicalDC 4842 EXPECT_EQ(findInDeclListOfDC(FooLexicalDC, FooName), nullptr); 4843 4844 // ASTImporter specific lookup finds it. 4845 ASTImporterLookupTable LT(*ToTU); 4846 auto Res = LT.lookup(FooDC, Foo->getDeclName()); 4847 ASSERT_EQ(Res.size(), 1u); 4848 EXPECT_EQ(*Res.begin(), Foo); 4849 } 4850 4851 TEST_P(ASTImporterLookupTableTest, 4852 FwdDeclStructShouldBeFoundByImporterSpecificLookup) { 4853 TranslationUnitDecl *ToTU = 4854 getToTuDecl("struct A { struct Foo *p; };", Lang_C99); 4855 auto *Foo = 4856 FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("Foo"))); 4857 auto *A = 4858 FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("A"))); 4859 DeclContext *FooDC = Foo->getDeclContext(); 4860 DeclContext *FooLexicalDC = Foo->getLexicalDeclContext(); 4861 ASSERT_EQ(cast<Decl>(FooLexicalDC), A); 4862 ASSERT_EQ(cast<Decl>(FooDC), ToTU); 4863 DeclarationName FooName = Foo->getDeclName(); 4864 4865 // Cannot find in the LookupTable of its DC (TUDecl). 4866 SmallVector<NamedDecl *, 2> FoundDecls; 4867 FooDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls); 4868 EXPECT_EQ(FoundDecls.size(), 0u); 4869 4870 // Cannot find in the LookupTable of its LexicalDC (A). 4871 FooLexicalDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls); 4872 EXPECT_EQ(FoundDecls.size(), 0u); 4873 4874 // Can't find in the list of Decls of the DC. 4875 EXPECT_EQ(findInDeclListOfDC(FooDC, FooName), nullptr); 4876 4877 // Can find in the list of Decls of the LexicalDC. 4878 EXPECT_EQ(findInDeclListOfDC(FooLexicalDC, FooName), Foo); 4879 4880 // ASTImporter specific lookup finds it. 4881 ASTImporterLookupTable LT(*ToTU); 4882 auto Res = LT.lookup(FooDC, Foo->getDeclName()); 4883 ASSERT_EQ(Res.size(), 1u); 4884 EXPECT_EQ(*Res.begin(), Foo); 4885 } 4886 4887 TEST_P(ASTImporterLookupTableTest, LookupFindsNamesInDifferentDC) { 4888 TranslationUnitDecl *ToTU = 4889 getToTuDecl("int V; struct A { int V; }; struct B { int V; };", Lang_C99); 4890 DeclarationName VName = FirstDeclMatcher<VarDecl>() 4891 .match(ToTU, varDecl(hasName("V"))) 4892 ->getDeclName(); 4893 auto *A = 4894 FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("A"))); 4895 auto *B = 4896 FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("B"))); 4897 4898 ASTImporterLookupTable LT(*ToTU); 4899 4900 auto Res = LT.lookup(cast<DeclContext>(A), VName); 4901 ASSERT_EQ(Res.size(), 1u); 4902 EXPECT_EQ(*Res.begin(), FirstDeclMatcher<FieldDecl>().match( 4903 ToTU, fieldDecl(hasName("V"), 4904 hasParent(recordDecl(hasName("A")))))); 4905 Res = LT.lookup(cast<DeclContext>(B), VName); 4906 ASSERT_EQ(Res.size(), 1u); 4907 EXPECT_EQ(*Res.begin(), FirstDeclMatcher<FieldDecl>().match( 4908 ToTU, fieldDecl(hasName("V"), 4909 hasParent(recordDecl(hasName("B")))))); 4910 Res = LT.lookup(ToTU, VName); 4911 ASSERT_EQ(Res.size(), 1u); 4912 EXPECT_EQ(*Res.begin(), FirstDeclMatcher<VarDecl>().match( 4913 ToTU, varDecl(hasName("V"), 4914 hasParent(translationUnitDecl())))); 4915 } 4916 4917 TEST_P(ASTImporterLookupTableTest, LookupFindsOverloadedNames) { 4918 TranslationUnitDecl *ToTU = getToTuDecl( 4919 R"( 4920 void foo(); 4921 void foo(int); 4922 void foo(int, int); 4923 )", 4924 Lang_CXX03); 4925 4926 ASTImporterLookupTable LT(*ToTU); 4927 auto *F0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl()); 4928 auto *F2 = LastDeclMatcher<FunctionDecl>().match(ToTU, functionDecl()); 4929 DeclarationName Name = F0->getDeclName(); 4930 auto Res = LT.lookup(ToTU, Name); 4931 EXPECT_EQ(Res.size(), 3u); 4932 EXPECT_EQ(Res.count(F0), 1u); 4933 EXPECT_EQ(Res.count(F2), 1u); 4934 } 4935 4936 TEST_P(ASTImporterLookupTableTest, 4937 DifferentOperatorsShouldHaveDifferentResultSet) { 4938 TranslationUnitDecl *ToTU = getToTuDecl( 4939 R"( 4940 struct X{}; 4941 void operator+(X, X); 4942 void operator-(X, X); 4943 )", 4944 Lang_CXX03); 4945 4946 ASTImporterLookupTable LT(*ToTU); 4947 auto *FPlus = FirstDeclMatcher<FunctionDecl>().match( 4948 ToTU, functionDecl(hasOverloadedOperatorName("+"))); 4949 auto *FMinus = FirstDeclMatcher<FunctionDecl>().match( 4950 ToTU, functionDecl(hasOverloadedOperatorName("-"))); 4951 DeclarationName NamePlus = FPlus->getDeclName(); 4952 auto ResPlus = LT.lookup(ToTU, NamePlus); 4953 EXPECT_EQ(ResPlus.size(), 1u); 4954 EXPECT_EQ(ResPlus.count(FPlus), 1u); 4955 EXPECT_EQ(ResPlus.count(FMinus), 0u); 4956 DeclarationName NameMinus = FMinus->getDeclName(); 4957 auto ResMinus = LT.lookup(ToTU, NameMinus); 4958 EXPECT_EQ(ResMinus.size(), 1u); 4959 EXPECT_EQ(ResMinus.count(FMinus), 1u); 4960 EXPECT_EQ(ResMinus.count(FPlus), 0u); 4961 EXPECT_NE(*ResMinus.begin(), *ResPlus.begin()); 4962 } 4963 4964 TEST_P(ASTImporterLookupTableTest, LookupDeclNamesFromDifferentTUs) { 4965 TranslationUnitDecl *ToTU = getToTuDecl( 4966 R"( 4967 struct X {}; 4968 void operator+(X, X); 4969 )", 4970 Lang_CXX03); 4971 auto *ToPlus = FirstDeclMatcher<FunctionDecl>().match( 4972 ToTU, functionDecl(hasOverloadedOperatorName("+"))); 4973 4974 Decl *FromTU = getTuDecl( 4975 R"( 4976 struct X {}; 4977 void operator+(X, X); 4978 )", 4979 Lang_CXX03); 4980 auto *FromPlus = FirstDeclMatcher<FunctionDecl>().match( 4981 FromTU, functionDecl(hasOverloadedOperatorName("+"))); 4982 4983 // FromPlus have a different TU, thus its DeclarationName is different too. 4984 ASSERT_NE(ToPlus->getDeclName(), FromPlus->getDeclName()); 4985 4986 ASTImporterLookupTable LT(*ToTU); 4987 auto Res = LT.lookup(ToTU, ToPlus->getDeclName()); 4988 ASSERT_EQ(Res.size(), 1u); 4989 EXPECT_EQ(*Res.begin(), ToPlus); 4990 4991 // FromPlus have a different TU, thus its DeclarationName is different too. 4992 Res = LT.lookup(ToTU, FromPlus->getDeclName()); 4993 ASSERT_EQ(Res.size(), 0u); 4994 } 4995 4996 TEST_P(ASTImporterLookupTableTest, 4997 LookupFindsFwdFriendClassDeclWithElaboratedType) { 4998 TranslationUnitDecl *ToTU = getToTuDecl( 4999 R"( 5000 class Y { friend class F; }; 5001 )", 5002 Lang_CXX03); 5003 5004 // In this case, the CXXRecordDecl is hidden, the FriendDecl is not a parent. 5005 // So we must dig up the underlying CXXRecordDecl. 5006 ASTImporterLookupTable LT(*ToTU); 5007 auto *FriendD = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl()); 5008 const RecordDecl *RD = getRecordDeclOfFriend(FriendD); 5009 auto *Y = FirstDeclMatcher<CXXRecordDecl>().match( 5010 ToTU, cxxRecordDecl(hasName("Y"))); 5011 5012 DeclarationName Name = RD->getDeclName(); 5013 auto Res = LT.lookup(ToTU, Name); 5014 EXPECT_EQ(Res.size(), 1u); 5015 EXPECT_EQ(*Res.begin(), RD); 5016 5017 Res = LT.lookup(Y, Name); 5018 EXPECT_EQ(Res.size(), 0u); 5019 } 5020 5021 TEST_P(ASTImporterLookupTableTest, 5022 LookupFindsFwdFriendClassDeclWithUnelaboratedType) { 5023 TranslationUnitDecl *ToTU = getToTuDecl( 5024 R"( 5025 class F; 5026 class Y { friend F; }; 5027 )", 5028 Lang_CXX11); 5029 5030 // In this case, the CXXRecordDecl is hidden, the FriendDecl is not a parent. 5031 // So we must dig up the underlying CXXRecordDecl. 5032 ASTImporterLookupTable LT(*ToTU); 5033 auto *FriendD = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl()); 5034 const RecordDecl *RD = getRecordDeclOfFriend(FriendD); 5035 auto *Y = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, cxxRecordDecl(hasName("Y"))); 5036 5037 DeclarationName Name = RD->getDeclName(); 5038 auto Res = LT.lookup(ToTU, Name); 5039 EXPECT_EQ(Res.size(), 1u); 5040 EXPECT_EQ(*Res.begin(), RD); 5041 5042 Res = LT.lookup(Y, Name); 5043 EXPECT_EQ(Res.size(), 0u); 5044 } 5045 5046 TEST_P(ASTImporterLookupTableTest, 5047 LookupFindsFriendClassDeclWithTypeAliasDoesNotAssert) { 5048 TranslationUnitDecl *ToTU = getToTuDecl( 5049 R"( 5050 class F; 5051 using alias_of_f = F; 5052 class Y { friend alias_of_f; }; 5053 )", 5054 Lang_CXX11); 5055 5056 // ASTImporterLookupTable constructor handles using declarations correctly, 5057 // no assert is expected. 5058 ASTImporterLookupTable LT(*ToTU); 5059 5060 auto *Alias = FirstDeclMatcher<TypeAliasDecl>().match( 5061 ToTU, typeAliasDecl(hasName("alias_of_f"))); 5062 DeclarationName Name = Alias->getDeclName(); 5063 auto Res = LT.lookup(ToTU, Name); 5064 EXPECT_EQ(Res.count(Alias), 1u); 5065 } 5066 5067 TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendClassTemplateDecl) { 5068 TranslationUnitDecl *ToTU = getToTuDecl( 5069 R"( 5070 class Y { template <class T> friend class F; }; 5071 )", 5072 Lang_CXX03); 5073 5074 ASTImporterLookupTable LT(*ToTU); 5075 auto *F = FirstDeclMatcher<ClassTemplateDecl>().match( 5076 ToTU, classTemplateDecl(hasName("F"))); 5077 DeclarationName Name = F->getDeclName(); 5078 auto Res = LT.lookup(ToTU, Name); 5079 EXPECT_EQ(Res.size(), 2u); 5080 EXPECT_EQ(Res.count(F), 1u); 5081 EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u); 5082 } 5083 5084 TEST_P(ASTImporterLookupTableTest, DependentFriendClass) { 5085 TranslationUnitDecl *ToTU = getToTuDecl( 5086 R"( 5087 template <typename T> 5088 class F; 5089 5090 template <typename T> 5091 class Y { 5092 friend class F<T>; 5093 }; 5094 )", 5095 Lang_CXX03); 5096 5097 ASTImporterLookupTable LT(*ToTU); 5098 auto *F = FirstDeclMatcher<ClassTemplateDecl>().match( 5099 ToTU, classTemplateDecl(hasName("F"))); 5100 DeclarationName Name = F->getDeclName(); 5101 auto Res = LT.lookup(ToTU, Name); 5102 EXPECT_EQ(Res.size(), 2u); 5103 EXPECT_EQ(Res.count(F), 1u); 5104 EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u); 5105 } 5106 5107 TEST_P(ASTImporterLookupTableTest, FriendClassTemplateSpecialization) { 5108 TranslationUnitDecl *ToTU = getToTuDecl( 5109 R"( 5110 template <typename T> 5111 class F; 5112 5113 class Y { 5114 friend class F<int>; 5115 }; 5116 )", 5117 Lang_CXX03); 5118 5119 ASTImporterLookupTable LT(*ToTU); 5120 auto *F = FirstDeclMatcher<ClassTemplateDecl>().match( 5121 ToTU, classTemplateDecl(hasName("F"))); 5122 DeclarationName Name = F->getDeclName(); 5123 auto Res = LT.lookup(ToTU, Name); 5124 ASSERT_EQ(Res.size(), 3u); 5125 EXPECT_EQ(Res.count(F), 1u); 5126 EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u); 5127 EXPECT_EQ(Res.count(*F->spec_begin()), 1u); 5128 } 5129 5130 TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendFunctionDecl) { 5131 TranslationUnitDecl *ToTU = getToTuDecl( 5132 R"( 5133 class Y { friend void F(); }; 5134 )", 5135 Lang_CXX03); 5136 5137 ASTImporterLookupTable LT(*ToTU); 5138 auto *F = 5139 FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl(hasName("F"))); 5140 DeclarationName Name = F->getDeclName(); 5141 auto Res = LT.lookup(ToTU, Name); 5142 EXPECT_EQ(Res.size(), 1u); 5143 EXPECT_EQ(*Res.begin(), F); 5144 } 5145 5146 TEST_P(ASTImporterLookupTableTest, 5147 LookupFindsDeclsInClassTemplateSpecialization) { 5148 TranslationUnitDecl *ToTU = getToTuDecl( 5149 R"( 5150 template <typename T> 5151 struct X { 5152 int F; 5153 }; 5154 void foo() { 5155 X<char> xc; 5156 } 5157 )", 5158 Lang_CXX03); 5159 5160 ASTImporterLookupTable LT(*ToTU); 5161 5162 auto *Template = FirstDeclMatcher<ClassTemplateDecl>().match( 5163 ToTU, classTemplateDecl(hasName("X"))); 5164 auto *FieldInTemplate = FirstDeclMatcher<FieldDecl>().match( 5165 ToTU, 5166 fieldDecl(hasParent(cxxRecordDecl(hasParent(classTemplateDecl()))))); 5167 5168 auto *Spec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 5169 ToTU, classTemplateSpecializationDecl(hasName("X"))); 5170 FieldDecl *FieldInSpec = *Spec->field_begin(); 5171 ASSERT_TRUE(FieldInSpec); 5172 5173 DeclarationName Name = FieldInSpec->getDeclName(); 5174 auto TemplateDC = cast<DeclContext>(Template->getTemplatedDecl()); 5175 5176 SmallVector<NamedDecl *, 2> FoundDecls; 5177 TemplateDC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); 5178 EXPECT_EQ(FoundDecls.size(), 1u); 5179 EXPECT_EQ(FoundDecls[0], FieldInTemplate); 5180 5181 auto Res = LT.lookup(TemplateDC, Name); 5182 ASSERT_EQ(Res.size(), 1u); 5183 EXPECT_EQ(*Res.begin(), FieldInTemplate); 5184 5185 cast<DeclContext>(Spec)->getRedeclContext()->localUncachedLookup(Name, 5186 FoundDecls); 5187 EXPECT_EQ(FoundDecls.size(), 1u); 5188 EXPECT_EQ(FoundDecls[0], FieldInSpec); 5189 5190 Res = LT.lookup(cast<DeclContext>(Spec), Name); 5191 ASSERT_EQ(Res.size(), 1u); 5192 EXPECT_EQ(*Res.begin(), FieldInSpec); 5193 } 5194 5195 TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendFunctionTemplateDecl) { 5196 TranslationUnitDecl *ToTU = getToTuDecl( 5197 R"( 5198 class Y { template <class T> friend void F(); }; 5199 )", 5200 Lang_CXX03); 5201 5202 ASTImporterLookupTable LT(*ToTU); 5203 auto *F = FirstDeclMatcher<FunctionTemplateDecl>().match( 5204 ToTU, functionTemplateDecl(hasName("F"))); 5205 DeclarationName Name = F->getDeclName(); 5206 auto Res = LT.lookup(ToTU, Name); 5207 EXPECT_EQ(Res.size(), 2u); 5208 EXPECT_EQ(Res.count(F), 1u); 5209 EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u); 5210 } 5211 5212 TEST_P(ASTImporterLookupTableTest, MultipleBefriendingClasses) { 5213 TranslationUnitDecl *ToTU = getToTuDecl( 5214 R"( 5215 struct X; 5216 struct A { 5217 friend struct X; 5218 }; 5219 struct B { 5220 friend struct X; 5221 }; 5222 )", 5223 Lang_CXX03); 5224 5225 ASTImporterLookupTable LT(*ToTU); 5226 auto *X = FirstDeclMatcher<CXXRecordDecl>().match( 5227 ToTU, cxxRecordDecl(hasName("X"))); 5228 auto *FriendD0 = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl()); 5229 auto *FriendD1 = LastDeclMatcher<FriendDecl>().match(ToTU, friendDecl()); 5230 const RecordDecl *RD0 = getRecordDeclOfFriend(FriendD0); 5231 const RecordDecl *RD1 = getRecordDeclOfFriend(FriendD1); 5232 ASSERT_EQ(RD0, RD1); 5233 ASSERT_EQ(RD1, X); 5234 5235 DeclarationName Name = X->getDeclName(); 5236 auto Res = LT.lookup(ToTU, Name); 5237 EXPECT_EQ(Res.size(), 1u); 5238 EXPECT_EQ(*Res.begin(), X); 5239 } 5240 5241 TEST_P(ASTImporterLookupTableTest, EnumConstantDecl) { 5242 TranslationUnitDecl *ToTU = getToTuDecl( 5243 R"( 5244 enum E { 5245 A, 5246 B 5247 }; 5248 )", 5249 Lang_C99); 5250 5251 ASTImporterLookupTable LT(*ToTU); 5252 auto *E = FirstDeclMatcher<EnumDecl>().match(ToTU, enumDecl(hasName("E"))); 5253 auto *A = FirstDeclMatcher<EnumConstantDecl>().match( 5254 ToTU, enumConstantDecl(hasName("A"))); 5255 5256 DeclarationName Name = A->getDeclName(); 5257 // Redecl context is the TU. 5258 ASSERT_EQ(E->getRedeclContext(), ToTU); 5259 5260 SmallVector<NamedDecl *, 2> FoundDecls; 5261 // Normal lookup finds in the DC. 5262 E->localUncachedLookup(Name, FoundDecls); 5263 EXPECT_EQ(FoundDecls.size(), 1u); 5264 5265 // Normal lookup finds in the Redecl context. 5266 ToTU->localUncachedLookup(Name, FoundDecls); 5267 EXPECT_EQ(FoundDecls.size(), 1u); 5268 5269 // Import specific lookup finds in the DC. 5270 auto Res = LT.lookup(E, Name); 5271 ASSERT_EQ(Res.size(), 1u); 5272 EXPECT_EQ(*Res.begin(), A); 5273 5274 // Import specific lookup finds in the Redecl context. 5275 Res = LT.lookup(ToTU, Name); 5276 ASSERT_EQ(Res.size(), 1u); 5277 EXPECT_EQ(*Res.begin(), A); 5278 } 5279 5280 TEST_P(ASTImporterLookupTableTest, LookupSearchesInTheWholeRedeclChain) { 5281 TranslationUnitDecl *ToTU = getToTuDecl( 5282 R"( 5283 namespace N { 5284 int A; 5285 } 5286 namespace N { 5287 } 5288 )", 5289 Lang_CXX03); 5290 auto *N1 = 5291 LastDeclMatcher<NamespaceDecl>().match(ToTU, namespaceDecl(hasName("N"))); 5292 auto *A = FirstDeclMatcher<VarDecl>().match(ToTU, varDecl(hasName("A"))); 5293 DeclarationName Name = A->getDeclName(); 5294 5295 ASTImporterLookupTable LT(*ToTU); 5296 auto Res = LT.lookup(N1, Name); 5297 ASSERT_EQ(Res.size(), 1u); 5298 EXPECT_EQ(*Res.begin(), A); 5299 } 5300 5301 TEST_P(ASTImporterOptionSpecificTestBase, 5302 RedeclChainShouldBeCorrectAmongstNamespaces) { 5303 Decl *FromTU = getTuDecl( 5304 R"( 5305 namespace NS { 5306 struct X; 5307 struct Y { 5308 static const int I = 3; 5309 }; 5310 } 5311 namespace NS { 5312 struct X { // <--- To be imported 5313 void method(int i = Y::I) {} 5314 int f; 5315 }; 5316 } 5317 )", 5318 Lang_CXX03); 5319 auto *FromFwd = FirstDeclMatcher<CXXRecordDecl>().match( 5320 FromTU, cxxRecordDecl(hasName("X"), unless(isImplicit()))); 5321 auto *FromDef = LastDeclMatcher<CXXRecordDecl>().match( 5322 FromTU, 5323 cxxRecordDecl(hasName("X"), isDefinition(), unless(isImplicit()))); 5324 ASSERT_NE(FromFwd, FromDef); 5325 ASSERT_FALSE(FromFwd->isThisDeclarationADefinition()); 5326 ASSERT_TRUE(FromDef->isThisDeclarationADefinition()); 5327 ASSERT_EQ(FromFwd->getCanonicalDecl(), FromDef->getCanonicalDecl()); 5328 5329 auto *ToDef = cast_or_null<CXXRecordDecl>(Import(FromDef, Lang_CXX03)); 5330 auto *ToFwd = cast_or_null<CXXRecordDecl>(Import(FromFwd, Lang_CXX03)); 5331 EXPECT_NE(ToFwd, ToDef); 5332 EXPECT_FALSE(ToFwd->isThisDeclarationADefinition()); 5333 EXPECT_TRUE(ToDef->isThisDeclarationADefinition()); 5334 EXPECT_EQ(ToFwd->getCanonicalDecl(), ToDef->getCanonicalDecl()); 5335 auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 5336 // We expect no (ODR) warning during the import. 5337 EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings()); 5338 } 5339 5340 struct ImportFriendFunctionTemplates : ASTImporterOptionSpecificTestBase {}; 5341 5342 TEST_P(ImportFriendFunctionTemplates, LookupShouldFindPreviousFriend) { 5343 Decl *ToTU = getToTuDecl( 5344 R"( 5345 class X { 5346 template <typename T> friend void foo(); 5347 }; 5348 )", 5349 Lang_CXX03); 5350 auto *Friend = FirstDeclMatcher<FunctionTemplateDecl>().match( 5351 ToTU, functionTemplateDecl(hasName("foo"))); 5352 5353 Decl *FromTU = getTuDecl( 5354 R"( 5355 template <typename T> void foo(); 5356 )", 5357 Lang_CXX03); 5358 auto *FromFoo = FirstDeclMatcher<FunctionTemplateDecl>().match( 5359 FromTU, functionTemplateDecl(hasName("foo"))); 5360 auto *Imported = Import(FromFoo, Lang_CXX03); 5361 5362 EXPECT_EQ(Imported->getPreviousDecl(), Friend); 5363 } 5364 5365 struct ASTImporterWithFakeErrors : ASTImporter { 5366 using ASTImporter::ASTImporter; 5367 bool returnWithErrorInTest() override { return true; } 5368 }; 5369 5370 struct ErrorHandlingTest : ASTImporterOptionSpecificTestBase { 5371 ErrorHandlingTest() { 5372 Creator = [](ASTContext &ToContext, FileManager &ToFileManager, 5373 ASTContext &FromContext, FileManager &FromFileManager, 5374 bool MinimalImport, 5375 const std::shared_ptr<ASTImporterSharedState> &SharedState) { 5376 return new ASTImporterWithFakeErrors(ToContext, ToFileManager, 5377 FromContext, FromFileManager, 5378 MinimalImport, SharedState); 5379 }; 5380 } 5381 // In this test we purposely report an error (UnsupportedConstruct) when 5382 // importing the below stmt. 5383 static constexpr auto* ErroneousStmt = R"( asm(""); )"; 5384 }; 5385 5386 // Check a case when no new AST node is created in the AST before encountering 5387 // the error. 5388 TEST_P(ErrorHandlingTest, ErrorHappensBeforeCreatingANewNode) { 5389 TranslationUnitDecl *ToTU = getToTuDecl( 5390 R"( 5391 template <typename T> 5392 class X {}; 5393 template <> 5394 class X<int> { int a; }; 5395 )", 5396 Lang_CXX03); 5397 TranslationUnitDecl *FromTU = getTuDecl( 5398 R"( 5399 template <typename T> 5400 class X {}; 5401 template <> 5402 class X<int> { double b; }; 5403 )", 5404 Lang_CXX03); 5405 auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match( 5406 FromTU, classTemplateSpecializationDecl(hasName("X"))); 5407 ClassTemplateSpecializationDecl *ImportedSpec = Import(FromSpec, Lang_CXX03); 5408 EXPECT_FALSE(ImportedSpec); 5409 5410 // The original Decl is kept, no new decl is created. 5411 EXPECT_EQ(DeclCounter<ClassTemplateSpecializationDecl>().match( 5412 ToTU, classTemplateSpecializationDecl(hasName("X"))), 5413 1u); 5414 5415 // But an error is set to the counterpart in the "from" context. 5416 ASTImporter *Importer = findFromTU(FromSpec)->Importer.get(); 5417 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromSpec); 5418 ASSERT_TRUE(OptErr); 5419 EXPECT_EQ(OptErr->Error, ImportError::NameConflict); 5420 } 5421 5422 // Check a case when a new AST node is created but not linked to the AST before 5423 // encountering the error. 5424 TEST_P(ErrorHandlingTest, 5425 ErrorHappensAfterCreatingTheNodeButBeforeLinkingThatToTheAST) { 5426 TranslationUnitDecl *FromTU = getTuDecl( 5427 std::string("void foo() { ") + ErroneousStmt + " }", Lang_CXX03); 5428 auto *FromFoo = FirstDeclMatcher<FunctionDecl>().match( 5429 FromTU, functionDecl(hasName("foo"))); 5430 5431 FunctionDecl *ImportedFoo = Import(FromFoo, Lang_CXX03); 5432 EXPECT_FALSE(ImportedFoo); 5433 5434 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 5435 // Created, but not linked. 5436 EXPECT_EQ( 5437 DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("foo"))), 5438 0u); 5439 5440 ASTImporter *Importer = findFromTU(FromFoo)->Importer.get(); 5441 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFoo); 5442 ASSERT_TRUE(OptErr); 5443 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5444 } 5445 5446 // Check a case when a new AST node is created and linked to the AST before 5447 // encountering the error. The error is set for the counterpart of the nodes in 5448 // the "from" context. 5449 TEST_P(ErrorHandlingTest, ErrorHappensAfterNodeIsCreatedAndLinked) { 5450 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5451 void f(); 5452 void f() { )") + ErroneousStmt + R"( } 5453 )", 5454 Lang_CXX03); 5455 auto *FromProto = FirstDeclMatcher<FunctionDecl>().match( 5456 FromTU, functionDecl(hasName("f"))); 5457 auto *FromDef = 5458 LastDeclMatcher<FunctionDecl>().match(FromTU, functionDecl(hasName("f"))); 5459 FunctionDecl *ImportedProto = Import(FromProto, Lang_CXX03); 5460 EXPECT_FALSE(ImportedProto); // Could not import. 5461 // However, we created two nodes in the AST. 1) the fwd decl 2) the 5462 // definition. The definition is not added to its DC, but the fwd decl is 5463 // there. 5464 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 5465 EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))), 5466 1u); 5467 // Match the fwd decl. 5468 auto *ToProto = 5469 FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))); 5470 EXPECT_TRUE(ToProto); 5471 // An error is set to the counterpart in the "from" context both for the fwd 5472 // decl and the definition. 5473 ASTImporter *Importer = findFromTU(FromProto)->Importer.get(); 5474 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromProto); 5475 ASSERT_TRUE(OptErr); 5476 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5477 OptErr = Importer->getImportDeclErrorIfAny(FromDef); 5478 ASSERT_TRUE(OptErr); 5479 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5480 } 5481 5482 // An error should be set for a class if we cannot import one member. 5483 TEST_P(ErrorHandlingTest, ErrorIsPropagatedFromMemberToClass) { 5484 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5485 class X { 5486 void f() { )") + ErroneousStmt + R"( } // This member has the error 5487 // during import. 5488 void ok(); // The error should not prevent importing this. 5489 }; // An error will be set for X too. 5490 )", 5491 Lang_CXX03); 5492 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 5493 FromTU, cxxRecordDecl(hasName("X"))); 5494 CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX03); 5495 5496 // An error is set for X. 5497 EXPECT_FALSE(ImportedX); 5498 ASTImporter *Importer = findFromTU(FromX)->Importer.get(); 5499 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); 5500 ASSERT_TRUE(OptErr); 5501 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5502 5503 // An error is set for f(). 5504 auto *FromF = FirstDeclMatcher<CXXMethodDecl>().match( 5505 FromTU, cxxMethodDecl(hasName("f"))); 5506 OptErr = Importer->getImportDeclErrorIfAny(FromF); 5507 ASSERT_TRUE(OptErr); 5508 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5509 // And any subsequent import should fail. 5510 CXXMethodDecl *ImportedF = Import(FromF, Lang_CXX03); 5511 EXPECT_FALSE(ImportedF); 5512 5513 // There is an error set for the other member too. 5514 auto *FromOK = FirstDeclMatcher<CXXMethodDecl>().match( 5515 FromTU, cxxMethodDecl(hasName("ok"))); 5516 OptErr = Importer->getImportDeclErrorIfAny(FromOK); 5517 EXPECT_TRUE(OptErr); 5518 // Cannot import the other member. 5519 CXXMethodDecl *ImportedOK = Import(FromOK, Lang_CXX03); 5520 EXPECT_FALSE(ImportedOK); 5521 } 5522 5523 // Check that an error propagates to the dependent AST nodes. 5524 // In the below code it means that an error in X should propagate to A. 5525 // And even to F since the containing A is erroneous. 5526 // And to all AST nodes which we visit during the import process which finally 5527 // ends up in a failure (in the error() function). 5528 TEST_P(ErrorHandlingTest, ErrorPropagatesThroughImportCycles) { 5529 Decl *FromTU = getTuDecl(std::string(R"( 5530 namespace NS { 5531 class A { 5532 template <int I> class F {}; 5533 class X { 5534 template <int I> friend class F; 5535 void error() { )") + 5536 ErroneousStmt + R"( } 5537 }; 5538 }; 5539 5540 class B {}; 5541 } // NS 5542 )", 5543 Lang_CXX03, "input0.cc"); 5544 5545 auto *FromFRD = FirstDeclMatcher<CXXRecordDecl>().match( 5546 FromTU, cxxRecordDecl(hasName("F"), isDefinition())); 5547 auto *FromA = FirstDeclMatcher<CXXRecordDecl>().match( 5548 FromTU, cxxRecordDecl(hasName("A"), isDefinition())); 5549 auto *FromB = FirstDeclMatcher<CXXRecordDecl>().match( 5550 FromTU, cxxRecordDecl(hasName("B"), isDefinition())); 5551 auto *FromNS = FirstDeclMatcher<NamespaceDecl>().match( 5552 FromTU, namespaceDecl(hasName("NS"))); 5553 5554 // Start by importing the templated CXXRecordDecl of F. 5555 // Import fails for that. 5556 EXPECT_FALSE(Import(FromFRD, Lang_CXX03)); 5557 // Import fails for A. 5558 EXPECT_FALSE(Import(FromA, Lang_CXX03)); 5559 // But we should be able to import the independent B. 5560 EXPECT_TRUE(Import(FromB, Lang_CXX03)); 5561 // And the namespace. 5562 EXPECT_TRUE(Import(FromNS, Lang_CXX03)); 5563 5564 // An error is set to the templated CXXRecordDecl of F. 5565 ASTImporter *Importer = findFromTU(FromFRD)->Importer.get(); 5566 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFRD); 5567 EXPECT_TRUE(OptErr); 5568 5569 // An error is set to A. 5570 OptErr = Importer->getImportDeclErrorIfAny(FromA); 5571 EXPECT_TRUE(OptErr); 5572 5573 // There is no error set to B. 5574 OptErr = Importer->getImportDeclErrorIfAny(FromB); 5575 EXPECT_FALSE(OptErr); 5576 5577 // There is no error set to NS. 5578 OptErr = Importer->getImportDeclErrorIfAny(FromNS); 5579 EXPECT_FALSE(OptErr); 5580 5581 // Check some of those decls whose ancestor is X, they all should have an 5582 // error set if we visited them during an import process which finally failed. 5583 // These decls are part of a cycle in an ImportPath. 5584 // There would not be any error set for these decls if we hadn't follow the 5585 // ImportPaths and the cycles. 5586 OptErr = Importer->getImportDeclErrorIfAny( 5587 FirstDeclMatcher<ClassTemplateDecl>().match( 5588 FromTU, classTemplateDecl(hasName("F")))); 5589 // An error is set to the 'F' ClassTemplateDecl. 5590 EXPECT_TRUE(OptErr); 5591 // An error is set to the FriendDecl. 5592 OptErr = Importer->getImportDeclErrorIfAny( 5593 FirstDeclMatcher<FriendDecl>().match( 5594 FromTU, friendDecl())); 5595 EXPECT_TRUE(OptErr); 5596 // An error is set to the implicit class of A. 5597 OptErr = 5598 Importer->getImportDeclErrorIfAny(FirstDeclMatcher<CXXRecordDecl>().match( 5599 FromTU, cxxRecordDecl(hasName("A"), isImplicit()))); 5600 EXPECT_TRUE(OptErr); 5601 // An error is set to the implicit class of X. 5602 OptErr = 5603 Importer->getImportDeclErrorIfAny(FirstDeclMatcher<CXXRecordDecl>().match( 5604 FromTU, cxxRecordDecl(hasName("X"), isImplicit()))); 5605 EXPECT_TRUE(OptErr); 5606 } 5607 5608 TEST_P(ErrorHandlingTest, ErrorIsNotPropagatedFromMemberToNamespace) { 5609 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5610 namespace X { 5611 void f() { )") + ErroneousStmt + R"( } // This member has the error 5612 // during import. 5613 void ok(); // The error should not prevent importing this. 5614 }; // An error will be set for X too. 5615 )", 5616 Lang_CXX03); 5617 auto *FromX = FirstDeclMatcher<NamespaceDecl>().match( 5618 FromTU, namespaceDecl(hasName("X"))); 5619 NamespaceDecl *ImportedX = Import(FromX, Lang_CXX03); 5620 5621 // There is no error set for X. 5622 EXPECT_TRUE(ImportedX); 5623 ASTImporter *Importer = findFromTU(FromX)->Importer.get(); 5624 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); 5625 ASSERT_FALSE(OptErr); 5626 5627 // An error is set for f(). 5628 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 5629 FromTU, functionDecl(hasName("f"))); 5630 OptErr = Importer->getImportDeclErrorIfAny(FromF); 5631 ASSERT_TRUE(OptErr); 5632 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5633 // And any subsequent import should fail. 5634 FunctionDecl *ImportedF = Import(FromF, Lang_CXX03); 5635 EXPECT_FALSE(ImportedF); 5636 5637 // There is no error set for ok(). 5638 auto *FromOK = FirstDeclMatcher<FunctionDecl>().match( 5639 FromTU, functionDecl(hasName("ok"))); 5640 OptErr = Importer->getImportDeclErrorIfAny(FromOK); 5641 EXPECT_FALSE(OptErr); 5642 // And we should be able to import. 5643 FunctionDecl *ImportedOK = Import(FromOK, Lang_CXX03); 5644 EXPECT_TRUE(ImportedOK); 5645 } 5646 5647 TEST_P(ErrorHandlingTest, ODRViolationWithinTypedefDecls) { 5648 // Importing `z` should fail - instead of crashing - due to an ODR violation. 5649 // The `bar::e` typedef sets it's DeclContext after the import is done. 5650 // However, if the importation fails, it will be left as a nullptr. 5651 // During the cleanup of the failed import, we should check whether the 5652 // DeclContext is null or not - instead of dereferencing that unconditionally. 5653 constexpr auto ToTUCode = R"( 5654 namespace X { 5655 struct bar { 5656 int odr_violation; 5657 }; 5658 })"; 5659 constexpr auto FromTUCode = R"( 5660 namespace X { 5661 enum b {}; 5662 struct bar { 5663 typedef b e; 5664 static e d; 5665 }; 5666 } 5667 int z = X::bar::d; 5668 )"; 5669 Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11); 5670 static_cast<void>(ToTU); 5671 Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11); 5672 auto *FromZ = 5673 FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("z"))); 5674 ASSERT_TRUE(FromZ); 5675 ASSERT_TRUE(FromZ->hasInit()); 5676 5677 auto *ImportedZ = Import(FromZ, Lang_CXX11); 5678 EXPECT_FALSE(ImportedZ); 5679 } 5680 5681 // An error should be set for a class if it had a previous import with an error 5682 // from another TU. 5683 TEST_P(ErrorHandlingTest, 5684 ImportedDeclWithErrorShouldFailTheImportOfDeclWhichMapToIt) { 5685 // We already have a fwd decl. 5686 TranslationUnitDecl *ToTU = getToTuDecl("class X;", Lang_CXX03); 5687 // Then we import a definition. 5688 { 5689 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5690 class X { 5691 void f() { )") + ErroneousStmt + R"( } 5692 void ok(); 5693 }; 5694 )", 5695 Lang_CXX03); 5696 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 5697 FromTU, cxxRecordDecl(hasName("X"))); 5698 CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX03); 5699 5700 // An error is set for X ... 5701 EXPECT_FALSE(ImportedX); 5702 ASTImporter *Importer = findFromTU(FromX)->Importer.get(); 5703 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); 5704 ASSERT_TRUE(OptErr); 5705 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5706 } 5707 // ... but the node had been created. 5708 auto *ToXDef = FirstDeclMatcher<CXXRecordDecl>().match( 5709 ToTU, cxxRecordDecl(hasName("X"), isDefinition())); 5710 // An error is set for "ToXDef" in the shared state. 5711 Optional<ImportError> OptErr = 5712 SharedStatePtr->getImportDeclErrorIfAny(ToXDef); 5713 ASSERT_TRUE(OptErr); 5714 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5715 5716 auto *ToXFwd = FirstDeclMatcher<CXXRecordDecl>().match( 5717 ToTU, cxxRecordDecl(hasName("X"), unless(isDefinition()))); 5718 // An error is NOT set for the fwd Decl of X in the shared state. 5719 OptErr = SharedStatePtr->getImportDeclErrorIfAny(ToXFwd); 5720 ASSERT_FALSE(OptErr); 5721 5722 // Try to import X again but from another TU. 5723 { 5724 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5725 class X { 5726 void f() { )") + ErroneousStmt + R"( } 5727 void ok(); 5728 }; 5729 )", 5730 Lang_CXX03, "input1.cc"); 5731 5732 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 5733 FromTU, cxxRecordDecl(hasName("X"))); 5734 CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX03); 5735 5736 // If we did not save the errors for the "to" context then the below checks 5737 // would fail, because the lookup finds the fwd Decl of the existing 5738 // definition in the "to" context. We can reach the existing definition via 5739 // the found fwd Decl. That existing definition is structurally equivalent 5740 // (we check only the fields) with this one we want to import, so we return 5741 // with the existing definition, which is erroneous (one method is missing). 5742 5743 // The import should fail. 5744 EXPECT_FALSE(ImportedX); 5745 ASTImporter *Importer = findFromTU(FromX)->Importer.get(); 5746 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX); 5747 // And an error is set for this new X in the "from" ctx. 5748 ASSERT_TRUE(OptErr); 5749 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5750 } 5751 } 5752 5753 TEST_P(ErrorHandlingTest, ImportOfOverriddenMethods) { 5754 auto MatchFooA = 5755 functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("A")))); 5756 auto MatchFooB = 5757 functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("B")))); 5758 auto MatchFooC = 5759 functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("C")))); 5760 5761 // Provoke import of a method that has overridden methods with import error. 5762 TranslationUnitDecl *FromTU = getTuDecl(std::string(R"( 5763 struct C; 5764 struct A { 5765 virtual void foo(); 5766 void f1(C *); 5767 }; 5768 void A::foo() { 5769 )") + ErroneousStmt + R"( 5770 } 5771 struct B : public A { 5772 void foo() override; 5773 }; 5774 struct C : public B { 5775 void foo() override; 5776 }; 5777 )", 5778 Lang_CXX11); 5779 auto *FromFooA = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooA); 5780 auto *FromFooB = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooB); 5781 auto *FromFooC = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooC); 5782 5783 EXPECT_FALSE(Import(FromFooA, Lang_CXX11)); 5784 ASTImporter *Importer = findFromTU(FromFooA)->Importer.get(); 5785 auto CheckError = [&Importer](Decl *FromD) { 5786 Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromD); 5787 ASSERT_TRUE(OptErr); 5788 EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct); 5789 }; 5790 CheckError(FromFooA); 5791 EXPECT_FALSE(Import(FromFooB, Lang_CXX11)); 5792 CheckError(FromFooB); 5793 EXPECT_FALSE(Import(FromFooC, Lang_CXX11)); 5794 CheckError(FromFooC); 5795 } 5796 5797 TEST_P(ErrorHandlingTest, ODRViolationWithinParmVarDecls) { 5798 // Importing of 'f' and parameter 'P' should cause an ODR error. 5799 // The error happens after the ParmVarDecl for 'P' was already created. 5800 // This is a special case because the ParmVarDecl has a temporary DeclContext. 5801 // Expected is no crash at error handling of ASTImporter. 5802 constexpr auto ToTUCode = R"( 5803 struct X { 5804 char A; 5805 }; 5806 )"; 5807 constexpr auto FromTUCode = R"( 5808 struct X { 5809 enum Y { Z }; 5810 }; 5811 void f(int P = X::Z); 5812 )"; 5813 Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11); 5814 static_cast<void>(ToTU); 5815 Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11); 5816 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 5817 FromTU, functionDecl(hasName("f"))); 5818 ASSERT_TRUE(FromF); 5819 5820 auto *ImportedF = Import(FromF, Lang_CXX11); 5821 EXPECT_FALSE(ImportedF); 5822 } 5823 5824 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) { 5825 Decl *FromTU = getTuDecl( 5826 R"( 5827 void f() { 5828 auto L = [](){}; 5829 } 5830 )", 5831 Lang_CXX11, "input0.cc"); 5832 auto Pattern = lambdaExpr(); 5833 CXXRecordDecl *FromL = 5834 FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass(); 5835 5836 auto ToL = Import(FromL, Lang_CXX11); 5837 unsigned ToLSize = std::distance(ToL->decls().begin(), ToL->decls().end()); 5838 unsigned FromLSize = 5839 std::distance(FromL->decls().begin(), FromL->decls().end()); 5840 EXPECT_NE(ToLSize, 0u); 5841 EXPECT_EQ(ToLSize, FromLSize); 5842 EXPECT_FALSE(FromL->isDependentLambda()); 5843 } 5844 5845 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) { 5846 Decl *FromTU = getTuDecl( 5847 R"( 5848 template <typename F> 5849 void f(F L = [](){}) {} 5850 )", 5851 Lang_CXX11, "input0.cc"); 5852 auto Pattern = lambdaExpr(); 5853 CXXRecordDecl *FromL = 5854 FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass(); 5855 5856 auto ToL = Import(FromL, Lang_CXX11); 5857 unsigned ToLSize = std::distance(ToL->decls().begin(), ToL->decls().end()); 5858 unsigned FromLSize = 5859 std::distance(FromL->decls().begin(), FromL->decls().end()); 5860 EXPECT_NE(ToLSize, 0u); 5861 EXPECT_EQ(ToLSize, FromLSize); 5862 EXPECT_TRUE(FromL->isDependentLambda()); 5863 } 5864 5865 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInGlobalScope) { 5866 Decl *FromTU = getTuDecl( 5867 R"( 5868 auto l1 = [](unsigned lp) { return 1; }; 5869 auto l2 = [](int lp) { return 2; }; 5870 int f(int p) { 5871 return l1(p) + l2(p); 5872 } 5873 )", 5874 Lang_CXX11, "input0.cc"); 5875 FunctionDecl *FromF = FirstDeclMatcher<FunctionDecl>().match( 5876 FromTU, functionDecl(hasName("f"))); 5877 FunctionDecl *ToF = Import(FromF, Lang_CXX11); 5878 EXPECT_TRUE(ToF); 5879 } 5880 5881 TEST_P(ASTImporterOptionSpecificTestBase, 5882 ImportExistingFriendClassTemplateDef) { 5883 auto Code = 5884 R"( 5885 template <class T1, class T2> 5886 struct Base { 5887 template <class U1, class U2> 5888 friend struct Class; 5889 }; 5890 template <class T1, class T2> 5891 struct Class { }; 5892 )"; 5893 5894 TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX03); 5895 TranslationUnitDecl *FromTU = getTuDecl(Code, Lang_CXX03, "input.cc"); 5896 5897 auto *ToClassProto = FirstDeclMatcher<ClassTemplateDecl>().match( 5898 ToTU, classTemplateDecl(hasName("Class"))); 5899 auto *ToClassDef = LastDeclMatcher<ClassTemplateDecl>().match( 5900 ToTU, classTemplateDecl(hasName("Class"))); 5901 ASSERT_FALSE(ToClassProto->isThisDeclarationADefinition()); 5902 ASSERT_TRUE(ToClassDef->isThisDeclarationADefinition()); 5903 // Previous friend decl is not linked to it! 5904 ASSERT_FALSE(ToClassDef->getPreviousDecl()); 5905 ASSERT_EQ(ToClassDef->getMostRecentDecl(), ToClassDef); 5906 ASSERT_EQ(ToClassProto->getMostRecentDecl(), ToClassProto); 5907 5908 auto *FromClassProto = FirstDeclMatcher<ClassTemplateDecl>().match( 5909 FromTU, classTemplateDecl(hasName("Class"))); 5910 auto *FromClassDef = LastDeclMatcher<ClassTemplateDecl>().match( 5911 FromTU, classTemplateDecl(hasName("Class"))); 5912 ASSERT_FALSE(FromClassProto->isThisDeclarationADefinition()); 5913 ASSERT_TRUE(FromClassDef->isThisDeclarationADefinition()); 5914 ASSERT_FALSE(FromClassDef->getPreviousDecl()); 5915 ASSERT_EQ(FromClassDef->getMostRecentDecl(), FromClassDef); 5916 ASSERT_EQ(FromClassProto->getMostRecentDecl(), FromClassProto); 5917 5918 auto *ImportedDef = Import(FromClassDef, Lang_CXX03); 5919 // At import we should find the definition for 'Class' even if the 5920 // prototype (inside 'friend') for it comes first in the AST and is not 5921 // linked to the definition. 5922 EXPECT_EQ(ImportedDef, ToClassDef); 5923 } 5924 5925 struct LLDBLookupTest : ASTImporterOptionSpecificTestBase { 5926 LLDBLookupTest() { 5927 Creator = [](ASTContext &ToContext, FileManager &ToFileManager, 5928 ASTContext &FromContext, FileManager &FromFileManager, 5929 bool MinimalImport, 5930 const std::shared_ptr<ASTImporterSharedState> &SharedState) { 5931 return new ASTImporter(ToContext, ToFileManager, FromContext, 5932 FromFileManager, MinimalImport, 5933 // We use the regular lookup. 5934 /*SharedState=*/nullptr); 5935 }; 5936 } 5937 }; 5938 5939 TEST_P(LLDBLookupTest, ImporterShouldFindInTransparentContext) { 5940 TranslationUnitDecl *ToTU = getToTuDecl( 5941 R"( 5942 extern "C" { 5943 class X{}; 5944 }; 5945 )", 5946 Lang_CXX03); 5947 auto *ToX = FirstDeclMatcher<CXXRecordDecl>().match( 5948 ToTU, cxxRecordDecl(hasName("X"))); 5949 5950 // Set up a stub external storage. 5951 ToTU->setHasExternalLexicalStorage(true); 5952 // Set up DeclContextBits.HasLazyExternalLexicalLookups to true. 5953 ToTU->setMustBuildLookupTable(); 5954 struct TestExternalASTSource : ExternalASTSource {}; 5955 ToTU->getASTContext().setExternalSource(new TestExternalASTSource()); 5956 5957 Decl *FromTU = getTuDecl( 5958 R"( 5959 class X; 5960 )", 5961 Lang_CXX03); 5962 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 5963 FromTU, cxxRecordDecl(hasName("X"))); 5964 auto *ImportedX = Import(FromX, Lang_CXX03); 5965 // The lookup must find the existing class definition in the LinkageSpecDecl. 5966 // Then the importer renders the existing and the new decl into one chain. 5967 EXPECT_EQ(ImportedX->getCanonicalDecl(), ToX->getCanonicalDecl()); 5968 } 5969 5970 struct SVEBuiltins : ASTImporterOptionSpecificTestBase {}; 5971 5972 TEST_P(SVEBuiltins, ImportTypes) { 5973 static const char *const TypeNames[] = { 5974 "__SVInt8_t", 5975 "__SVInt16_t", 5976 "__SVInt32_t", 5977 "__SVInt64_t", 5978 "__SVUint8_t", 5979 "__SVUint16_t", 5980 "__SVUint32_t", 5981 "__SVUint64_t", 5982 "__SVFloat16_t", 5983 "__SVBFloat16_t", 5984 "__SVFloat32_t", 5985 "__SVFloat64_t", 5986 "__SVBool_t" 5987 }; 5988 5989 TranslationUnitDecl *ToTU = getToTuDecl("", Lang_CXX03); 5990 TranslationUnitDecl *FromTU = getTuDecl("", Lang_CXX03, "input.cc"); 5991 for (auto *TypeName : TypeNames) { 5992 auto *ToTypedef = FirstDeclMatcher<TypedefDecl>().match( 5993 ToTU, typedefDecl(hasName(TypeName))); 5994 QualType ToType = ToTypedef->getUnderlyingType(); 5995 5996 auto *FromTypedef = FirstDeclMatcher<TypedefDecl>().match( 5997 FromTU, typedefDecl(hasName(TypeName))); 5998 QualType FromType = FromTypedef->getUnderlyingType(); 5999 6000 QualType ImportedType = ImportType(FromType, FromTypedef, Lang_CXX03); 6001 EXPECT_EQ(ImportedType, ToType); 6002 } 6003 } 6004 6005 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfDefaultImplicitFunctions) { 6006 // Test that import of implicit functions works and the functions 6007 // are merged into one chain. 6008 auto GetDeclToImport = [this](StringRef File) { 6009 Decl *FromTU = getTuDecl( 6010 R"( 6011 struct X { }; 6012 // Force generating some implicit operator definitions for X. 6013 void f() { X x1, x2; x1 = x2; X *x3 = new X; delete x3; } 6014 )", 6015 Lang_CXX11, File); 6016 auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match( 6017 FromTU, cxxRecordDecl(hasName("X"), unless(isImplicit()))); 6018 // Destructor is picked as one example of implicit function. 6019 return FromD->getDestructor(); 6020 }; 6021 6022 auto *ToD1 = Import(GetDeclToImport("input1.cc"), Lang_CXX11); 6023 ASSERT_TRUE(ToD1); 6024 6025 auto *ToD2 = Import(GetDeclToImport("input2.cc"), Lang_CXX11); 6026 ASSERT_TRUE(ToD2); 6027 6028 EXPECT_EQ(ToD1->getCanonicalDecl(), ToD2->getCanonicalDecl()); 6029 } 6030 6031 TEST_P(ASTImporterOptionSpecificTestBase, 6032 ImportOfExplicitlyDefaultedOrDeleted) { 6033 Decl *FromTU = getTuDecl( 6034 R"( 6035 struct X { X() = default; X(const X&) = delete; }; 6036 )", 6037 Lang_CXX11); 6038 auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match( 6039 FromTU, cxxRecordDecl(hasName("X"))); 6040 auto *ImportedX = Import(FromX, Lang_CXX11); 6041 auto *Constr1 = FirstDeclMatcher<CXXConstructorDecl>().match( 6042 ImportedX, cxxConstructorDecl(hasName("X"), unless(isImplicit()))); 6043 auto *Constr2 = LastDeclMatcher<CXXConstructorDecl>().match( 6044 ImportedX, cxxConstructorDecl(hasName("X"), unless(isImplicit()))); 6045 6046 ASSERT_TRUE(ImportedX); 6047 EXPECT_TRUE(Constr1->isDefaulted()); 6048 EXPECT_TRUE(Constr1->isExplicitlyDefaulted()); 6049 EXPECT_TRUE(Constr2->isDeletedAsWritten()); 6050 EXPECT_EQ(ImportedX->isAggregate(), FromX->isAggregate()); 6051 } 6052 6053 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, SVEBuiltins, 6054 ::testing::Values(std::vector<std::string>{ 6055 "-target", "aarch64-linux-gnu"})); 6056 6057 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, DeclContextTest, 6058 ::testing::Values(std::vector<std::string>())); 6059 6060 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, CanonicalRedeclChain, 6061 ::testing::Values(std::vector<std::string>())); 6062 6063 TEST_P(ASTImporterOptionSpecificTestBase, LambdasAreDifferentiated) { 6064 Decl *FromTU = getTuDecl( 6065 R"( 6066 void f() { 6067 auto L0 = [](){}; 6068 auto L1 = [](){}; 6069 } 6070 )", 6071 Lang_CXX11, "input0.cc"); 6072 auto Pattern = lambdaExpr(); 6073 CXXRecordDecl *FromL0 = 6074 FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass(); 6075 CXXRecordDecl *FromL1 = 6076 LastDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass(); 6077 ASSERT_NE(FromL0, FromL1); 6078 6079 CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11); 6080 CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11); 6081 EXPECT_NE(ToL0, ToL1); 6082 } 6083 6084 TEST_P(ASTImporterOptionSpecificTestBase, 6085 LambdasInFunctionParamsAreDifferentiated) { 6086 Decl *FromTU = getTuDecl( 6087 R"( 6088 template <typename F0, typename F1> 6089 void f(F0 L0 = [](){}, F1 L1 = [](){}) {} 6090 )", 6091 Lang_CXX11, "input0.cc"); 6092 auto Pattern = cxxRecordDecl(isLambda()); 6093 CXXRecordDecl *FromL0 = 6094 FirstDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern); 6095 CXXRecordDecl *FromL1 = 6096 LastDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern); 6097 ASSERT_NE(FromL0, FromL1); 6098 6099 CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11); 6100 CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11); 6101 ASSERT_NE(ToL0, ToL1); 6102 } 6103 6104 TEST_P(ASTImporterOptionSpecificTestBase, 6105 LambdasInFunctionParamsAreDifferentiatedWhenMacroIsUsed) { 6106 Decl *FromTU = getTuDecl( 6107 R"( 6108 #define LAMBDA [](){} 6109 template <typename F0, typename F1> 6110 void f(F0 L0 = LAMBDA, F1 L1 = LAMBDA) {} 6111 )", 6112 Lang_CXX11, "input0.cc"); 6113 auto Pattern = cxxRecordDecl(isLambda()); 6114 CXXRecordDecl *FromL0 = 6115 FirstDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern); 6116 CXXRecordDecl *FromL1 = 6117 LastDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern); 6118 ASSERT_NE(FromL0, FromL1); 6119 6120 Import(FromL0, Lang_CXX11); 6121 Import(FromL1, Lang_CXX11); 6122 CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11); 6123 CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11); 6124 ASSERT_NE(ToL0, ToL1); 6125 } 6126 6127 TEST_P(ASTImporterOptionSpecificTestBase, ImportAssignedLambda) { 6128 Decl *FromTU = getTuDecl( 6129 R"( 6130 void f() { 6131 auto x = []{} = {}; auto x2 = x; 6132 } 6133 )", 6134 Lang_CXX20, "input0.cc"); 6135 auto FromF = FirstDeclMatcher<FunctionDecl>().match( 6136 FromTU, functionDecl(hasName("f"))); 6137 // We have only one lambda class. 6138 ASSERT_EQ( 6139 DeclCounter<CXXRecordDecl>().match(FromTU, cxxRecordDecl(isLambda())), 6140 1u); 6141 6142 FunctionDecl *ToF = Import(FromF, Lang_CXX20); 6143 EXPECT_TRUE(ToF); 6144 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 6145 // We have only one lambda class after the import. 6146 EXPECT_EQ(DeclCounter<CXXRecordDecl>().match(ToTU, cxxRecordDecl(isLambda())), 6147 1u); 6148 } 6149 6150 TEST_P(ASTImporterOptionSpecificTestBase, ImportDefaultConstructibleLambdas) { 6151 Decl *FromTU = getTuDecl( 6152 R"( 6153 void f() { 6154 auto x = []{} = {}; 6155 auto xb = []{} = {}; 6156 } 6157 )", 6158 Lang_CXX20, "input0.cc"); 6159 auto FromF = FirstDeclMatcher<FunctionDecl>().match( 6160 FromTU, functionDecl(hasName("f"))); 6161 // We have two lambda classes. 6162 ASSERT_EQ( 6163 DeclCounter<CXXRecordDecl>().match(FromTU, cxxRecordDecl(isLambda())), 6164 2u); 6165 6166 FunctionDecl *ToF = Import(FromF, Lang_CXX20); 6167 EXPECT_TRUE(ToF); 6168 TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl(); 6169 // We have two lambda classes after the import. 6170 EXPECT_EQ(DeclCounter<CXXRecordDecl>().match(ToTU, cxxRecordDecl(isLambda())), 6171 2u); 6172 } 6173 6174 TEST_P(ASTImporterOptionSpecificTestBase, 6175 ImportFunctionDeclWithTypeSourceInfoWithSourceDecl) { 6176 // This code results in a lambda with implicit constructor. 6177 // The constructor's TypeSourceInfo points out the function prototype. 6178 // This prototype has an EST_Unevaluated in its exception information and a 6179 // SourceDecl that is the function declaration itself. 6180 // The test verifies that AST import of such AST does not crash. 6181 // (Here the function's TypeSourceInfo references the function itself.) 6182 Decl *FromTU = getTuDecl( 6183 R"( 6184 template<typename T> void f(T) { auto X = [](){}; } 6185 void g() { f(10); } 6186 )", 6187 Lang_CXX11, "input0.cc"); 6188 6189 // Use LastDeclMatcher to find the LambdaExpr in the template specialization. 6190 CXXRecordDecl *FromL = LastDeclMatcher<LambdaExpr>() 6191 .match(FromTU, lambdaExpr()) 6192 ->getLambdaClass(); 6193 6194 CXXConstructorDecl *FromCtor = *FromL->ctor_begin(); 6195 ASSERT_TRUE(FromCtor->isCopyConstructor()); 6196 ASSERT_TRUE(FromCtor->getTypeSourceInfo()); 6197 const auto *FromFPT = FromCtor->getType()->getAs<FunctionProtoType>(); 6198 ASSERT_TRUE(FromFPT); 6199 EXPECT_EQ(FromCtor->getTypeSourceInfo()->getType().getTypePtr(), FromFPT); 6200 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); 6201 // If type is EST_Unevaluated, SourceDecl should be set to the parent Decl. 6202 EXPECT_EQ(FromEPI.ExceptionSpec.Type, EST_Unevaluated); 6203 EXPECT_EQ(FromEPI.ExceptionSpec.SourceDecl, FromCtor); 6204 6205 auto ToL = Import(FromL, Lang_CXX11); 6206 6207 // Check if the import was correct. 6208 CXXConstructorDecl *ToCtor = *ToL->ctor_begin(); 6209 EXPECT_TRUE(ToCtor->getTypeSourceInfo()); 6210 const auto *ToFPT = ToCtor->getType()->getAs<FunctionProtoType>(); 6211 ASSERT_TRUE(ToFPT); 6212 EXPECT_EQ(ToCtor->getTypeSourceInfo()->getType().getTypePtr(), ToFPT); 6213 FunctionProtoType::ExtProtoInfo ToEPI = ToFPT->getExtProtoInfo(); 6214 EXPECT_EQ(ToEPI.ExceptionSpec.Type, EST_Unevaluated); 6215 EXPECT_EQ(ToEPI.ExceptionSpec.SourceDecl, ToCtor); 6216 } 6217 6218 struct ImportAutoFunctions : ASTImporterOptionSpecificTestBase {}; 6219 6220 TEST_P(ImportAutoFunctions, ReturnWithTypedefDeclaredInside) { 6221 Decl *FromTU = getTuDecl( 6222 R"( 6223 auto X = [](long l) { 6224 using int_type = long; 6225 auto dur = 13; 6226 return static_cast<int_type>(dur); 6227 }; 6228 )", 6229 Lang_CXX14, "input0.cc"); 6230 CXXMethodDecl *From = 6231 FirstDeclMatcher<CXXMethodDecl>().match(FromTU, cxxMethodDecl()); 6232 6233 // Explicitly set the return type of the lambda's operator() to the TypeAlias. 6234 // Normally the return type would be the built-in 'long' type. However, there 6235 // are cases when Clang does not use the canonical type and the TypeAlias is 6236 // used. I could not create such an AST from regular source code, it requires 6237 // some special state in the preprocessor. I've found such an AST when Clang 6238 // parsed libcxx/src/filesystem/directory_iterator.cpp, but could not reduce 6239 // that with creduce, because after preprocessing, the AST no longer 6240 // contained the TypeAlias as a return type of the lambda. 6241 ASTContext &Ctx = From->getASTContext(); 6242 TypeAliasDecl *FromTA = 6243 FirstDeclMatcher<TypeAliasDecl>().match(FromTU, typeAliasDecl()); 6244 QualType TT = Ctx.getTypedefType(FromTA); 6245 const FunctionProtoType *FPT = cast<FunctionProtoType>(From->getType()); 6246 QualType NewFunType = 6247 Ctx.getFunctionType(TT, FPT->getParamTypes(), FPT->getExtProtoInfo()); 6248 From->setType(NewFunType); 6249 6250 CXXMethodDecl *To = Import(From, Lang_CXX14); 6251 EXPECT_TRUE(To); 6252 EXPECT_TRUE(isa<TypedefType>(To->getReturnType())); 6253 } 6254 6255 TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredInside) { 6256 Decl *FromTU = getTuDecl( 6257 R"( 6258 auto foo() { 6259 struct X {}; 6260 return X(); 6261 } 6262 )", 6263 Lang_CXX14, "input0.cc"); 6264 FunctionDecl *From = 6265 FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 6266 6267 FunctionDecl *To = Import(From, Lang_CXX14); 6268 EXPECT_TRUE(To); 6269 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6270 } 6271 6272 TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredInside2) { 6273 Decl *FromTU = getTuDecl( 6274 R"( 6275 auto foo() { 6276 struct X {}; 6277 return X(); 6278 } 6279 )", 6280 Lang_CXX14, "input0.cc"); 6281 FunctionDecl *From = 6282 FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 6283 6284 // This time import the type directly. 6285 QualType ToT = ImportType(From->getType(), From, Lang_CXX14); 6286 const FunctionProtoType *FPT = cast<FunctionProtoType>(ToT); 6287 EXPECT_TRUE(isa<AutoType>(FPT->getReturnType())); 6288 } 6289 6290 TEST_P(ImportAutoFunctions, ReturnWithTypedefToStructDeclaredInside) { 6291 Decl *FromTU = getTuDecl( 6292 R"( 6293 auto foo() { 6294 struct X {}; 6295 using Y = X; 6296 return Y(); 6297 } 6298 )", 6299 Lang_CXX14, "input0.cc"); 6300 FunctionDecl *From = 6301 FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 6302 6303 FunctionDecl *To = Import(From, Lang_CXX14); 6304 EXPECT_TRUE(To); 6305 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6306 } 6307 6308 TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredNestedInside) { 6309 Decl *FromTU = getTuDecl( 6310 R"( 6311 auto foo() { 6312 struct X { struct Y{}; }; 6313 return X::Y(); 6314 } 6315 )", 6316 Lang_CXX14, "input0.cc"); 6317 FunctionDecl *From = 6318 FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl()); 6319 6320 FunctionDecl *To = Import(From, Lang_CXX14); 6321 EXPECT_TRUE(To); 6322 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6323 } 6324 6325 TEST_P(ImportAutoFunctions, ReturnWithInternalLambdaType) { 6326 Decl *FromTU = getTuDecl( 6327 R"( 6328 auto f() { 6329 auto l = []() { 6330 struct X {}; 6331 return X(); 6332 }; 6333 return l(); 6334 } 6335 )", 6336 Lang_CXX17, "input0.cc"); 6337 FunctionDecl *From = FirstDeclMatcher<FunctionDecl>().match( 6338 FromTU, functionDecl(hasName("f"))); 6339 6340 FunctionDecl *To = Import(From, Lang_CXX17); 6341 EXPECT_TRUE(To); 6342 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6343 } 6344 6345 TEST_P(ImportAutoFunctions, ReturnWithTypeInIf) { 6346 Decl *FromTU = getTuDecl( 6347 R"( 6348 auto f() { 6349 if (struct X {} x; true) 6350 return X(); 6351 else 6352 return X(); 6353 } 6354 )", 6355 Lang_CXX17, "input0.cc"); 6356 FunctionDecl *From = FirstDeclMatcher<FunctionDecl>().match( 6357 FromTU, functionDecl(hasName("f"))); 6358 6359 FunctionDecl *To = Import(From, Lang_CXX17); 6360 EXPECT_TRUE(To); 6361 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6362 } 6363 6364 TEST_P(ImportAutoFunctions, ReturnWithTypeInFor) { 6365 Decl *FromTU = getTuDecl( 6366 R"( 6367 auto f() { 6368 for (struct X {} x;;) 6369 return X(); 6370 } 6371 )", 6372 Lang_CXX17, "input0.cc"); 6373 FunctionDecl *From = FirstDeclMatcher<FunctionDecl>().match( 6374 FromTU, functionDecl(hasName("f"))); 6375 6376 FunctionDecl *To = Import(From, Lang_CXX17); 6377 EXPECT_TRUE(To); 6378 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6379 } 6380 6381 TEST_P(ImportAutoFunctions, ReturnWithTypeInSwitch) { 6382 Decl *FromTU = getTuDecl( 6383 R"( 6384 auto f() { 6385 switch (struct X {} x; 10) { 6386 case 10: 6387 return X(); 6388 } 6389 } 6390 )", 6391 Lang_CXX17, "input0.cc"); 6392 FunctionDecl *From = FirstDeclMatcher<FunctionDecl>().match( 6393 FromTU, functionDecl(hasName("f"))); 6394 6395 FunctionDecl *To = Import(From, Lang_CXX17); 6396 EXPECT_TRUE(To); 6397 EXPECT_TRUE(isa<AutoType>(To->getReturnType())); 6398 } 6399 6400 struct ImportSourceLocations : ASTImporterOptionSpecificTestBase {}; 6401 6402 TEST_P(ImportSourceLocations, PreserveFileIDTreeStructure) { 6403 // Tests that the FileID tree structure (with the links being the include 6404 // chains) is preserved while importing other files (which need to be 6405 // added to this structure with fake include locations. 6406 6407 SourceLocation Location1; 6408 { 6409 auto Pattern = varDecl(hasName("X")); 6410 Decl *FromTU = getTuDecl("int X;", Lang_C99, "input0.c"); 6411 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 6412 6413 Location1 = Import(FromD, Lang_C99)->getLocation(); 6414 } 6415 SourceLocation Location2; 6416 { 6417 auto Pattern = varDecl(hasName("Y")); 6418 Decl *FromTU = getTuDecl("int Y;", Lang_C99, "input1.c"); 6419 auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 6420 6421 Location2 = Import(FromD, Lang_C99)->getLocation(); 6422 } 6423 6424 SourceManager &ToSM = ToAST->getSourceManager(); 6425 FileID FileID1 = ToSM.getFileID(Location1); 6426 FileID FileID2 = ToSM.getFileID(Location2); 6427 6428 // Check that the imported files look like as if they were included from the 6429 // start of the main file. 6430 SourceLocation FileStart = ToSM.getLocForStartOfFile(ToSM.getMainFileID()); 6431 EXPECT_NE(FileID1, ToSM.getMainFileID()); 6432 EXPECT_NE(FileID2, ToSM.getMainFileID()); 6433 EXPECT_EQ(ToSM.getIncludeLoc(FileID1), FileStart); 6434 EXPECT_EQ(ToSM.getIncludeLoc(FileID2), FileStart); 6435 6436 // Let the SourceManager check the order of the locations. The order should 6437 // be the order in which the declarations are imported. 6438 EXPECT_TRUE(ToSM.isBeforeInTranslationUnit(Location1, Location2)); 6439 EXPECT_FALSE(ToSM.isBeforeInTranslationUnit(Location2, Location1)); 6440 } 6441 6442 TEST_P(ImportSourceLocations, NormalFileBuffer) { 6443 // Test importing normal file buffers. 6444 6445 std::string Path = "input0.c"; 6446 std::string Source = "int X;"; 6447 TranslationUnitDecl *FromTU = getTuDecl(Source, Lang_C99, Path); 6448 6449 SourceLocation ImportedLoc; 6450 { 6451 // Import the VarDecl to trigger the importing of the FileID. 6452 auto Pattern = varDecl(hasName("X")); 6453 VarDecl *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 6454 ImportedLoc = Import(FromD, Lang_C99)->getLocation(); 6455 } 6456 6457 // Make sure the imported buffer has the original contents. 6458 SourceManager &ToSM = ToAST->getSourceManager(); 6459 FileID ImportedID = ToSM.getFileID(ImportedLoc); 6460 EXPECT_EQ(Source, 6461 ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer()); 6462 } 6463 6464 TEST_P(ImportSourceLocations, OverwrittenFileBuffer) { 6465 // Test importing overwritten file buffers. 6466 6467 std::string Path = "input0.c"; 6468 TranslationUnitDecl *FromTU = getTuDecl("int X;", Lang_C99, Path); 6469 6470 // Overwrite the file buffer for our input file with new content. 6471 const std::string Contents = "overwritten contents"; 6472 SourceLocation ImportedLoc; 6473 { 6474 SourceManager &FromSM = FromTU->getASTContext().getSourceManager(); 6475 clang::FileManager &FM = FromSM.getFileManager(); 6476 const clang::FileEntry &FE = 6477 *FM.getVirtualFile(Path, static_cast<off_t>(Contents.size()), 0); 6478 6479 llvm::SmallVector<char, 64> Buffer; 6480 Buffer.append(Contents.begin(), Contents.end()); 6481 auto FileContents = std::make_unique<llvm::SmallVectorMemoryBuffer>( 6482 std::move(Buffer), Path, /*RequiresNullTerminator=*/false); 6483 FromSM.overrideFileContents(&FE, std::move(FileContents)); 6484 6485 // Import the VarDecl to trigger the importing of the FileID. 6486 auto Pattern = varDecl(hasName("X")); 6487 VarDecl *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern); 6488 ImportedLoc = Import(FromD, Lang_C99)->getLocation(); 6489 } 6490 6491 // Make sure the imported buffer has the overwritten contents. 6492 SourceManager &ToSM = ToAST->getSourceManager(); 6493 FileID ImportedID = ToSM.getFileID(ImportedLoc); 6494 EXPECT_EQ(Contents, 6495 ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer()); 6496 } 6497 6498 struct ImportAttributes : public ASTImporterOptionSpecificTestBase { 6499 void checkAttrImportCommon(const Attr *From, const Attr *To, 6500 const Decl *ToD) { 6501 6502 // Verify that dump does not crash because invalid data. 6503 ToD->dump(llvm::nulls()); 6504 6505 EXPECT_EQ(From->getParsedKind(), To->getParsedKind()); 6506 EXPECT_EQ(From->getSyntax(), To->getSyntax()); 6507 if (From->getAttrName()) { 6508 EXPECT_TRUE(To->getAttrName()); 6509 EXPECT_STREQ(From->getAttrName()->getNameStart(), 6510 To->getAttrName()->getNameStart()); 6511 } else { 6512 EXPECT_FALSE(To->getAttrName()); 6513 } 6514 if (From->getScopeName()) { 6515 EXPECT_TRUE(To->getScopeName()); 6516 EXPECT_STREQ(From->getScopeName()->getNameStart(), 6517 To->getScopeName()->getNameStart()); 6518 } else { 6519 EXPECT_FALSE(To->getScopeName()); 6520 } 6521 EXPECT_EQ(From->getSpellingListIndex(), To->getSpellingListIndex()); 6522 EXPECT_STREQ(From->getSpelling(), To->getSpelling()); 6523 EXPECT_EQ(From->isInherited(), To->isInherited()); 6524 EXPECT_EQ(From->isImplicit(), To->isImplicit()); 6525 EXPECT_EQ(From->isPackExpansion(), To->isPackExpansion()); 6526 EXPECT_EQ(From->isLateParsed(), To->isLateParsed()); 6527 } 6528 6529 template <class DT, class AT> 6530 void importAttr(const char *Code, AT *&FromAttr, AT *&ToAttr) { 6531 static_assert(std::is_base_of<Attr, AT>::value, "AT should be an Attr"); 6532 static_assert(std::is_base_of<Decl, DT>::value, "DT should be a Decl"); 6533 6534 Decl *FromTU = getTuDecl(Code, Lang_CXX11, "input.cc"); 6535 DT *FromD = 6536 FirstDeclMatcher<DT>().match(FromTU, namedDecl(hasName("test"))); 6537 ASSERT_TRUE(FromD); 6538 6539 DT *ToD = Import(FromD, Lang_CXX11); 6540 ASSERT_TRUE(ToD); 6541 6542 FromAttr = FromD->template getAttr<AT>(); 6543 ToAttr = ToD->template getAttr<AT>(); 6544 ASSERT_TRUE(FromAttr); 6545 EXPECT_TRUE(ToAttr); 6546 6547 checkAttrImportCommon(FromAttr, ToAttr, ToD); 6548 } 6549 6550 template <class T> void checkImported(const T *From, const T *To) { 6551 EXPECT_TRUE(To); 6552 EXPECT_NE(From, To); 6553 } 6554 6555 template <class T> 6556 void checkImportVariadicArg(const llvm::iterator_range<T **> &From, 6557 const llvm::iterator_range<T **> &To) { 6558 for (auto FromI = From.begin(), ToI = To.begin(); FromI != From.end(); 6559 ++FromI, ++ToI) { 6560 ASSERT_NE(ToI, To.end()); 6561 checkImported(*FromI, *ToI); 6562 } 6563 } 6564 }; 6565 6566 template <> 6567 void ImportAttributes::checkImported<Decl>(const Decl *From, const Decl *To) { 6568 EXPECT_TRUE(To); 6569 EXPECT_NE(From, To); 6570 EXPECT_EQ(To->getTranslationUnitDecl(), 6571 ToAST->getASTContext().getTranslationUnitDecl()); 6572 } 6573 6574 // FIXME: Use ImportAttributes for this test. 6575 TEST_P(ASTImporterOptionSpecificTestBase, ImportExprOfAlignmentAttr) { 6576 // Test if import of these packed and aligned attributes does not trigger an 6577 // error situation where source location from 'From' context is referenced in 6578 // 'To' context through evaluation of the alignof attribute. 6579 // This happens if the 'alignof(A)' expression is not imported correctly. 6580 Decl *FromTU = getTuDecl( 6581 R"( 6582 struct __attribute__((packed)) A { int __attribute__((aligned(8))) X; }; 6583 struct alignas(alignof(A)) S {}; 6584 )", 6585 Lang_CXX11, "input.cc"); 6586 auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match( 6587 FromTU, cxxRecordDecl(hasName("S"), unless(isImplicit()))); 6588 ASSERT_TRUE(FromD); 6589 6590 auto *ToD = Import(FromD, Lang_CXX11); 6591 ASSERT_TRUE(ToD); 6592 6593 auto *FromAttr = FromD->getAttr<AlignedAttr>(); 6594 auto *ToAttr = ToD->getAttr<AlignedAttr>(); 6595 EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited()); 6596 EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion()); 6597 EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit()); 6598 EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax()); 6599 EXPECT_EQ(FromAttr->getSemanticSpelling(), ToAttr->getSemanticSpelling()); 6600 EXPECT_TRUE(ToAttr->getAlignmentExpr()); 6601 6602 auto *ToA = FirstDeclMatcher<CXXRecordDecl>().match( 6603 ToD->getTranslationUnitDecl(), 6604 cxxRecordDecl(hasName("A"), unless(isImplicit()))); 6605 // Ensure that 'struct A' was imported (through reference from attribute of 6606 // 'S'). 6607 EXPECT_TRUE(ToA); 6608 } 6609 6610 // FIXME: Use ImportAttributes for this test. 6611 TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) { 6612 Decl *FromTU = getTuDecl( 6613 R"( 6614 int foo(const char * fmt, ...) 6615 __attribute__ ((__format__ (__scanf__, 1, 2))); 6616 )", 6617 Lang_CXX03, "input.cc"); 6618 auto *FromD = FirstDeclMatcher<FunctionDecl>().match( 6619 FromTU, functionDecl(hasName("foo"))); 6620 ASSERT_TRUE(FromD); 6621 6622 auto *ToD = Import(FromD, Lang_CXX03); 6623 ASSERT_TRUE(ToD); 6624 ToD->dump(); // Should not crash! 6625 6626 auto *FromAttr = FromD->getAttr<FormatAttr>(); 6627 auto *ToAttr = ToD->getAttr<FormatAttr>(); 6628 EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited()); 6629 EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion()); 6630 EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit()); 6631 EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax()); 6632 EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(), 6633 ToAttr->getAttributeSpellingListIndex()); 6634 EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName()); 6635 } 6636 6637 TEST_P(ImportAttributes, ImportGuardedVar) { 6638 GuardedVarAttr *FromAttr, *ToAttr; 6639 importAttr<VarDecl>("int test __attribute__((guarded_var));", FromAttr, 6640 ToAttr); 6641 } 6642 6643 TEST_P(ImportAttributes, ImportPtGuardedVar) { 6644 PtGuardedVarAttr *FromAttr, *ToAttr; 6645 importAttr<VarDecl>("int *test __attribute__((pt_guarded_var));", FromAttr, 6646 ToAttr); 6647 } 6648 6649 TEST_P(ImportAttributes, ImportScopedLockable) { 6650 ScopedLockableAttr *FromAttr, *ToAttr; 6651 importAttr<CXXRecordDecl>("struct __attribute__((scoped_lockable)) test {};", 6652 FromAttr, ToAttr); 6653 } 6654 6655 TEST_P(ImportAttributes, ImportCapability) { 6656 CapabilityAttr *FromAttr, *ToAttr; 6657 importAttr<CXXRecordDecl>( 6658 "struct __attribute__((capability(\"cap\"))) test {};", FromAttr, ToAttr); 6659 EXPECT_EQ(FromAttr->getName(), ToAttr->getName()); 6660 } 6661 6662 TEST_P(ImportAttributes, ImportAssertCapability) { 6663 AssertCapabilityAttr *FromAttr, *ToAttr; 6664 importAttr<FunctionDecl>( 6665 "void test(int A1, int A2) __attribute__((assert_capability(A1, A2)));", 6666 FromAttr, ToAttr); 6667 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6668 } 6669 6670 TEST_P(ImportAttributes, ImportAcquireCapability) { 6671 AcquireCapabilityAttr *FromAttr, *ToAttr; 6672 importAttr<FunctionDecl>( 6673 "void test(int A1, int A2) __attribute__((acquire_capability(A1, A2)));", 6674 FromAttr, ToAttr); 6675 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6676 } 6677 6678 TEST_P(ImportAttributes, ImportTryAcquireCapability) { 6679 TryAcquireCapabilityAttr *FromAttr, *ToAttr; 6680 importAttr<FunctionDecl>( 6681 "void test(int A1, int A2) __attribute__((try_acquire_capability(1, A1, " 6682 "A2)));", 6683 FromAttr, ToAttr); 6684 checkImported(FromAttr->getSuccessValue(), ToAttr->getSuccessValue()); 6685 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6686 } 6687 6688 TEST_P(ImportAttributes, ImportReleaseCapability) { 6689 ReleaseCapabilityAttr *FromAttr, *ToAttr; 6690 importAttr<FunctionDecl>( 6691 "void test(int A1, int A2) __attribute__((release_capability(A1, A2)));", 6692 FromAttr, ToAttr); 6693 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6694 } 6695 6696 TEST_P(ImportAttributes, ImportRequiresCapability) { 6697 RequiresCapabilityAttr *FromAttr, *ToAttr; 6698 importAttr<FunctionDecl>( 6699 "void test(int A1, int A2) __attribute__((requires_capability(A1, A2)));", 6700 FromAttr, ToAttr); 6701 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6702 } 6703 6704 TEST_P(ImportAttributes, ImportNoThreadSafetyAnalysis) { 6705 NoThreadSafetyAnalysisAttr *FromAttr, *ToAttr; 6706 importAttr<FunctionDecl>( 6707 "void test() __attribute__((no_thread_safety_analysis));", FromAttr, 6708 ToAttr); 6709 } 6710 6711 TEST_P(ImportAttributes, ImportGuardedBy) { 6712 GuardedByAttr *FromAttr, *ToAttr; 6713 importAttr<VarDecl>( 6714 R"( 6715 int G; 6716 int test __attribute__((guarded_by(G))); 6717 )", 6718 FromAttr, ToAttr); 6719 checkImported(FromAttr->getArg(), ToAttr->getArg()); 6720 } 6721 6722 TEST_P(ImportAttributes, ImportPtGuardedBy) { 6723 PtGuardedByAttr *FromAttr, *ToAttr; 6724 importAttr<VarDecl>( 6725 R"( 6726 int G; 6727 int *test __attribute__((pt_guarded_by(G))); 6728 )", 6729 FromAttr, ToAttr); 6730 checkImported(FromAttr->getArg(), ToAttr->getArg()); 6731 } 6732 6733 TEST_P(ImportAttributes, ImportAcquiredAfter) { 6734 AcquiredAfterAttr *FromAttr, *ToAttr; 6735 importAttr<VarDecl>( 6736 R"( 6737 struct __attribute__((lockable)) L {}; 6738 L A1; 6739 L A2; 6740 L test __attribute__((acquired_after(A1, A2))); 6741 )", 6742 FromAttr, ToAttr); 6743 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6744 } 6745 6746 TEST_P(ImportAttributes, ImportAcquiredBefore) { 6747 AcquiredBeforeAttr *FromAttr, *ToAttr; 6748 importAttr<VarDecl>( 6749 R"( 6750 struct __attribute__((lockable)) L {}; 6751 L A1; 6752 L A2; 6753 L test __attribute__((acquired_before(A1, A2))); 6754 )", 6755 FromAttr, ToAttr); 6756 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6757 } 6758 6759 TEST_P(ImportAttributes, ImportAssertExclusiveLock) { 6760 AssertExclusiveLockAttr *FromAttr, *ToAttr; 6761 importAttr<FunctionDecl>("void test(int A1, int A2) " 6762 "__attribute__((assert_exclusive_lock(A1, A2)));", 6763 FromAttr, ToAttr); 6764 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6765 } 6766 6767 TEST_P(ImportAttributes, ImportAssertSharedLock) { 6768 AssertSharedLockAttr *FromAttr, *ToAttr; 6769 importAttr<FunctionDecl>( 6770 "void test(int A1, int A2) __attribute__((assert_shared_lock(A1, A2)));", 6771 FromAttr, ToAttr); 6772 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6773 } 6774 6775 TEST_P(ImportAttributes, ImportExclusiveTrylockFunction) { 6776 ExclusiveTrylockFunctionAttr *FromAttr, *ToAttr; 6777 importAttr<FunctionDecl>( 6778 "void test(int A1, int A2) __attribute__((exclusive_trylock_function(1, " 6779 "A1, A2)));", 6780 FromAttr, ToAttr); 6781 checkImported(FromAttr->getSuccessValue(), ToAttr->getSuccessValue()); 6782 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6783 } 6784 6785 TEST_P(ImportAttributes, ImportSharedTrylockFunction) { 6786 SharedTrylockFunctionAttr *FromAttr, *ToAttr; 6787 importAttr<FunctionDecl>( 6788 "void test(int A1, int A2) __attribute__((shared_trylock_function(1, A1, " 6789 "A2)));", 6790 FromAttr, ToAttr); 6791 checkImported(FromAttr->getSuccessValue(), ToAttr->getSuccessValue()); 6792 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6793 } 6794 6795 TEST_P(ImportAttributes, ImportLockReturned) { 6796 LockReturnedAttr *FromAttr, *ToAttr; 6797 importAttr<FunctionDecl>( 6798 "void test(int A1) __attribute__((lock_returned(A1)));", FromAttr, 6799 ToAttr); 6800 checkImported(FromAttr->getArg(), ToAttr->getArg()); 6801 } 6802 6803 TEST_P(ImportAttributes, ImportLocksExcluded) { 6804 LocksExcludedAttr *FromAttr, *ToAttr; 6805 importAttr<FunctionDecl>( 6806 "void test(int A1, int A2) __attribute__((locks_excluded(A1, A2)));", 6807 FromAttr, ToAttr); 6808 checkImportVariadicArg(FromAttr->args(), ToAttr->args()); 6809 } 6810 6811 template <typename T> 6812 auto ExtendWithOptions(const T &Values, const std::vector<std::string> &Args) { 6813 auto Copy = Values; 6814 for (std::vector<std::string> &ArgV : Copy) { 6815 for (const std::string &Arg : Args) { 6816 ArgV.push_back(Arg); 6817 } 6818 } 6819 return ::testing::ValuesIn(Copy); 6820 } 6821 6822 struct ImportWithExternalSource : ASTImporterOptionSpecificTestBase { 6823 ImportWithExternalSource() { 6824 Creator = [](ASTContext &ToContext, FileManager &ToFileManager, 6825 ASTContext &FromContext, FileManager &FromFileManager, 6826 bool MinimalImport, 6827 const std::shared_ptr<ASTImporterSharedState> &SharedState) { 6828 return new ASTImporter(ToContext, ToFileManager, FromContext, 6829 // Use minimal import for these tests. 6830 FromFileManager, /*MinimalImport=*/true, 6831 // We use the regular lookup. 6832 /*SharedState=*/nullptr); 6833 }; 6834 } 6835 }; 6836 6837 /// An ExternalASTSource that keeps track of the tags is completed. 6838 struct SourceWithCompletedTagList : clang::ExternalASTSource { 6839 std::vector<clang::TagDecl *> &CompletedTags; 6840 SourceWithCompletedTagList(std::vector<clang::TagDecl *> &CompletedTags) 6841 : CompletedTags(CompletedTags) {} 6842 void CompleteType(TagDecl *Tag) override { 6843 auto *Record = cast<CXXRecordDecl>(Tag); 6844 Record->startDefinition(); 6845 Record->completeDefinition(); 6846 CompletedTags.push_back(Tag); 6847 } 6848 using clang::ExternalASTSource::CompleteType; 6849 }; 6850 6851 TEST_P(ImportWithExternalSource, CompleteRecordBeforeImporting) { 6852 // Create an empty TU. 6853 TranslationUnitDecl *FromTU = getTuDecl("", Lang_CXX03, "input.cpp"); 6854 6855 // Create and add the test ExternalASTSource. 6856 std::vector<clang::TagDecl *> CompletedTags; 6857 IntrusiveRefCntPtr<ExternalASTSource> source = 6858 new SourceWithCompletedTagList(CompletedTags); 6859 clang::ASTContext &Context = FromTU->getASTContext(); 6860 Context.setExternalSource(std::move(source)); 6861 6862 // Create a dummy class by hand with external lexical storage. 6863 IdentifierInfo &Ident = Context.Idents.get("test_class"); 6864 auto *Record = CXXRecordDecl::Create( 6865 Context, TTK_Class, FromTU, SourceLocation(), SourceLocation(), &Ident); 6866 Record->setHasExternalLexicalStorage(); 6867 FromTU->addDecl(Record); 6868 6869 // Do a minimal import of the created class. 6870 EXPECT_EQ(0U, CompletedTags.size()); 6871 Import(Record, Lang_CXX03); 6872 EXPECT_EQ(0U, CompletedTags.size()); 6873 6874 // Import the definition of the created class. 6875 llvm::Error Err = findFromTU(Record)->Importer->ImportDefinition(Record); 6876 EXPECT_FALSE((bool)Err); 6877 consumeError(std::move(Err)); 6878 6879 // Make sure the class was completed once. 6880 EXPECT_EQ(1U, CompletedTags.size()); 6881 EXPECT_EQ(Record, CompletedTags.front()); 6882 } 6883 6884 TEST_P(ImportFunctions, CTADImplicit) { 6885 Decl *FromTU = getTuDecl( 6886 R"( 6887 template <typename T> struct A { 6888 A(T); 6889 }; 6890 A a{(int)0}; 6891 )", 6892 Lang_CXX17, "input.cc"); 6893 auto *FromD = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 6894 FromTU, 6895 cxxDeductionGuideDecl(hasParameter(0, hasType(asString("A<T>"))))); 6896 auto *ToD = Import(FromD, Lang_CXX17); 6897 ASSERT_TRUE(ToD); 6898 EXPECT_TRUE(ToD->isCopyDeductionCandidate()); 6899 // Check that the deduced class template is also imported. 6900 EXPECT_TRUE(findFromTU(FromD)->Importer->GetAlreadyImportedOrNull( 6901 FromD->getDeducedTemplate())); 6902 } 6903 6904 TEST_P(ImportFunctions, CTADUserDefinedExplicit) { 6905 Decl *FromTU = getTuDecl( 6906 R"( 6907 template <typename T> struct A { 6908 A(T); 6909 }; 6910 template <typename T> explicit A(T) -> A<float>; 6911 A a{(int)0}; // calls A<float>::A(float) 6912 )", 6913 Lang_CXX17, "input.cc"); 6914 auto *FromD = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 6915 FromTU, cxxDeductionGuideDecl(unless(isImplicit()))); 6916 // Not-implicit: i.e. not compiler-generated, user defined. 6917 ASSERT_FALSE(FromD->isImplicit()); 6918 ASSERT_TRUE(FromD->isExplicit()); // Has the explicit keyword. 6919 auto *ToD = Import(FromD, Lang_CXX17); 6920 ASSERT_TRUE(ToD); 6921 EXPECT_FALSE(FromD->isImplicit()); 6922 EXPECT_TRUE(ToD->isExplicit()); 6923 } 6924 6925 TEST_P(ImportFunctions, CTADWithLocalTypedef) { 6926 Decl *TU = getTuDecl( 6927 R"( 6928 template <typename T> struct A { 6929 typedef T U; 6930 A(U); 6931 }; 6932 A a{(int)0}; 6933 )", 6934 Lang_CXX17, "input.cc"); 6935 auto *FromD = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 6936 TU, cxxDeductionGuideDecl()); 6937 auto *ToD = Import(FromD, Lang_CXX17); 6938 ASSERT_TRUE(ToD); 6939 } 6940 6941 TEST_P(ImportFunctions, ParmVarDeclDeclContext) { 6942 constexpr auto FromTUCode = R"( 6943 void f(int P); 6944 )"; 6945 Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11); 6946 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 6947 FromTU, functionDecl(hasName("f"))); 6948 ASSERT_TRUE(FromF); 6949 6950 auto *ImportedF = Import(FromF, Lang_CXX11); 6951 EXPECT_TRUE(ImportedF); 6952 EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains( 6953 ImportedF, ImportedF->getParamDecl(0))); 6954 } 6955 6956 // FIXME Move these tests out of ASTImporterTest. For that we need to factor 6957 // out the ASTImporter specific pars from ASTImporterOptionSpecificTestBase 6958 // into a new test Fixture. Then we should lift up this Fixture to its own 6959 // implementation file and only then could we reuse the Fixture in other AST 6960 // unitttests. 6961 struct CTAD : ASTImporterOptionSpecificTestBase {}; 6962 6963 TEST_P(CTAD, DeductionGuideShouldReferToANonLocalTypedef) { 6964 Decl *TU = getTuDecl( 6965 R"( 6966 typedef int U; 6967 template <typename T> struct A { 6968 A(U, T); 6969 }; 6970 A a{(int)0, (int)0}; 6971 )", 6972 Lang_CXX17, "input.cc"); 6973 auto *Guide = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 6974 TU, cxxDeductionGuideDecl()); 6975 auto *Typedef = FirstDeclMatcher<TypedefNameDecl>().match( 6976 TU, typedefNameDecl(hasName("U"))); 6977 ParmVarDecl *Param = Guide->getParamDecl(0); 6978 // The type of the first param (which is a typedef) should match the typedef 6979 // in the global scope. 6980 EXPECT_EQ(Param->getType()->castAs<TypedefType>()->getDecl(), Typedef); 6981 } 6982 6983 TEST_P(CTAD, DeductionGuideShouldReferToANonLocalTypedefInParamPtr) { 6984 Decl *TU = getTuDecl( 6985 R"( 6986 typedef int U; 6987 template <typename T> struct A { 6988 A(U*, T); 6989 }; 6990 A a{(int*)0, (int)0}; 6991 )", 6992 Lang_CXX17, "input.cc"); 6993 auto *Guide = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 6994 TU, cxxDeductionGuideDecl()); 6995 auto *Typedef = FirstDeclMatcher<TypedefNameDecl>().match( 6996 TU, typedefNameDecl(hasName("U"))); 6997 ParmVarDecl *Param = Guide->getParamDecl(0); 6998 EXPECT_EQ(Param->getType() 6999 ->getAs<PointerType>() 7000 ->getPointeeType() 7001 ->getAs<TypedefType>() 7002 ->getDecl(), 7003 Typedef); 7004 } 7005 7006 TEST_P(CTAD, DeductionGuideShouldCopyALocalTypedef) { 7007 Decl *TU = getTuDecl( 7008 R"( 7009 template <typename T> struct A { 7010 typedef T U; 7011 A(U, T); 7012 }; 7013 A a{(int)0, (int)0}; 7014 )", 7015 Lang_CXX17, "input.cc"); 7016 auto *Guide = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 7017 TU, cxxDeductionGuideDecl()); 7018 auto *Typedef = FirstDeclMatcher<TypedefNameDecl>().match( 7019 TU, typedefNameDecl(hasName("U"))); 7020 ParmVarDecl *Param = Guide->getParamDecl(0); 7021 EXPECT_NE(Param->getType()->castAs<TypedefType>()->getDecl(), Typedef); 7022 } 7023 7024 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, CTAD, 7025 DefaultTestValuesForRunOptions); 7026 7027 TEST_P(ASTImporterOptionSpecificTestBase, TypedefWithAttribute) { 7028 Decl *TU = getTuDecl( 7029 R"( 7030 namespace N { 7031 typedef int X __attribute__((annotate("A"))); 7032 } 7033 )", 7034 Lang_CXX17, "input.cc"); 7035 auto *FromD = 7036 FirstDeclMatcher<TypedefDecl>().match(TU, typedefDecl(hasName("X"))); 7037 auto *ToD = Import(FromD, Lang_CXX17); 7038 ASSERT_TRUE(ToD); 7039 ASSERT_EQ(ToD->getAttrs().size(), 1U); 7040 auto *ToAttr = dyn_cast<AnnotateAttr>(ToD->getAttrs()[0]); 7041 ASSERT_TRUE(ToAttr); 7042 EXPECT_EQ(ToAttr->getAnnotation(), "A"); 7043 } 7044 7045 TEST_P(ASTImporterOptionSpecificTestBase, 7046 ImportOfTemplatedDeclWhenPreviousDeclHasNoDescribedTemplateSet) { 7047 Decl *FromTU = getTuDecl( 7048 R"( 7049 7050 namespace std { 7051 template<typename T> 7052 class basic_stringbuf; 7053 } 7054 namespace std { 7055 class char_traits; 7056 template<typename T = char_traits> 7057 class basic_stringbuf; 7058 } 7059 namespace std { 7060 template<typename T> 7061 class basic_stringbuf {}; 7062 } 7063 7064 )", 7065 Lang_CXX11); 7066 7067 auto *From1 = FirstDeclMatcher<ClassTemplateDecl>().match( 7068 FromTU, 7069 classTemplateDecl(hasName("basic_stringbuf"), unless(isImplicit()))); 7070 auto *To1 = cast_or_null<ClassTemplateDecl>(Import(From1, Lang_CXX11)); 7071 EXPECT_TRUE(To1); 7072 7073 auto *From2 = LastDeclMatcher<ClassTemplateDecl>().match( 7074 FromTU, 7075 classTemplateDecl(hasName("basic_stringbuf"), unless(isImplicit()))); 7076 auto *To2 = cast_or_null<ClassTemplateDecl>(Import(From2, Lang_CXX11)); 7077 EXPECT_TRUE(To2); 7078 } 7079 7080 TEST_P(ASTImporterOptionSpecificTestBase, ImportOfCapturedVLAType) { 7081 Decl *FromTU = getTuDecl( 7082 R"( 7083 void declToImport(int N) { 7084 int VLA[N]; 7085 [&VLA] {}; // FieldDecl inside the lambda. 7086 } 7087 )", 7088 Lang_CXX14); 7089 auto *FromFD = FirstDeclMatcher<FieldDecl>().match(FromTU, fieldDecl()); 7090 ASSERT_TRUE(FromFD); 7091 ASSERT_TRUE(FromFD->hasCapturedVLAType()); 7092 7093 auto *ToFD = Import(FromFD, Lang_CXX14); 7094 EXPECT_TRUE(ToFD); 7095 EXPECT_TRUE(ToFD->hasCapturedVLAType()); 7096 EXPECT_NE(FromFD->getCapturedVLAType(), ToFD->getCapturedVLAType()); 7097 } 7098 7099 TEST_P(ASTImporterOptionSpecificTestBase, ImportEnumMemberSpecialization) { 7100 Decl *FromTU = getTuDecl( 7101 R"( 7102 template <class T> struct A { 7103 enum tagname { enumerator }; 7104 }; 7105 template struct A<int>; 7106 )", 7107 Lang_CXX03); 7108 auto *FromD = FirstDeclMatcher<EnumDecl>().match( 7109 FromTU, enumDecl(hasName("tagname"), 7110 hasParent(classTemplateSpecializationDecl()))); 7111 ASSERT_TRUE(FromD); 7112 ASSERT_TRUE(FromD->getMemberSpecializationInfo()); 7113 7114 auto *ToD = Import(FromD, Lang_CXX03); 7115 EXPECT_TRUE(ToD); 7116 EXPECT_TRUE(ToD->getMemberSpecializationInfo()); 7117 EXPECT_EQ(FromD->getTemplateSpecializationKind(), 7118 ToD->getTemplateSpecializationKind()); 7119 } 7120 7121 TEST_P(ASTImporterOptionSpecificTestBase, ImportIsInheritingConstructorBit) { 7122 Decl *FromTU = getTuDecl( 7123 R"( 7124 struct A { 7125 A(int); 7126 }; 7127 struct B : A { 7128 using A::A; // Inherited ctor. 7129 }; 7130 void f() { 7131 (B(0)); 7132 } 7133 )", 7134 Lang_CXX11); 7135 auto *FromD = FirstDeclMatcher<CXXConstructorDecl>().match( 7136 FromTU, cxxConstructorDecl(isInheritingConstructor())); 7137 ASSERT_TRUE(FromD); 7138 ASSERT_TRUE(FromD->isInheritingConstructor()); 7139 7140 auto *ToD = Import(FromD, Lang_CXX11); 7141 ASSERT_TRUE(ToD); 7142 EXPECT_TRUE(ToD->isInheritingConstructor()); 7143 } 7144 7145 TEST_P(ASTImporterOptionSpecificTestBase, ImportConstructorUsingShadow) { 7146 TranslationUnitDecl *FromTU = getTuDecl( 7147 R"( 7148 struct A { 7149 A(int, int); 7150 }; 7151 struct B : A { 7152 using A::A; 7153 }; 7154 struct C : B { 7155 using B::B; 7156 }; 7157 )", 7158 Lang_CXX11); 7159 7160 auto CheckAST = [](TranslationUnitDecl *TU, CXXRecordDecl *RecordC) { 7161 auto *RecordA = FirstDeclMatcher<CXXRecordDecl>().match( 7162 TU, cxxRecordDecl(hasName("A"))); 7163 auto *RecordB = FirstDeclMatcher<CXXRecordDecl>().match( 7164 TU, cxxRecordDecl(hasName("B"))); 7165 auto *ConstrA = FirstDeclMatcher<CXXConstructorDecl>().match( 7166 TU, cxxConstructorDecl(hasParent(equalsNode(RecordA)), 7167 parameterCountIs(2))); 7168 auto *ShadowBA = cast<ConstructorUsingShadowDecl>( 7169 FirstDeclMatcher<UsingShadowDecl>().match( 7170 TU, usingShadowDecl(hasParent(equalsNode(RecordB)), 7171 hasTargetDecl(equalsNode(ConstrA))))); 7172 auto *ShadowCA = cast<ConstructorUsingShadowDecl>( 7173 FirstDeclMatcher<UsingShadowDecl>().match( 7174 TU, usingShadowDecl(hasParent(equalsNode(RecordC)), 7175 hasTargetDecl(equalsNode(ConstrA))))); 7176 EXPECT_EQ(ShadowBA->getTargetDecl(), ConstrA); 7177 EXPECT_EQ(ShadowBA->getNominatedBaseClass(), RecordA); 7178 EXPECT_EQ(ShadowBA->getConstructedBaseClass(), RecordA); 7179 EXPECT_EQ(ShadowBA->getNominatedBaseClassShadowDecl(), nullptr); 7180 EXPECT_EQ(ShadowBA->getConstructedBaseClassShadowDecl(), nullptr); 7181 EXPECT_FALSE(ShadowBA->constructsVirtualBase()); 7182 EXPECT_EQ(ShadowCA->getTargetDecl(), ConstrA); 7183 EXPECT_EQ(ShadowCA->getNominatedBaseClass(), RecordB); 7184 EXPECT_EQ(ShadowCA->getConstructedBaseClass(), RecordB); 7185 EXPECT_EQ(ShadowCA->getNominatedBaseClassShadowDecl(), ShadowBA); 7186 EXPECT_EQ(ShadowCA->getConstructedBaseClassShadowDecl(), ShadowBA); 7187 EXPECT_FALSE(ShadowCA->constructsVirtualBase()); 7188 }; 7189 7190 auto *FromC = FirstDeclMatcher<CXXRecordDecl>().match( 7191 FromTU, cxxRecordDecl(hasName("C"))); 7192 7193 auto *ToC = Import(FromC, Lang_CXX11); 7194 TranslationUnitDecl *ToTU = ToC->getTranslationUnitDecl(); 7195 7196 CheckAST(FromTU, FromC); 7197 CheckAST(ToTU, ToC); 7198 } 7199 7200 AST_MATCHER_P(UsingShadowDecl, hasIntroducerDecl, internal::Matcher<NamedDecl>, 7201 InnerMatcher) { 7202 return InnerMatcher.matches(*Node.getIntroducer(), Finder, Builder); 7203 } 7204 7205 TEST_P(ASTImporterOptionSpecificTestBase, 7206 ImportConstructorUsingShadowVirtualBase) { 7207 TranslationUnitDecl *FromTU = getTuDecl( 7208 R"( 7209 struct A { A(int, int); }; 7210 struct B : A { using A::A; }; 7211 7212 struct V1 : virtual B { using B::B; }; 7213 struct V2 : virtual B { using B::B; }; 7214 7215 struct D2 : V1, V2 { 7216 using V1::V1; 7217 using V2::V2; 7218 }; 7219 )", 7220 Lang_CXX11); 7221 7222 auto CheckAST = [](TranslationUnitDecl *TU, CXXRecordDecl *RecordD2) { 7223 auto *RecordA = FirstDeclMatcher<CXXRecordDecl>().match( 7224 TU, cxxRecordDecl(hasName("A"))); 7225 auto *RecordB = FirstDeclMatcher<CXXRecordDecl>().match( 7226 TU, cxxRecordDecl(hasName("B"))); 7227 auto *RecordV1 = FirstDeclMatcher<CXXRecordDecl>().match( 7228 TU, cxxRecordDecl(hasName("V1"))); 7229 auto *RecordV2 = FirstDeclMatcher<CXXRecordDecl>().match( 7230 TU, cxxRecordDecl(hasName("V2"))); 7231 auto *ConstrA = FirstDeclMatcher<CXXConstructorDecl>().match( 7232 TU, cxxConstructorDecl(hasParent(equalsNode(RecordA)), 7233 parameterCountIs(2))); 7234 auto *ConstrB = FirstDeclMatcher<CXXConstructorDecl>().match( 7235 TU, cxxConstructorDecl(hasParent(equalsNode(RecordB)), 7236 isCopyConstructor())); 7237 auto *UsingD2V1 = FirstDeclMatcher<UsingDecl>().match( 7238 TU, usingDecl(hasParent(equalsNode(RecordD2)))); 7239 auto *UsingD2V2 = LastDeclMatcher<UsingDecl>().match( 7240 TU, usingDecl(hasParent(equalsNode(RecordD2)))); 7241 auto *ShadowBA = cast<ConstructorUsingShadowDecl>( 7242 FirstDeclMatcher<UsingShadowDecl>().match( 7243 TU, usingShadowDecl(hasParent(equalsNode(RecordB)), 7244 hasTargetDecl(equalsNode(ConstrA))))); 7245 auto *ShadowV1A = cast<ConstructorUsingShadowDecl>( 7246 FirstDeclMatcher<UsingShadowDecl>().match( 7247 TU, usingShadowDecl(hasParent(equalsNode(RecordV1)), 7248 hasTargetDecl(equalsNode(ConstrA))))); 7249 auto *ShadowV1B = cast<ConstructorUsingShadowDecl>( 7250 FirstDeclMatcher<UsingShadowDecl>().match( 7251 TU, usingShadowDecl(hasParent(equalsNode(RecordV1)), 7252 hasTargetDecl(equalsNode(ConstrB))))); 7253 auto *ShadowV2A = cast<ConstructorUsingShadowDecl>( 7254 FirstDeclMatcher<UsingShadowDecl>().match( 7255 TU, usingShadowDecl(hasParent(equalsNode(RecordV2)), 7256 hasTargetDecl(equalsNode(ConstrA))))); 7257 auto *ShadowV2B = cast<ConstructorUsingShadowDecl>( 7258 FirstDeclMatcher<UsingShadowDecl>().match( 7259 TU, usingShadowDecl(hasParent(equalsNode(RecordV2)), 7260 hasTargetDecl(equalsNode(ConstrB))))); 7261 auto *ShadowD2V1A = cast<ConstructorUsingShadowDecl>( 7262 FirstDeclMatcher<UsingShadowDecl>().match( 7263 TU, usingShadowDecl(hasParent(equalsNode(RecordD2)), 7264 hasIntroducerDecl(equalsNode(UsingD2V1)), 7265 hasTargetDecl(equalsNode(ConstrA))))); 7266 auto *ShadowD2V1B = cast<ConstructorUsingShadowDecl>( 7267 FirstDeclMatcher<UsingShadowDecl>().match( 7268 TU, usingShadowDecl(hasParent(equalsNode(RecordD2)), 7269 hasIntroducerDecl(equalsNode(UsingD2V1)), 7270 hasTargetDecl(equalsNode(ConstrB))))); 7271 auto *ShadowD2V2A = cast<ConstructorUsingShadowDecl>( 7272 FirstDeclMatcher<UsingShadowDecl>().match( 7273 TU, usingShadowDecl(hasParent(equalsNode(RecordD2)), 7274 hasIntroducerDecl(equalsNode(UsingD2V2)), 7275 hasTargetDecl(equalsNode(ConstrA))))); 7276 auto *ShadowD2V2B = cast<ConstructorUsingShadowDecl>( 7277 FirstDeclMatcher<UsingShadowDecl>().match( 7278 TU, usingShadowDecl(hasParent(equalsNode(RecordD2)), 7279 hasIntroducerDecl(equalsNode(UsingD2V2)), 7280 hasTargetDecl(equalsNode(ConstrB))))); 7281 7282 EXPECT_EQ(ShadowD2V1A->getTargetDecl(), ConstrA); 7283 EXPECT_EQ(ShadowD2V1A->getNominatedBaseClassShadowDecl(), ShadowV1A); 7284 EXPECT_EQ(ShadowD2V1A->getNominatedBaseClass(), RecordV1); 7285 EXPECT_EQ(ShadowD2V1A->getConstructedBaseClassShadowDecl(), ShadowBA); 7286 EXPECT_EQ(ShadowD2V1A->getConstructedBaseClass(), RecordB); 7287 EXPECT_TRUE(ShadowD2V1A->constructsVirtualBase()); 7288 EXPECT_EQ(ShadowD2V1B->getTargetDecl(), ConstrB); 7289 EXPECT_EQ(ShadowD2V1B->getNominatedBaseClassShadowDecl(), ShadowV1B); 7290 EXPECT_EQ(ShadowD2V1B->getNominatedBaseClass(), RecordV1); 7291 EXPECT_EQ(ShadowD2V1B->getConstructedBaseClassShadowDecl(), nullptr); 7292 EXPECT_EQ(ShadowD2V1B->getConstructedBaseClass(), RecordB); 7293 EXPECT_TRUE(ShadowD2V1B->constructsVirtualBase()); 7294 EXPECT_EQ(ShadowD2V2A->getTargetDecl(), ConstrA); 7295 EXPECT_EQ(ShadowD2V2A->getNominatedBaseClassShadowDecl(), ShadowV2A); 7296 EXPECT_EQ(ShadowD2V2A->getNominatedBaseClass(), RecordV2); 7297 EXPECT_EQ(ShadowD2V2A->getConstructedBaseClassShadowDecl(), ShadowBA); 7298 EXPECT_EQ(ShadowD2V2A->getConstructedBaseClass(), RecordB); 7299 EXPECT_TRUE(ShadowD2V2A->constructsVirtualBase()); 7300 EXPECT_EQ(ShadowD2V2B->getTargetDecl(), ConstrB); 7301 EXPECT_EQ(ShadowD2V2B->getNominatedBaseClassShadowDecl(), ShadowV2B); 7302 EXPECT_EQ(ShadowD2V2B->getNominatedBaseClass(), RecordV2); 7303 EXPECT_EQ(ShadowD2V2B->getConstructedBaseClassShadowDecl(), nullptr); 7304 EXPECT_EQ(ShadowD2V2B->getConstructedBaseClass(), RecordB); 7305 EXPECT_TRUE(ShadowD2V2B->constructsVirtualBase()); 7306 7307 EXPECT_TRUE(ShadowV1A->constructsVirtualBase()); 7308 EXPECT_TRUE(ShadowV1B->constructsVirtualBase()); 7309 EXPECT_TRUE(ShadowV2A->constructsVirtualBase()); 7310 EXPECT_TRUE(ShadowV2B->constructsVirtualBase()); 7311 EXPECT_FALSE(ShadowBA->constructsVirtualBase()); 7312 }; 7313 7314 auto *FromD2 = FirstDeclMatcher<CXXRecordDecl>().match( 7315 FromTU, cxxRecordDecl(hasName("D2"))); 7316 7317 auto *ToD2 = Import(FromD2, Lang_CXX11); 7318 TranslationUnitDecl *ToTU = ToD2->getTranslationUnitDecl(); 7319 7320 CheckAST(FromTU, FromD2); 7321 CheckAST(ToTU, ToD2); 7322 } 7323 7324 TEST_P(ASTImporterOptionSpecificTestBase, ImportUsingShadowList) { 7325 TranslationUnitDecl *FromTU = getTuDecl( 7326 R"( 7327 struct A { 7328 void f(); 7329 void f(int); 7330 }; 7331 struct B : A { 7332 using A::f; 7333 }; 7334 )", 7335 Lang_CXX11); 7336 7337 auto *FromB = FirstDeclMatcher<CXXRecordDecl>().match( 7338 FromTU, cxxRecordDecl(hasName("B"))); 7339 7340 auto *ToB = Import(FromB, Lang_CXX11); 7341 TranslationUnitDecl *ToTU = ToB->getTranslationUnitDecl(); 7342 7343 auto *ToUsing = FirstDeclMatcher<UsingDecl>().match( 7344 ToTU, usingDecl(hasParent(equalsNode(ToB)))); 7345 auto *ToUsingShadowF1 = FirstDeclMatcher<UsingShadowDecl>().match( 7346 ToTU, usingShadowDecl(hasTargetDecl( 7347 functionDecl(hasName("f"), parameterCountIs(0))))); 7348 auto *ToUsingShadowF2 = FirstDeclMatcher<UsingShadowDecl>().match( 7349 ToTU, usingShadowDecl(hasTargetDecl( 7350 functionDecl(hasName("f"), parameterCountIs(1))))); 7351 7352 EXPECT_EQ(ToUsing->shadow_size(), 2u); 7353 auto ShadowI = ToUsing->shadow_begin(); 7354 EXPECT_EQ(*ShadowI, ToUsingShadowF1); 7355 ++ShadowI; 7356 EXPECT_EQ(*ShadowI, ToUsingShadowF2); 7357 } 7358 7359 AST_MATCHER_P(FunctionTemplateDecl, templateParameterCountIs, unsigned, Cnt) { 7360 return Node.getTemplateParameters()->size() == Cnt; 7361 } 7362 7363 TEST_P(ASTImporterOptionSpecificTestBase, ImportDeductionGuide) { 7364 TranslationUnitDecl *FromTU = getTuDecl( 7365 R"( 7366 template<class> class A { }; 7367 template<class T> class B { 7368 template<class T1, typename = A<T>> B(T1); 7369 }; 7370 template<class T> 7371 B(T, T) -> B<int>; 7372 )", 7373 Lang_CXX17); 7374 7375 // Get the implicit deduction guide for (non-default) constructor of 'B'. 7376 auto *FromDGCtor = FirstDeclMatcher<FunctionTemplateDecl>().match( 7377 FromTU, functionTemplateDecl(templateParameterCountIs(3))); 7378 // Implicit deduction guide for copy constructor of 'B'. 7379 auto *FromDGCopyCtor = FirstDeclMatcher<FunctionTemplateDecl>().match( 7380 FromTU, functionTemplateDecl(templateParameterCountIs(1), isImplicit())); 7381 // User defined deduction guide. 7382 auto *FromDGOther = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 7383 FromTU, cxxDeductionGuideDecl(unless(isImplicit()))); 7384 7385 TemplateParameterList *FromDGCtorTP = FromDGCtor->getTemplateParameters(); 7386 // Don't know why exactly but this is the DeclContext here. 7387 EXPECT_EQ(FromDGCtorTP->getParam(0)->getDeclContext(), 7388 FromDGCopyCtor->getTemplatedDecl()); 7389 EXPECT_EQ(FromDGCtorTP->getParam(1)->getDeclContext(), 7390 FromDGCtor->getTemplatedDecl()); 7391 EXPECT_EQ(FromDGCtorTP->getParam(2)->getDeclContext(), 7392 FromDGCtor->getTemplatedDecl()); 7393 EXPECT_EQ( 7394 FromDGCopyCtor->getTemplateParameters()->getParam(0)->getDeclContext(), 7395 FromDGCopyCtor->getTemplatedDecl()); 7396 EXPECT_EQ(FromDGOther->getDescribedTemplate() 7397 ->getTemplateParameters() 7398 ->getParam(0) 7399 ->getDeclContext(), 7400 FromDGOther); 7401 7402 auto *ToDGCtor = Import(FromDGCtor, Lang_CXX17); 7403 auto *ToDGCopyCtor = Import(FromDGCopyCtor, Lang_CXX17); 7404 auto *ToDGOther = Import(FromDGOther, Lang_CXX17); 7405 ASSERT_TRUE(ToDGCtor); 7406 ASSERT_TRUE(ToDGCopyCtor); 7407 ASSERT_TRUE(ToDGOther); 7408 7409 TemplateParameterList *ToDGCtorTP = ToDGCtor->getTemplateParameters(); 7410 EXPECT_EQ(ToDGCtorTP->getParam(0)->getDeclContext(), 7411 ToDGCopyCtor->getTemplatedDecl()); 7412 EXPECT_EQ(ToDGCtorTP->getParam(1)->getDeclContext(), 7413 ToDGCtor->getTemplatedDecl()); 7414 EXPECT_EQ(ToDGCtorTP->getParam(2)->getDeclContext(), 7415 ToDGCtor->getTemplatedDecl()); 7416 EXPECT_EQ( 7417 ToDGCopyCtor->getTemplateParameters()->getParam(0)->getDeclContext(), 7418 ToDGCopyCtor->getTemplatedDecl()); 7419 EXPECT_EQ(ToDGOther->getDescribedTemplate() 7420 ->getTemplateParameters() 7421 ->getParam(0) 7422 ->getDeclContext(), 7423 ToDGOther); 7424 } 7425 7426 TEST_P(ASTImporterOptionSpecificTestBase, ImportDeductionGuideDifferentOrder) { 7427 // This test demonstrates that the DeclContext of the imported object is 7428 // dependent on the order of import. The test is an exact copy of the previous 7429 // one except at the indicated locations. 7430 TranslationUnitDecl *FromTU = getTuDecl( 7431 R"( 7432 template<class> class A { }; 7433 template<class T> class B { 7434 template<class T1, typename = A<T>> B(T1); 7435 }; 7436 template<class T> 7437 B(T, T) -> B<int>; 7438 )", 7439 Lang_CXX17); 7440 7441 // Get the implicit deduction guide for (non-default) constructor of 'B'. 7442 auto *FromDGCtor = FirstDeclMatcher<FunctionTemplateDecl>().match( 7443 FromTU, functionTemplateDecl(templateParameterCountIs(3))); 7444 // Implicit deduction guide for copy constructor of 'B'. 7445 auto *FromDGCopyCtor = FirstDeclMatcher<FunctionTemplateDecl>().match( 7446 FromTU, functionTemplateDecl(templateParameterCountIs(1), isImplicit())); 7447 // User defined deduction guide. 7448 auto *FromDGOther = FirstDeclMatcher<CXXDeductionGuideDecl>().match( 7449 FromTU, cxxDeductionGuideDecl(unless(isImplicit()))); 7450 7451 TemplateParameterList *FromDGCtorTP = FromDGCtor->getTemplateParameters(); 7452 // Don't know why exactly but this is the DeclContext here. 7453 EXPECT_EQ(FromDGCtorTP->getParam(0)->getDeclContext(), 7454 FromDGCopyCtor->getTemplatedDecl()); 7455 EXPECT_EQ(FromDGCtorTP->getParam(1)->getDeclContext(), 7456 FromDGCtor->getTemplatedDecl()); 7457 EXPECT_EQ(FromDGCtorTP->getParam(2)->getDeclContext(), 7458 FromDGCtor->getTemplatedDecl()); 7459 EXPECT_EQ( 7460 FromDGCopyCtor->getTemplateParameters()->getParam(0)->getDeclContext(), 7461 FromDGCopyCtor->getTemplatedDecl()); 7462 EXPECT_EQ(FromDGOther->getDescribedTemplate() 7463 ->getTemplateParameters() 7464 ->getParam(0) 7465 ->getDeclContext(), 7466 FromDGOther); 7467 7468 // Here the import of 'ToDGCopyCtor' and 'ToDGCtor' is reversed relative to 7469 // the previous test. 7470 auto *ToDGCopyCtor = Import(FromDGCopyCtor, Lang_CXX17); 7471 auto *ToDGCtor = Import(FromDGCtor, Lang_CXX17); 7472 auto *ToDGOther = Import(FromDGOther, Lang_CXX17); 7473 ASSERT_TRUE(ToDGCtor); 7474 ASSERT_TRUE(ToDGCopyCtor); 7475 ASSERT_TRUE(ToDGOther); 7476 7477 TemplateParameterList *ToDGCtorTP = ToDGCtor->getTemplateParameters(); 7478 // Next line: DeclContext is different relative to the previous test. 7479 EXPECT_EQ(ToDGCtorTP->getParam(0)->getDeclContext(), 7480 ToDGCtor->getTemplatedDecl()); 7481 EXPECT_EQ(ToDGCtorTP->getParam(1)->getDeclContext(), 7482 ToDGCtor->getTemplatedDecl()); 7483 EXPECT_EQ(ToDGCtorTP->getParam(2)->getDeclContext(), 7484 ToDGCtor->getTemplatedDecl()); 7485 // Next line: DeclContext is different relative to the previous test. 7486 EXPECT_EQ( 7487 ToDGCopyCtor->getTemplateParameters()->getParam(0)->getDeclContext(), 7488 ToDGCtor->getTemplatedDecl()); 7489 EXPECT_EQ(ToDGOther->getDescribedTemplate() 7490 ->getTemplateParameters() 7491 ->getParam(0) 7492 ->getDeclContext(), 7493 ToDGOther); 7494 } 7495 7496 TEST_P(ASTImporterOptionSpecificTestBase, 7497 ImportRecordWithLayoutRequestingExpr) { 7498 TranslationUnitDecl *FromTU = getTuDecl( 7499 R"( 7500 struct A { 7501 int idx; 7502 static void foo(A x) { 7503 (void)&"text"[x.idx]; 7504 } 7505 }; 7506 )", 7507 Lang_CXX11); 7508 7509 auto *FromA = FirstDeclMatcher<CXXRecordDecl>().match( 7510 FromTU, cxxRecordDecl(hasName("A"))); 7511 7512 // Test that during import of 'foo' the record layout can be obtained without 7513 // crash. 7514 auto *ToA = Import(FromA, Lang_CXX11); 7515 EXPECT_TRUE(ToA); 7516 EXPECT_TRUE(ToA->isCompleteDefinition()); 7517 } 7518 7519 TEST_P(ASTImporterOptionSpecificTestBase, 7520 ImportRecordWithLayoutRequestingExprDifferentRecord) { 7521 TranslationUnitDecl *FromTU = getTuDecl( 7522 R"( 7523 struct B; 7524 struct A { 7525 int idx; 7526 B *b; 7527 }; 7528 struct B { 7529 static void foo(A x) { 7530 (void)&"text"[x.idx]; 7531 } 7532 }; 7533 )", 7534 Lang_CXX11); 7535 7536 auto *FromA = FirstDeclMatcher<CXXRecordDecl>().match( 7537 FromTU, cxxRecordDecl(hasName("A"))); 7538 7539 // Test that during import of 'foo' the record layout (of 'A') can be obtained 7540 // without crash. It is not possible to have all of the fields of 'A' imported 7541 // at that time (without big code changes). 7542 auto *ToA = Import(FromA, Lang_CXX11); 7543 EXPECT_TRUE(ToA); 7544 EXPECT_TRUE(ToA->isCompleteDefinition()); 7545 } 7546 7547 TEST_P(ASTImporterOptionSpecificTestBase, ImportInClassInitializerFromField) { 7548 // Encounter import of a field when the field already exists but has the 7549 // in-class initializer expression not yet set. Such case can occur in the AST 7550 // of generated template specializations. 7551 // The first code forces to create a template specialization of 7552 // `A<int>` but without implicit constructors. 7553 // The second ("From") code contains a variable of type `A<int>`, this 7554 // results in a template specialization that has constructors and 7555 // CXXDefaultInitExpr nodes. 7556 Decl *ToTU = getToTuDecl( 7557 R"( 7558 void f(); 7559 template<typename> struct A { int X = 1; }; 7560 struct B { A<int> Y; }; 7561 )", 7562 Lang_CXX11); 7563 auto *ToX = FirstDeclMatcher<FieldDecl>().match( 7564 ToTU, 7565 fieldDecl(hasName("X"), hasParent(classTemplateSpecializationDecl()))); 7566 ASSERT_TRUE(ToX->hasInClassInitializer()); 7567 ASSERT_FALSE(ToX->getInClassInitializer()); 7568 7569 Decl *FromTU = getTuDecl( 7570 R"( 7571 void f(); 7572 template<typename> struct A { int X = 1; }; 7573 struct B { A<int> Y; }; 7574 // 7575 A<int> Z; 7576 )", 7577 Lang_CXX11, "input1.cc"); 7578 auto *FromX = FirstDeclMatcher<FieldDecl>().match( 7579 FromTU, 7580 fieldDecl(hasName("X"), hasParent(classTemplateSpecializationDecl()))); 7581 7582 auto *ToXImported = Import(FromX, Lang_CXX11); 7583 EXPECT_EQ(ToXImported, ToX); 7584 EXPECT_TRUE(ToX->getInClassInitializer()); 7585 } 7586 7587 TEST_P(ASTImporterOptionSpecificTestBase, 7588 ImportInClassInitializerFromCXXDefaultInitExpr) { 7589 // Encounter AST import of a CXXDefaultInitExpr where the "to-field" 7590 // of it exists but has the in-class initializer not set yet. 7591 Decl *ToTU = getToTuDecl( 7592 R"( 7593 namespace N { 7594 template<typename> int b; 7595 struct X; 7596 } 7597 template<typename> struct A { N::X *X = nullptr; }; 7598 struct B { A<int> Y; }; 7599 )", 7600 Lang_CXX14); 7601 auto *ToX = FirstDeclMatcher<FieldDecl>().match( 7602 ToTU, 7603 fieldDecl(hasName("X"), hasParent(classTemplateSpecializationDecl()))); 7604 ASSERT_TRUE(ToX->hasInClassInitializer()); 7605 ASSERT_FALSE(ToX->getInClassInitializer()); 7606 7607 Decl *FromTU = getTuDecl( 7608 R"( 7609 namespace N { 7610 template<typename> int b; 7611 struct X; 7612 } 7613 template<typename> struct A { N::X *X = nullptr; }; 7614 struct B { A<int> Y; }; 7615 // 7616 void f() { 7617 (void)A<int>{}; 7618 } 7619 struct C { 7620 C(): attr(new A<int>{}){} 7621 A<int> *attr; 7622 const int value = N::b<C>; 7623 }; 7624 )", 7625 Lang_CXX14, "input1.cc"); 7626 auto *FromF = FirstDeclMatcher<FunctionDecl>().match( 7627 FromTU, functionDecl(hasName("f"), isDefinition())); 7628 auto *ToF = Import(FromF, Lang_CXX11); 7629 EXPECT_TRUE(ToF); 7630 EXPECT_TRUE(ToX->getInClassInitializer()); 7631 } 7632 7633 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest, 7634 DefaultTestValuesForRunOptions); 7635 7636 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportPath, 7637 ::testing::Values(std::vector<std::string>())); 7638 7639 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportExpr, 7640 DefaultTestValuesForRunOptions); 7641 7642 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFixedPointExpr, 7643 ExtendWithOptions(DefaultTestArrayForRunOptions, 7644 std::vector<std::string>{ 7645 "-ffixed-point"})); 7646 7647 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportBlock, 7648 ExtendWithOptions(DefaultTestArrayForRunOptions, 7649 std::vector<std::string>{ 7650 "-fblocks"})); 7651 7652 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportType, 7653 DefaultTestValuesForRunOptions); 7654 7655 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportDecl, 7656 DefaultTestValuesForRunOptions); 7657 7658 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterOptionSpecificTestBase, 7659 DefaultTestValuesForRunOptions); 7660 7661 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ErrorHandlingTest, 7662 DefaultTestValuesForRunOptions); 7663 7664 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, RedirectingImporterTest, 7665 DefaultTestValuesForRunOptions); 7666 7667 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFunctions, 7668 DefaultTestValuesForRunOptions); 7669 7670 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportAutoFunctions, 7671 DefaultTestValuesForRunOptions); 7672 7673 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFunctionTemplates, 7674 DefaultTestValuesForRunOptions); 7675 7676 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFriendFunctionTemplates, 7677 DefaultTestValuesForRunOptions); 7678 7679 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportClasses, 7680 DefaultTestValuesForRunOptions); 7681 7682 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFriendFunctions, 7683 DefaultTestValuesForRunOptions); 7684 7685 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportFriendClasses, 7686 DefaultTestValuesForRunOptions); 7687 7688 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, 7689 ImportFunctionTemplateSpecializations, 7690 DefaultTestValuesForRunOptions); 7691 7692 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportImplicitMethods, 7693 DefaultTestValuesForRunOptions); 7694 7695 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportVariables, 7696 DefaultTestValuesForRunOptions); 7697 7698 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, LLDBLookupTest, 7699 DefaultTestValuesForRunOptions); 7700 7701 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportSourceLocations, 7702 DefaultTestValuesForRunOptions); 7703 7704 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportWithExternalSource, 7705 DefaultTestValuesForRunOptions); 7706 7707 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ImportAttributes, 7708 DefaultTestValuesForRunOptions); 7709 7710 } // end namespace ast_matchers 7711 } // end namespace clang 7712