CommonOptionsParser.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. //===--- CommonOptionsParser.cpp - common options for clang tools ---------===//
  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 the CommonOptionsParser class used to parse common
  10. // command-line options for clang tools, so that they can be run as separate
  11. // command-line applications with a consistent common interface for handling
  12. // compilation database and input files.
  13. //
  14. // It provides a common subset of command-line options, common algorithm
  15. // for locating a compilation database and source files, and help messages
  16. // for the basic command-line interface.
  17. //
  18. // It creates a CompilationDatabase and reads common command-line options.
  19. //
  20. // This class uses the Clang Tooling infrastructure, see
  21. // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
  22. // for details on setting it up with LLVM source tree.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #include "clang/Tooling/CommonOptionsParser.h"
  26. #include "clang/Tooling/Tooling.h"
  27. #include "llvm/Support/CommandLine.h"
  28. using namespace clang::tooling;
  29. using namespace llvm;
  30. const char *const CommonOptionsParser::HelpMessage =
  31. "\n"
  32. "-p <build-path> is used to read a compile command database.\n"
  33. "\n"
  34. "\tFor example, it can be a CMake build directory in which a file named\n"
  35. "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n"
  36. "\tCMake option to get this output). When no build path is specified,\n"
  37. "\ta search for compile_commands.json will be attempted through all\n"
  38. "\tparent paths of the first input file . See:\n"
  39. "\thttps://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n"
  40. "\texample of setting up Clang Tooling on a source tree.\n"
  41. "\n"
  42. "<source0> ... specify the paths of source files. These paths are\n"
  43. "\tlooked up in the compile command database. If the path of a file is\n"
  44. "\tabsolute, it needs to point into CMake's source tree. If the path is\n"
  45. "\trelative, the current working directory needs to be in the CMake\n"
  46. "\tsource tree and the file must be in a subdirectory of the current\n"
  47. "\tworking directory. \"./\" prefixes in the relative files will be\n"
  48. "\tautomatically removed, but the rest of a relative path must be a\n"
  49. "\tsuffix of a path in the compile command database.\n"
  50. "\n";
  51. void ArgumentsAdjustingCompilations::appendArgumentsAdjuster(
  52. ArgumentsAdjuster Adjuster) {
  53. Adjusters.push_back(std::move(Adjuster));
  54. }
  55. std::vector<CompileCommand> ArgumentsAdjustingCompilations::getCompileCommands(
  56. StringRef FilePath) const {
  57. return adjustCommands(Compilations->getCompileCommands(FilePath));
  58. }
  59. std::vector<std::string>
  60. ArgumentsAdjustingCompilations::getAllFiles() const {
  61. return Compilations->getAllFiles();
  62. }
  63. std::vector<CompileCommand>
  64. ArgumentsAdjustingCompilations::getAllCompileCommands() const {
  65. return adjustCommands(Compilations->getAllCompileCommands());
  66. }
  67. std::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(
  68. std::vector<CompileCommand> Commands) const {
  69. for (CompileCommand &Command : Commands)
  70. for (const auto &Adjuster : Adjusters)
  71. Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename);
  72. return Commands;
  73. }
  74. llvm::Error CommonOptionsParser::init(
  75. int &argc, const char **argv, cl::OptionCategory &Category,
  76. llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
  77. static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
  78. cl::Optional, cl::cat(Category),
  79. cl::sub(cl::SubCommand::getAll()));
  80. static cl::list<std::string> SourcePaths(
  81. cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag,
  82. cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
  83. static cl::list<std::string> ArgsAfter(
  84. "extra-arg",
  85. cl::desc("Additional argument to append to the compiler command line"),
  86. cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
  87. static cl::list<std::string> ArgsBefore(
  88. "extra-arg-before",
  89. cl::desc("Additional argument to prepend to the compiler command line"),
  90. cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
  91. cl::ResetAllOptionOccurrences();
  92. cl::HideUnrelatedOptions(Category);
  93. std::string ErrorMessage;
  94. Compilations =
  95. FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
  96. if (!ErrorMessage.empty())
  97. ErrorMessage.append("\n");
  98. llvm::raw_string_ostream OS(ErrorMessage);
  99. // Stop initializing if command-line option parsing failed.
  100. if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
  101. OS.flush();
  102. return llvm::make_error<llvm::StringError>(ErrorMessage,
  103. llvm::inconvertibleErrorCode());
  104. }
  105. cl::PrintOptionValues();
  106. SourcePathList = SourcePaths;
  107. if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
  108. SourcePathList.empty())
  109. return llvm::Error::success();
  110. if (!Compilations) {
  111. if (!BuildPath.empty()) {
  112. Compilations =
  113. CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
  114. } else {
  115. Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
  116. ErrorMessage);
  117. }
  118. if (!Compilations) {
  119. llvm::errs() << "Error while trying to load a compilation database:\n"
  120. << ErrorMessage << "Running without flags.\n";
  121. Compilations.reset(
  122. new FixedCompilationDatabase(".", std::vector<std::string>()));
  123. }
  124. }
  125. auto AdjustingCompilations =
  126. std::make_unique<ArgumentsAdjustingCompilations>(
  127. std::move(Compilations));
  128. Adjuster =
  129. getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN);
  130. Adjuster = combineAdjusters(
  131. std::move(Adjuster),
  132. getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
  133. AdjustingCompilations->appendArgumentsAdjuster(Adjuster);
  134. Compilations = std::move(AdjustingCompilations);
  135. return llvm::Error::success();
  136. }
  137. llvm::Expected<CommonOptionsParser> CommonOptionsParser::create(
  138. int &argc, const char **argv, llvm::cl::OptionCategory &Category,
  139. llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
  140. CommonOptionsParser Parser;
  141. llvm::Error Err =
  142. Parser.init(argc, argv, Category, OccurrencesFlag, Overview);
  143. if (Err)
  144. return std::move(Err);
  145. return std::move(Parser);
  146. }
  147. CommonOptionsParser::CommonOptionsParser(
  148. int &argc, const char **argv, cl::OptionCategory &Category,
  149. llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
  150. llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
  151. if (Err) {
  152. llvm::report_fatal_error(
  153. Twine("CommonOptionsParser: failed to parse command-line arguments. ") +
  154. llvm::toString(std::move(Err)));
  155. }
  156. }