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