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