ClangCheck.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. //===--- tools/clang-check/ClangCheck.cpp - Clang check tool --------------===//
  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. //
  9. // This file implements a clang-check tool that runs clang based on the info
  10. // stored in a compilation database.
  11. //
  12. // This tool uses the Clang Tooling infrastructure, see
  13. // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
  14. // for details on setting it up with LLVM source tree.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/AST/ASTConsumer.h"
  18. #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
  19. #include "clang/Driver/Options.h"
  20. #include "clang/Frontend/ASTConsumers.h"
  21. #include "clang/Frontend/CompilerInstance.h"
  22. #include "clang/Rewrite/Frontend/FixItRewriter.h"
  23. #include "clang/Rewrite/Frontend/FrontendActions.h"
  24. #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
  25. #include "clang/Tooling/CommonOptionsParser.h"
  26. #include "clang/Tooling/Tooling.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/Option/OptTable.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/Signals.h"
  31. #include "llvm/Support/TargetSelect.h"
  32. using namespace clang::driver;
  33. using namespace clang::tooling;
  34. using namespace llvm;
  35. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  36. static cl::extrahelp MoreHelp(
  37. "\tFor example, to run clang-check on all files in a subtree of the\n"
  38. "\tsource tree, use:\n"
  39. "\n"
  40. "\t find path/in/subtree -name '*.cpp'|xargs clang-check\n"
  41. "\n"
  42. "\tor using a specific build path:\n"
  43. "\n"
  44. "\t find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
  45. "\n"
  46. "\tNote, that path/in/subtree and current directory should follow the\n"
  47. "\trules described above.\n"
  48. "\n"
  49. );
  50. static cl::OptionCategory ClangCheckCategory("clang-check options");
  51. static const opt::OptTable &Options = getDriverOptTable();
  52. static cl::opt<bool>
  53. ASTDump("ast-dump",
  54. cl::desc(Options.getOptionHelpText(options::OPT_ast_dump)),
  55. cl::cat(ClangCheckCategory));
  56. static cl::opt<bool>
  57. ASTList("ast-list",
  58. cl::desc(Options.getOptionHelpText(options::OPT_ast_list)),
  59. cl::cat(ClangCheckCategory));
  60. static cl::opt<bool>
  61. ASTPrint("ast-print",
  62. cl::desc(Options.getOptionHelpText(options::OPT_ast_print)),
  63. cl::cat(ClangCheckCategory));
  64. static cl::opt<std::string> ASTDumpFilter(
  65. "ast-dump-filter",
  66. cl::desc(Options.getOptionHelpText(options::OPT_ast_dump_filter)),
  67. cl::cat(ClangCheckCategory));
  68. static cl::opt<bool>
  69. Analyze("analyze",
  70. cl::desc(Options.getOptionHelpText(options::OPT_analyze)),
  71. cl::cat(ClangCheckCategory));
  72. static cl::opt<bool>
  73. Fixit("fixit", cl::desc(Options.getOptionHelpText(options::OPT_fixit)),
  74. cl::cat(ClangCheckCategory));
  75. static cl::opt<bool> FixWhatYouCan(
  76. "fix-what-you-can",
  77. cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
  78. cl::cat(ClangCheckCategory));
  79. namespace {
  80. // FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
  81. // into a header file and reuse that.
  82. class FixItOptions : public clang::FixItOptions {
  83. public:
  84. FixItOptions() {
  85. FixWhatYouCan = ::FixWhatYouCan;
  86. }
  87. std::string RewriteFilename(const std::string& filename, int &fd) override {
  88. // We don't need to do permission checking here since clang will diagnose
  89. // any I/O errors itself.
  90. fd = -1; // No file descriptor for file.
  91. return filename;
  92. }
  93. };
  94. /// Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
  95. /// in the final error counts.
  96. ///
  97. /// This has the side-effect that clang-check -fixit exits with code 0 on
  98. /// successfully fixing all errors.
  99. class FixItRewriter : public clang::FixItRewriter {
  100. public:
  101. FixItRewriter(clang::DiagnosticsEngine& Diags,
  102. clang::SourceManager& SourceMgr,
  103. const clang::LangOptions& LangOpts,
  104. clang::FixItOptions* FixItOpts)
  105. : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
  106. }
  107. bool IncludeInDiagnosticCounts() const override { return false; }
  108. };
  109. /// Subclasses \c clang::FixItAction so that we can install the custom
  110. /// \c FixItRewriter.
  111. class ClangCheckFixItAction : public clang::FixItAction {
  112. public:
  113. bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
  114. FixItOpts.reset(new FixItOptions);
  115. Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
  116. CI.getLangOpts(), FixItOpts.get()));
  117. return true;
  118. }
  119. };
  120. class ClangCheckActionFactory {
  121. public:
  122. std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
  123. if (ASTList)
  124. return clang::CreateASTDeclNodeLister();
  125. if (ASTDump)
  126. return clang::CreateASTDumper(nullptr /*Dump to stdout.*/, ASTDumpFilter,
  127. /*DumpDecls=*/true,
  128. /*Deserialize=*/false,
  129. /*DumpLookups=*/false,
  130. clang::ADOF_Default);
  131. if (ASTPrint)
  132. return clang::CreateASTPrinter(nullptr, ASTDumpFilter);
  133. return std::make_unique<clang::ASTConsumer>();
  134. }
  135. };
  136. } // namespace
  137. int main(int argc, const char **argv) {
  138. llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  139. // Initialize targets for clang module support.
  140. llvm::InitializeAllTargets();
  141. llvm::InitializeAllTargetMCs();
  142. llvm::InitializeAllAsmPrinters();
  143. llvm::InitializeAllAsmParsers();
  144. CommonOptionsParser OptionsParser(argc, argv, ClangCheckCategory);
  145. ClangTool Tool(OptionsParser.getCompilations(),
  146. OptionsParser.getSourcePathList());
  147. // Clear adjusters because -fsyntax-only is inserted by the default chain.
  148. Tool.clearArgumentsAdjusters();
  149. Tool.appendArgumentsAdjuster(getClangStripOutputAdjuster());
  150. Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
  151. // Running the analyzer requires --analyze. Other modes can work with the
  152. // -fsyntax-only option.
  153. Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
  154. Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
  155. ClangCheckActionFactory CheckFactory;
  156. std::unique_ptr<FrontendActionFactory> FrontendFactory;
  157. // Choose the correct factory based on the selected mode.
  158. if (Analyze)
  159. FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
  160. else if (Fixit)
  161. FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
  162. else
  163. FrontendFactory = newFrontendActionFactory(&CheckFactory);
  164. return Tool.run(FrontendFactory.get());
  165. }