1 //===- unittests/Frontend/FrontendActionTest.cpp - FrontendAction tests ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/AST/RecursiveASTVisitor.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Frontend/CompilerInvocation.h"
15 #include "clang/Frontend/FrontendAction.h"
16 
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 
20 #include "gtest/gtest.h"
21 
22 using namespace llvm;
23 using namespace clang;
24 
25 namespace {
26 
27 class TestASTFrontendAction : public ASTFrontendAction {
28 public:
29   std::vector<std::string> decl_names;
30 
31   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
32                                          StringRef InFile) {
33     return new Visitor(decl_names);
34   }
35 
36 private:
37   class Visitor : public ASTConsumer, public RecursiveASTVisitor<Visitor> {
38   public:
39     Visitor(std::vector<std::string> &decl_names) : decl_names_(decl_names) {}
40 
41     virtual void HandleTranslationUnit(ASTContext &context) {
42       TraverseDecl(context.getTranslationUnitDecl());
43     }
44 
45     virtual bool VisitNamedDecl(NamedDecl *Decl) {
46       decl_names_.push_back(Decl->getQualifiedNameAsString());
47       return true;
48     }
49 
50   private:
51     std::vector<std::string> &decl_names_;
52   };
53 };
54 
55 TEST(ASTFrontendAction, Sanity) {
56   CompilerInvocation *invocation = new CompilerInvocation;
57   invocation->getPreprocessorOpts().addRemappedFile(
58     "test.cc", MemoryBuffer::getMemBuffer("int main() { float x; }"));
59   invocation->getFrontendOpts().Inputs.push_back(FrontendInputFile("test.cc",
60                                                                    IK_CXX));
61   invocation->getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly;
62   invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu";
63   CompilerInstance compiler;
64   compiler.setInvocation(invocation);
65   compiler.createDiagnostics(0, NULL);
66 
67   TestASTFrontendAction test_action;
68   ASSERT_TRUE(compiler.ExecuteAction(test_action));
69   ASSERT_EQ(3U, test_action.decl_names.size());
70   EXPECT_EQ("__builtin_va_list", test_action.decl_names[0]);
71   EXPECT_EQ("main", test_action.decl_names[1]);
72   EXPECT_EQ("x", test_action.decl_names[2]);
73 }
74 
75 } // anonymous namespace
76