Debian Codegraph @

llvm-project/clang/unittests/AST/ASTImporterTest.cpp

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