clang  6.0.0svn
CommonOptionsParser.cpp
Go to the documentation of this file.
1 //===--- CommonOptionsParser.cpp - common options for clang tools ---------===//
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 // This file implements the CommonOptionsParser class used to parse common
11 // command-line options for clang tools, so that they can be run as separate
12 // command-line applications with a consistent common interface for handling
13 // compilation database and input files.
14 //
15 // It provides a common subset of command-line options, common algorithm
16 // for locating a compilation database and source files, and help messages
17 // for the basic command-line interface.
18 //
19 // It creates a CompilationDatabase and reads common command-line options.
20 //
21 // This class uses the Clang Tooling infrastructure, see
22 // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
23 // for details on setting it up with LLVM source tree.
24 //
25 //===----------------------------------------------------------------------===//
26 
28 #include "clang/Tooling/Tooling.h"
29 #include "llvm/Support/CommandLine.h"
30 
31 using namespace clang::tooling;
32 using namespace llvm;
33 
34 const char *const CommonOptionsParser::HelpMessage =
35  "\n"
36  "-p <build-path> is used to read a compile command database.\n"
37  "\n"
38  "\tFor example, it can be a CMake build directory in which a file named\n"
39  "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n"
40  "\tCMake option to get this output). When no build path is specified,\n"
41  "\ta search for compile_commands.json will be attempted through all\n"
42  "\tparent paths of the first input file . See:\n"
43  "\thttp://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n"
44  "\texample of setting up Clang Tooling on a source tree.\n"
45  "\n"
46  "<source0> ... specify the paths of source files. These paths are\n"
47  "\tlooked up in the compile command database. If the path of a file is\n"
48  "\tabsolute, it needs to point into CMake's source tree. If the path is\n"
49  "\trelative, the current working directory needs to be in the CMake\n"
50  "\tsource tree and the file must be in a subdirectory of the current\n"
51  "\tworking directory. \"./\" prefixes in the relative files will be\n"
52  "\tautomatically removed, but the rest of a relative path must be a\n"
53  "\tsuffix of a path in the compile command database.\n"
54  "\n";
55 
57  ArgumentsAdjuster Adjuster) {
58  Adjusters.push_back(std::move(Adjuster));
59 }
60 
62  StringRef FilePath) const {
63  return adjustCommands(Compilations->getCompileCommands(FilePath));
64 }
65 
66 std::vector<std::string>
68  return Compilations->getAllFiles();
69 }
70 
71 std::vector<CompileCommand>
73  return adjustCommands(Compilations->getAllCompileCommands());
74 }
75 
76 std::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(
77  std::vector<CompileCommand> Commands) const {
78  for (CompileCommand &Command : Commands)
79  for (const auto &Adjuster : Adjusters)
80  Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename);
81  return Commands;
82 }
83 
84 llvm::Error CommonOptionsParser::init(
85  int &argc, const char **argv, cl::OptionCategory &Category,
86  llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
87  static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden,
88  cl::sub(*cl::AllSubCommands));
89 
90  static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
91  cl::Optional, cl::cat(Category),
92  cl::sub(*cl::AllSubCommands));
93 
94  static cl::list<std::string> SourcePaths(
95  cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag,
96  cl::cat(Category), cl::sub(*cl::AllSubCommands));
97 
98  static cl::list<std::string> ArgsAfter(
99  "extra-arg",
100  cl::desc("Additional argument to append to the compiler command line"),
101  cl::cat(Category), cl::sub(*cl::AllSubCommands));
102 
103  static cl::list<std::string> ArgsBefore(
104  "extra-arg-before",
105  cl::desc("Additional argument to prepend to the compiler command line"),
106  cl::cat(Category), cl::sub(*cl::AllSubCommands));
107 
108  cl::ResetAllOptionOccurrences();
109 
110  cl::HideUnrelatedOptions(Category);
111 
112  std::string ErrorMessage;
113  Compilations =
114  FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
115  if (!ErrorMessage.empty())
116  ErrorMessage.append("\n");
117  llvm::raw_string_ostream OS(ErrorMessage);
118  // Stop initializing if command-line option parsing failed.
119  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
120  OS.flush();
121  return llvm::make_error<llvm::StringError>("[CommonOptionsParser]: " +
122  ErrorMessage,
123  llvm::inconvertibleErrorCode());
124  }
125 
126  cl::PrintOptionValues();
127 
128  SourcePathList = SourcePaths;
129  if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
130  SourcePathList.empty())
131  return llvm::Error::success();
132  if (!Compilations) {
133  if (!BuildPath.empty()) {
134  Compilations =
135  CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
136  } else {
137  Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
138  ErrorMessage);
139  }
140  if (!Compilations) {
141  llvm::errs() << "Error while trying to load a compilation database:\n"
142  << ErrorMessage << "Running without flags.\n";
143  Compilations.reset(
144  new FixedCompilationDatabase(".", std::vector<std::string>()));
145  }
146  }
147  auto AdjustingCompilations =
148  llvm::make_unique<ArgumentsAdjustingCompilations>(
149  std::move(Compilations));
150  Adjuster =
152  Adjuster = combineAdjusters(
153  std::move(Adjuster),
155  AdjustingCompilations->appendArgumentsAdjuster(Adjuster);
156  Compilations = std::move(AdjustingCompilations);
157  return llvm::Error::success();
158 }
159 
161  int &argc, const char **argv, llvm::cl::OptionCategory &Category,
162  llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
164  llvm::Error Err =
165  Parser.init(argc, argv, Category, OccurrencesFlag, Overview);
166  if (Err)
167  return std::move(Err);
168  return std::move(Parser);
169 }
170 
171 CommonOptionsParser::CommonOptionsParser(
172  int &argc, const char **argv, cl::OptionCategory &Category,
173  llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
174  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
175  if (Err) {
176  llvm::report_fatal_error(
177  "CommonOptionsParser: failed to parse command-line arguments. " +
178  llvm::toString(std::move(Err)));
179  }
180 }
static std::unique_ptr< CompilationDatabase > autoDetectFromDirectory(StringRef SourceDir, std::string &ErrorMessage)
Tries to detect a compilation database location and load it.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:26
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
ArgumentsAdjuster getInsertArgumentAdjuster(const CommandLineArguments &Extra, ArgumentInsertPosition Pos)
Gets an argument adjuster which inserts Extra arguments in the specified position.
ArgumentsAdjuster combineAdjusters(ArgumentsAdjuster First, ArgumentsAdjuster Second)
Gets an argument adjuster which adjusts the arguments in sequence with the First adjuster and then wi...
int Category
Definition: Format.cpp:1348
std::vector< CompileCommand > getCompileCommands(StringRef FilePath) const override
Returns all compile commands in which the specified file was compiled.
std::vector< std::string > getAllFiles() const override
Returns the list of all files available in the compilation database.
std::function< CommandLineArguments(const CommandLineArguments &, StringRef Filename)> ArgumentsAdjuster
A prototype of a command line adjuster.
static std::unique_ptr< FixedCompilationDatabase > loadFromCommandLine(int &Argc, const char *const *Argv, std::string &ErrorMsg, Twine Directory=".")
Creates a FixedCompilationDatabase from the arguments after "--".
Specifies the working directory and command of a compilation.
A parser for options common to all command-line Clang tools.
static std::unique_ptr< CompilationDatabase > autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage)
Tries to detect a compilation database location and load it.
void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster)
static llvm::Expected< CommonOptionsParser > create(int &argc, const char **argv, llvm::cl::OptionCategory &Category, llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview=nullptr)
A factory method that is similar to the above constructor, except this returns an error instead exiti...
std::string toString(const til::SExpr *E)
std::vector< CompileCommand > getAllCompileCommands() const override
Returns all compile commands for all the files in the compilation database.
A compilation database that returns a single compile command line.