1 //===- unittest/AST/ASTImporterTest.cpp - AST node import test ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Tests for the correct import of AST nodes from one AST context to another.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTImporter.h"
16 #include "MatchVerifier.h"
17 #include "clang/ASTMatchers/ASTMatchFinder.h"
18 #include "clang/ASTMatchers/ASTMatchers.h"
19 #include "clang/Tooling/Tooling.h"
20 #include "gtest/gtest.h"
21 
22 namespace clang {
23 namespace ast_matchers {
24 
25 using clang::tooling::newFrontendActionFactory;
26 using clang::tooling::runToolOnCodeWithArgs;
27 using clang::tooling::FrontendActionFactory;
28 
29 typedef std::vector<std::string> StringVector;
30 
31 void getLangArgs(Language Lang, StringVector &Args) {
32   switch (Lang) {
33   case Lang_C:
34     Args.insert(Args.end(), { "-x", "c", "-std=c99" });
35     break;
36   case Lang_C89:
37     Args.insert(Args.end(), { "-x", "c", "-std=c89" });
38     break;
39   case Lang_CXX:
40     Args.push_back("-std=c++98");
41     break;
42   case Lang_CXX11:
43     Args.push_back("-std=c++11");
44     break;
45   case Lang_OpenCL:
46   case Lang_OBJCXX:
47     break;
48   }
49 }
50 
51 template<typename NodeType, typename MatcherType>
52 testing::AssertionResult
53 testImport(const std::string &FromCode, Language FromLang,
54            const std::string &ToCode, Language ToLang,
55            MatchVerifier<NodeType> &Verifier,
56            const MatcherType &AMatcher) {
57   StringVector FromArgs, ToArgs;
58   getLangArgs(FromLang, FromArgs);
59   getLangArgs(ToLang, ToArgs);
60 
61   const char *const InputFileName = "input.cc";
62   const char *const OutputFileName = "output.cc";
63 
64   std::unique_ptr<ASTUnit>
65       FromAST = tooling::buildASTFromCodeWithArgs(
66         FromCode, FromArgs, InputFileName),
67       ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
68 
69   ASTContext &FromCtx = FromAST->getASTContext(),
70       &ToCtx = ToAST->getASTContext();
71 
72   // Add input.cc to virtual file system so importer can 'find' it
73   // while importing SourceLocations.
74   vfs::OverlayFileSystem *OFS = static_cast<vfs::OverlayFileSystem *>(
75         ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get());
76   vfs::InMemoryFileSystem *MFS = static_cast<vfs::InMemoryFileSystem *>(
77         OFS->overlays_begin()->get());
78   MFS->addFile(InputFileName, 0,
79                llvm::MemoryBuffer::getMemBuffer(FromCode.c_str()));
80 
81   ASTImporter Importer(ToCtx, ToAST->getFileManager(),
82                        FromCtx, FromAST->getFileManager(), false);
83 
84   IdentifierInfo *ImportedII = &FromCtx.Idents.get("declToImport");
85   assert(ImportedII && "Declaration with 'declToImport' name"
86                        "should be specified in test!");
87   DeclarationName ImportDeclName(ImportedII);
88   SmallVector<NamedDecl *, 4> FoundDecls;
89   FromCtx.getTranslationUnitDecl()->localUncachedLookup(
90         ImportDeclName, FoundDecls);
91 
92   if (FoundDecls.size() != 1)
93     return testing::AssertionFailure() << "Multiple declarations were found!";
94 
95   auto Imported = Importer.Import(*FoundDecls.begin());
96   if (!Imported)
97     return testing::AssertionFailure() << "Import failed, nullptr returned!";
98 
99   // This should dump source locations and assert if some source locations
100   // were not imported
101   SmallString<1024> ImportChecker;
102   llvm::raw_svector_ostream ToNothing(ImportChecker);
103   ToCtx.getTranslationUnitDecl()->print(ToNothing);
104 
105   return Verifier.match(Imported, AMatcher);
106 }
107 
108 TEST(ImportExpr, ImportStringLiteral) {
109   MatchVerifier<Decl> Verifier;
110   EXPECT_TRUE(testImport("void declToImport() { \"foo\"; }",
111                          Lang_CXX, "", Lang_CXX, Verifier,
112                          functionDecl(
113                            hasBody(
114                              compoundStmt(
115                                has(
116                                  stringLiteral(
117                                    hasType(
118                                      asString("const char [4]")))))))));
119   EXPECT_TRUE(testImport("void declToImport() { L\"foo\"; }",
120                          Lang_CXX, "", Lang_CXX, Verifier,
121                          functionDecl(
122                            hasBody(
123                              compoundStmt(
124                                has(
125                                  stringLiteral(
126                                    hasType(
127                                      asString("const wchar_t [4]")))))))));
128   EXPECT_TRUE(testImport("void declToImport() { \"foo\" \"bar\"; }",
129                          Lang_CXX, "", Lang_CXX, Verifier,
130                          functionDecl(
131                            hasBody(
132                              compoundStmt(
133                                has(
134                                  stringLiteral(
135                                    hasType(
136                                      asString("const char [7]")))))))));
137 }
138 
139 TEST(ImportExpr, ImportGNUNullExpr) {
140   MatchVerifier<Decl> Verifier;
141   EXPECT_TRUE(testImport("void declToImport() { __null; }",
142                          Lang_CXX, "", Lang_CXX, Verifier,
143                          functionDecl(
144                            hasBody(
145                              compoundStmt(
146                                has(
147                                  gnuNullExpr(
148                                    hasType(isInteger()))))))));
149 }
150 
151 TEST(ImportExpr, ImportCXXNullPtrLiteralExpr) {
152   MatchVerifier<Decl> Verifier;
153   EXPECT_TRUE(testImport("void declToImport() { nullptr; }",
154                          Lang_CXX11, "", Lang_CXX11, Verifier,
155                          functionDecl(
156                            hasBody(
157                              compoundStmt(
158                                has(
159                                  cxxNullPtrLiteralExpr()))))));
160 }
161 
162 
163 TEST(ImportExpr, ImportFloatinglLiteralExpr) {
164   MatchVerifier<Decl> Verifier;
165   EXPECT_TRUE(testImport("void declToImport() { 1.0; }",
166                          Lang_CXX, "", Lang_CXX, Verifier,
167                          functionDecl(
168                            hasBody(
169                              compoundStmt(
170                                has(
171                                  floatLiteral(
172                                    equals(1.0),
173                                    hasType(asString("double")))))))));
174   EXPECT_TRUE(testImport("void declToImport() { 1.0e-5f; }",
175                          Lang_CXX, "", Lang_CXX, Verifier,
176                          functionDecl(
177                            hasBody(
178                              compoundStmt(
179                                has(
180                                  floatLiteral(
181                                    equals(1.0e-5f),
182                                    hasType(asString("float")))))))));
183 }
184 
185 TEST(ImportExpr, ImportCompoundLiteralExpr) {
186   MatchVerifier<Decl> Verifier;
187   EXPECT_TRUE(
188         testImport(
189           "void declToImport() {"
190           "  struct s { int x; long y; unsigned z; }; "
191           "  (struct s){ 42, 0L, 1U }; }",
192           Lang_CXX, "", Lang_CXX, Verifier,
193           functionDecl(
194             hasBody(
195               compoundStmt(
196                 has(
197                   compoundLiteralExpr(
198                     hasType(asString("struct s")),
199                     has(initListExpr(
200                       hasType(asString("struct s")),
201                       has(integerLiteral(
202                             equals(42), hasType(asString("int")))),
203                       has(integerLiteral(
204                             equals(0), hasType(asString("long")))),
205                       has(integerLiteral(
206                             equals(1),
207                             hasType(asString("unsigned int"))))
208                       )))))))));
209 }
210 
211 TEST(ImportExpr, ImportCXXThisExpr) {
212   MatchVerifier<Decl> Verifier;
213   EXPECT_TRUE(
214         testImport("class declToImport { void f() { this; } };",
215                    Lang_CXX, "", Lang_CXX, Verifier,
216                    cxxRecordDecl(
217                      hasMethod(
218                        hasBody(
219                          compoundStmt(
220                            has(
221                              cxxThisExpr(
222                                hasType(
223                                  asString("class declToImport *"))))))))));
224 }
225 
226 TEST(ImportExpr, ImportAtomicExpr) {
227   MatchVerifier<Decl> Verifier;
228   EXPECT_TRUE(
229         testImport(
230           "void declToImport() { int *ptr; __atomic_load_n(ptr, 1); }",
231           Lang_CXX, "", Lang_CXX, Verifier,
232           functionDecl(
233             hasBody(
234               compoundStmt(
235                 has(
236                   atomicExpr(
237                     has(declRefExpr(
238                           hasDeclaration(varDecl(hasName("ptr"))),
239                           hasType(asString("int *")))),
240                     has(integerLiteral(equals(1), hasType(asString("int"))))
241                     )))))));
242 }
243 
244 TEST(ImportExpr, ImportLabelDeclAndAddrLabelExpr) {
245   MatchVerifier<Decl> Verifier;
246   EXPECT_TRUE(
247         testImport(
248           "void declToImport() { loop: goto loop; &&loop; }",
249           Lang_CXX, "", Lang_CXX, Verifier,
250           functionDecl(
251             hasBody(
252               compoundStmt(
253                 has(labelStmt(hasDeclaration(labelDecl(hasName("loop"))))),
254                 has(addrLabelExpr(hasDeclaration(labelDecl(hasName("loop")))))
255                 )))));
256 }
257 
258 AST_MATCHER_P(TemplateDecl, hasTemplateDecl,
259               internal::Matcher<NamedDecl>, InnerMatcher) {
260   const NamedDecl *Template = Node.getTemplatedDecl();
261   return Template && InnerMatcher.matches(*Template, Finder, Builder);
262 }
263 
264 TEST(ImportExpr, ImportParenListExpr) {
265   MatchVerifier<Decl> Verifier;
266   EXPECT_TRUE(
267         testImport(
268           "template<typename T> class dummy { void f() { dummy X(*this); } };"
269           "typedef dummy<int> declToImport;"
270           "template class dummy<int>;",
271           Lang_CXX, "", Lang_CXX, Verifier,
272           typedefDecl(
273             hasType(
274               templateSpecializationType(
275                 hasDeclaration(
276                   classTemplateDecl(
277                     hasTemplateDecl(
278                       cxxRecordDecl(
279                         hasMethod(
280                         allOf(
281                           hasName("f"),
282                           hasBody(
283                             compoundStmt(
284                               has(
285                                 declStmt(
286                                   hasSingleDecl(
287                                     varDecl(
288                                       hasInitializer(
289                                         parenListExpr(
290                                           has(
291                                             unaryOperator(
292                                               hasOperatorName("*"),
293                                               hasUnaryOperand(cxxThisExpr())
294                                               )))))))))))))))))))));
295 }
296 
297 TEST(ImportExpr, ImportStmtExpr) {
298   MatchVerifier<Decl> Verifier;
299   // NOTE: has() ignores implicit casts, using hasDescendant() to match it
300   EXPECT_TRUE(
301         testImport(
302           "void declToImport() { int b; int a = b ?: 1; int C = ({int X=4; X;}); }",
303           Lang_CXX, "", Lang_CXX, Verifier,
304           functionDecl(
305             hasBody(
306               compoundStmt(
307                 has(
308                   declStmt(
309                     hasSingleDecl(
310                       varDecl(
311                         hasName("C"),
312                         hasType(asString("int")),
313                         hasInitializer(
314                           stmtExpr(
315                             hasAnySubstatement(
316                               declStmt(
317                                 hasSingleDecl(
318                                   varDecl(
319                                     hasName("X"),
320                                     hasType(asString("int")),
321                                     hasInitializer(
322                                       integerLiteral(equals(4))))))),
323                             hasDescendant(
324                               implicitCastExpr()
325                               ))))))))))));
326 }
327 
328 TEST(ImportExpr, ImportConditionalOperator) {
329   MatchVerifier<Decl> Verifier;
330   EXPECT_TRUE(
331         testImport(
332           "void declToImport() { true ? 1 : -5; }",
333           Lang_CXX, "", Lang_CXX, Verifier,
334           functionDecl(
335             hasBody(
336               compoundStmt(
337                 has(
338                   conditionalOperator(
339                     hasCondition(cxxBoolLiteral(equals(true))),
340                     hasTrueExpression(integerLiteral(equals(1))),
341                     hasFalseExpression(
342                       unaryOperator(hasUnaryOperand(integerLiteral(equals(5))))
343                       ))))))));
344 }
345 
346 TEST(ImportExpr, ImportBinaryConditionalOperator) {
347   MatchVerifier<Decl> Verifier;
348   EXPECT_TRUE(
349         testImport(
350           "void declToImport() { 1 ?: -5; }",
351           Lang_CXX, "", Lang_CXX, Verifier,
352           functionDecl(
353             hasBody(
354               compoundStmt(
355                 has(
356                   binaryConditionalOperator(
357                     hasCondition(
358                       implicitCastExpr(
359                         hasSourceExpression(
360                           opaqueValueExpr(
361                             hasSourceExpression(integerLiteral(equals(1))))),
362                         hasType(booleanType()))),
363                     hasTrueExpression(
364                       opaqueValueExpr(hasSourceExpression(
365                                         integerLiteral(equals(1))))),
366                     hasFalseExpression(
367                       unaryOperator(hasOperatorName("-"),
368                                     hasUnaryOperand(integerLiteral(equals(5)))))
369                       )))))));
370 }
371 
372 TEST(ImportExpr, ImportDesignatedInitExpr) {
373   MatchVerifier<Decl> Verifier;
374   EXPECT_TRUE(testImport("void declToImport() {"
375                          "  struct point { double x; double y; };"
376                          "  struct point ptarray[10] = "
377                                 "{ [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
378                          Lang_C, "", Lang_C, Verifier,
379                          functionDecl(
380                            hasBody(
381                              compoundStmt(
382                                has(
383                                  declStmt(
384                                    hasSingleDecl(
385                                      varDecl(
386                                        hasInitializer(
387                                          initListExpr(
388                                            hasSyntacticForm(
389                                              initListExpr(
390                                                has(
391                                                  designatedInitExpr(
392                                                    designatorCountIs(2),
393                                                    has(floatLiteral(
394                                                          equals(1.0))),
395                                                    has(integerLiteral(
396                                                          equals(2))))),
397                                                has(
398                                                  designatedInitExpr(
399                                                    designatorCountIs(2),
400                                                    has(floatLiteral(
401                                                          equals(2.0))),
402                                                    has(integerLiteral(
403                                                          equals(2))))),
404                                                has(
405                                                  designatedInitExpr(
406                                                    designatorCountIs(2),
407                                                    has(floatLiteral(
408                                                          equals(1.0))),
409                                                    has(integerLiteral(
410                                                          equals(0)))))
411                                                )))))))))))));
412 }
413 
414 
415 TEST(ImportExpr, ImportPredefinedExpr) {
416   MatchVerifier<Decl> Verifier;
417   // __func__ expands as StringLiteral("declToImport")
418   EXPECT_TRUE(testImport("void declToImport() { __func__; }",
419                          Lang_CXX, "", Lang_CXX, Verifier,
420                          functionDecl(
421                            hasBody(
422                              compoundStmt(
423                                has(
424                                  predefinedExpr(
425                                    hasType(
426                                      asString("const char [13]")),
427                                    has(
428                                      stringLiteral(
429                                        hasType(
430                                          asString("const char [13]")))))))))));
431 }
432 
433 TEST(ImportExpr, ImportInitListExpr) {
434   MatchVerifier<Decl> Verifier;
435   EXPECT_TRUE(
436         testImport(
437           "void declToImport() {"
438           "  struct point { double x; double y; };"
439           "  point ptarray[10] = { [2].y = 1.0, [2].x = 2.0,"
440           "                        [0].x = 1.0 }; }",
441           Lang_CXX, "", Lang_CXX, Verifier,
442           functionDecl(
443             hasBody(
444               compoundStmt(
445                 has(
446                   declStmt(
447                     hasSingleDecl(
448                       varDecl(
449                         hasInitializer(
450                           initListExpr(
451                             has(
452                               cxxConstructExpr(
453                                 requiresZeroInitialization())),
454                             has(
455                               initListExpr(
456                                 hasType(asString("struct point")),
457                                 has(floatLiteral(equals(1.0))),
458                                 has(implicitValueInitExpr(
459                                       hasType(asString("double")))))),
460                             has(
461                               initListExpr(
462                                 hasType(asString("struct point")),
463                                 has(floatLiteral(equals(2.0))),
464                                 has(floatLiteral(equals(1.0)))))
465                               )))))))))));
466 }
467 
468 
469 } // end namespace ast_matchers
470 } // end namespace clang
471