1 //===- unittest/Tooling/ExecutionTest.cpp - Tool execution 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/Tooling/Execution.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/DeclCXX.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/Frontend/FrontendAction.h"
16 #include "clang/Frontend/FrontendActions.h"
17 #include "clang/Tooling/AllTUsExecution.h"
18 #include "clang/Tooling/CompilationDatabase.h"
19 #include "clang/Tooling/StandaloneExecution.h"
20 #include "clang/Tooling/ToolExecutorPluginRegistry.h"
21 #include "clang/Tooling/Tooling.h"
22 #include "gmock/gmock.h"
23 #include "gtest/gtest.h"
24 #include <algorithm>
25 #include <string>
26 
27 namespace clang {
28 namespace tooling {
29 
30 namespace {
31 
32 // This traverses the AST and outputs function name as key and "1" as value for
33 // each function declaration.
34 class ASTConsumerWithResult
35     : public ASTConsumer,
36       public RecursiveASTVisitor<ASTConsumerWithResult> {
37 public:
38   using ASTVisitor = RecursiveASTVisitor<ASTConsumerWithResult>;
39 
40   explicit ASTConsumerWithResult(ExecutionContext *Context) : Context(Context) {
41     assert(Context != nullptr);
42   }
43 
44   void HandleTranslationUnit(clang::ASTContext &Context) override {
45     TraverseDecl(Context.getTranslationUnitDecl());
46   }
47 
48   bool TraverseFunctionDecl(clang::FunctionDecl *Decl) {
49     Context->reportResult(Decl->getNameAsString(),
50                           Context->getRevision() + ":" + Context->getCorpus() +
51                               ":" + Context->getCurrentCompilationUnit() +
52                               "/1");
53     return ASTVisitor::TraverseFunctionDecl(Decl);
54   }
55 
56 private:
57   ExecutionContext *const Context;
58 };
59 
60 class ReportResultAction : public ASTFrontendAction {
61 public:
62   explicit ReportResultAction(ExecutionContext *Context) : Context(Context) {
63     assert(Context != nullptr);
64   }
65 
66 protected:
67   std::unique_ptr<clang::ASTConsumer>
68   CreateASTConsumer(clang::CompilerInstance &compiler,
69                     StringRef /* dummy */) override {
70     std::unique_ptr<clang::ASTConsumer> ast_consumer{
71         new ASTConsumerWithResult(Context)};
72     return ast_consumer;
73   }
74 
75 private:
76   ExecutionContext *const Context;
77 };
78 
79 class ReportResultActionFactory : public FrontendActionFactory {
80 public:
81   ReportResultActionFactory(ExecutionContext *Context) : Context(Context) {}
82   FrontendAction *create() override { return new ReportResultAction(Context); }
83 
84 private:
85   ExecutionContext *const Context;
86 };
87 
88 } // namespace
89 
90 class TestToolExecutor : public ToolExecutor {
91 public:
92   static const char *ExecutorName;
93 
94   TestToolExecutor(CommonOptionsParser Options)
95       : OptionsParser(std::move(Options)) {}
96 
97   StringRef getExecutorName() const override { return ExecutorName; }
98 
99   llvm::Error
100   execute(llvm::ArrayRef<std::pair<std::unique_ptr<FrontendActionFactory>,
101                                    ArgumentsAdjuster>>) override {
102     return llvm::Error::success();
103   }
104 
105   ExecutionContext *getExecutionContext() override { return nullptr; };
106 
107   ToolResults *getToolResults() override { return nullptr; }
108 
109   llvm::ArrayRef<std::string> getSourcePaths() const {
110     return OptionsParser.getSourcePathList();
111   }
112 
113   void mapVirtualFile(StringRef FilePath, StringRef Content) override {
114     VFS[FilePath] = Content;
115   }
116 
117 private:
118   CommonOptionsParser OptionsParser;
119   std::string SourcePaths;
120   std::map<std::string, std::string> VFS;
121 };
122 
123 const char *TestToolExecutor::ExecutorName = "test-executor";
124 
125 class TestToolExecutorPlugin : public ToolExecutorPlugin {
126 public:
127   llvm::Expected<std::unique_ptr<ToolExecutor>>
128   create(CommonOptionsParser &OptionsParser) override {
129     return llvm::make_unique<TestToolExecutor>(std::move(OptionsParser));
130   }
131 };
132 
133 static ToolExecutorPluginRegistry::Add<TestToolExecutorPlugin>
134     X("test-executor", "Plugin for TestToolExecutor.");
135 
136 llvm::cl::OptionCategory TestCategory("execution-test options");
137 
138 TEST(CreateToolExecutorTest, FailedCreateExecutorUndefinedFlag) {
139   std::vector<const char *> argv = {"prog", "--fake_flag_no_no_no", "f"};
140   int argc = argv.size();
141   auto Executor = internal::createExecutorFromCommandLineArgsImpl(
142       argc, &argv[0], TestCategory);
143   ASSERT_FALSE((bool)Executor);
144   llvm::consumeError(Executor.takeError());
145 }
146 
147 TEST(CreateToolExecutorTest, RegisterFlagsBeforeReset) {
148   llvm::cl::opt<std::string> BeforeReset(
149       "before_reset", llvm::cl::desc("Defined before reset."),
150       llvm::cl::init(""));
151 
152   llvm::cl::ResetAllOptionOccurrences();
153 
154   std::vector<const char *> argv = {"prog", "--before_reset=set", "f"};
155   int argc = argv.size();
156   auto Executor = internal::createExecutorFromCommandLineArgsImpl(
157       argc, &argv[0], TestCategory);
158   ASSERT_TRUE((bool)Executor);
159   EXPECT_EQ(BeforeReset, "set");
160   BeforeReset.removeArgument();
161 }
162 
163 TEST(CreateToolExecutorTest, CreateStandaloneToolExecutor) {
164   std::vector<const char *> argv = {"prog", "standalone.cpp"};
165   int argc = argv.size();
166   auto Executor = internal::createExecutorFromCommandLineArgsImpl(
167       argc, &argv[0], TestCategory);
168   ASSERT_TRUE((bool)Executor);
169   EXPECT_EQ(Executor->get()->getExecutorName(),
170             StandaloneToolExecutor::ExecutorName);
171 }
172 
173 TEST(CreateToolExecutorTest, CreateTestToolExecutor) {
174   std::vector<const char *> argv = {"prog", "test.cpp",
175                                     "--executor=test-executor"};
176   int argc = argv.size();
177   auto Executor = internal::createExecutorFromCommandLineArgsImpl(
178       argc, &argv[0], TestCategory);
179   ASSERT_TRUE((bool)Executor);
180   EXPECT_EQ(Executor->get()->getExecutorName(), TestToolExecutor::ExecutorName);
181 }
182 
183 TEST(StandaloneToolTest, SynctaxOnlyActionOnSimpleCode) {
184   FixedCompilationDatabase Compilations(".", std::vector<std::string>());
185   StandaloneToolExecutor Executor(Compilations,
186                                   std::vector<std::string>(1, "a.cc"));
187   Executor.mapVirtualFile("a.cc", "int x = 0;");
188 
189   auto Err = Executor.execute(newFrontendActionFactory<SyntaxOnlyAction>(),
190                               getClangSyntaxOnlyAdjuster());
191   ASSERT_TRUE(!Err);
192 }
193 
194 TEST(StandaloneToolTest, SimpleAction) {
195   FixedCompilationDatabase Compilations(".", std::vector<std::string>());
196   StandaloneToolExecutor Executor(Compilations,
197                                   std::vector<std::string>(1, "a.cc"));
198   Executor.mapVirtualFile("a.cc", "int x = 0;");
199 
200   auto Err = Executor.execute(std::unique_ptr<FrontendActionFactory>(
201       new ReportResultActionFactory(Executor.getExecutionContext())));
202   ASSERT_TRUE(!Err);
203   auto KVs = Executor.getToolResults()->AllKVResults();
204   ASSERT_EQ(KVs.size(), 0u);
205 }
206 
207 TEST(StandaloneToolTest, SimpleActionWithResult) {
208   FixedCompilationDatabase Compilations(".", std::vector<std::string>());
209   StandaloneToolExecutor Executor(Compilations,
210                                   std::vector<std::string>(1, "a.cc"));
211   Executor.mapVirtualFile("a.cc", "int x = 0; void f() {}");
212 
213   auto Err = Executor.execute(std::unique_ptr<FrontendActionFactory>(
214       new ReportResultActionFactory(Executor.getExecutionContext())));
215   ASSERT_TRUE(!Err);
216   auto KVs = Executor.getToolResults()->AllKVResults();
217   ASSERT_EQ(KVs.size(), 1u);
218   EXPECT_EQ("f", KVs[0].first);
219   // Currently the standlone executor returns empty corpus, revision, and
220   // compilation unit.
221   EXPECT_EQ("::/1", KVs[0].second);
222 
223   Executor.getToolResults()->forEachResult(
224       [](StringRef, StringRef Value) { EXPECT_EQ("::/1", Value); });
225 }
226 
227 class FixedCompilationDatabaseWithFiles : public CompilationDatabase {
228 public:
229   FixedCompilationDatabaseWithFiles(Twine Directory,
230                                     ArrayRef<std::string> Files,
231                                     ArrayRef<std::string> CommandLine)
232       : FixedCompilations(Directory, CommandLine), Files(Files) {}
233 
234   std::vector<CompileCommand>
235   getCompileCommands(StringRef FilePath) const override {
236     return FixedCompilations.getCompileCommands(FilePath);
237   }
238 
239   std::vector<std::string> getAllFiles() const override { return Files; }
240 
241 private:
242   FixedCompilationDatabase FixedCompilations;
243   std::vector<std::string> Files;
244 };
245 
246 MATCHER_P(Named, Name, "") { return arg.first == Name; }
247 
248 TEST(AllTUsToolTest, AFewFiles) {
249   FixedCompilationDatabaseWithFiles Compilations(".", {"a.cc", "b.cc", "c.cc"},
250                                                  std::vector<std::string>());
251   AllTUsToolExecutor Executor(Compilations, /*ThreadCount=*/0);
252   Executor.mapVirtualFile("a.cc", "void x() {}");
253   Executor.mapVirtualFile("b.cc", "void y() {}");
254   Executor.mapVirtualFile("c.cc", "void z() {}");
255 
256   auto Err = Executor.execute(std::unique_ptr<FrontendActionFactory>(
257       new ReportResultActionFactory(Executor.getExecutionContext())));
258   ASSERT_TRUE(!Err);
259   EXPECT_THAT(
260       Executor.getToolResults()->AllKVResults(),
261       ::testing::UnorderedElementsAre(Named("x"), Named("y"), Named("z")));
262 }
263 
264 TEST(AllTUsToolTest, ManyFiles) {
265   unsigned NumFiles = 100;
266   std::vector<std::string> Files;
267   std::map<std::string, std::string> FileToContent;
268   std::vector<std::string> ExpectedSymbols;
269   for (unsigned i = 1; i <= NumFiles; ++i) {
270     std::string File = "f" + std::to_string(i) + ".cc";
271     std::string Symbol = "looong_function_name_" + std::to_string(i);
272     Files.push_back(File);
273     FileToContent[File] = "void " + Symbol + "() {}";
274     ExpectedSymbols.push_back(Symbol);
275   }
276   FixedCompilationDatabaseWithFiles Compilations(".", Files,
277                                                  std::vector<std::string>());
278   AllTUsToolExecutor Executor(Compilations, /*ThreadCount=*/0);
279   for (const auto &FileAndContent : FileToContent) {
280     Executor.mapVirtualFile(FileAndContent.first, FileAndContent.second);
281   }
282 
283   auto Err = Executor.execute(std::unique_ptr<FrontendActionFactory>(
284       new ReportResultActionFactory(Executor.getExecutionContext())));
285   ASSERT_TRUE(!Err);
286   std::vector<std::string> Results;
287   Executor.getToolResults()->forEachResult(
288       [&](StringRef Name, StringRef) { Results.push_back(Name); });
289   EXPECT_THAT(ExpectedSymbols, ::testing::UnorderedElementsAreArray(Results));
290 }
291 
292 } // end namespace tooling
293 } // end namespace clang
294