ExecutionTest.cpp 10 KB

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