blob: 5d881aab1e0d0fd808982b12e26c2ab5fc6c92fd [file] [log] [blame]
Alexander Kornienko01387262012-08-22 20:52:52 +00001//===--- CommonOptionsParser.cpp - common options for clang tools ---------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Kornienko01387262012-08-22 20:52:52 +00006//
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
Alexander Kornienko01387262012-08-22 20:52:52 +000026#include "clang/Tooling/CommonOptionsParser.h"
27#include "clang/Tooling/Tooling.h"
Eric Liue6f85432017-10-24 13:10:58 +000028#include "llvm/Support/CommandLine.h"
Alexander Kornienko01387262012-08-22 20:52:52 +000029
30using namespace clang::tooling;
31using namespace llvm;
32
Alexander Kornienko4bcd58b2012-08-24 00:39:14 +000033const char *const CommonOptionsParser::HelpMessage =
Alexander Kornienko01387262012-08-22 20:52:52 +000034 "\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"
Edwin Vane524741f2012-12-14 18:58:25 +000040 "\ta search for compile_commands.json will be attempted through all\n"
41 "\tparent paths of the first input file . See:\n"
Alexander Kornienkob101c392019-07-01 18:55:10 +000042 "\thttps://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n"
Alexander Kornienko01387262012-08-22 20:52:52 +000043 "\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
Johannes Altmanninger5d2fd552017-08-18 16:21:08 +000055void ArgumentsAdjustingCompilations::appendArgumentsAdjuster(
56 ArgumentsAdjuster Adjuster) {
57 Adjusters.push_back(std::move(Adjuster));
58}
Alexander Kornienko61686092014-11-04 08:51:24 +000059
Johannes Altmanninger5d2fd552017-08-18 16:21:08 +000060std::vector<CompileCommand> ArgumentsAdjustingCompilations::getCompileCommands(
61 StringRef FilePath) const {
62 return adjustCommands(Compilations->getCompileCommands(FilePath));
63}
Alexander Kornienko61686092014-11-04 08:51:24 +000064
Johannes Altmanninger5d2fd552017-08-18 16:21:08 +000065std::vector<std::string>
66ArgumentsAdjustingCompilations::getAllFiles() const {
67 return Compilations->getAllFiles();
68}
Alexander Kornienko61686092014-11-04 08:51:24 +000069
Johannes Altmanninger5d2fd552017-08-18 16:21:08 +000070std::vector<CompileCommand>
71ArgumentsAdjustingCompilations::getAllCompileCommands() const {
72 return adjustCommands(Compilations->getAllCompileCommands());
73}
Alexander Kornienko61686092014-11-04 08:51:24 +000074
Johannes Altmanninger5d2fd552017-08-18 16:21:08 +000075std::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}
Alexander Kornienko61686092014-11-04 08:51:24 +000082
Eric Liue6f85432017-10-24 13:10:58 +000083llvm::Error CommonOptionsParser::init(
Alexander Kornienko3474b552015-08-17 10:01:42 +000084 int &argc, const char **argv, cl::OptionCategory &Category,
85 llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
Alexander Kornienkob5e774e2013-12-12 09:59:42 +000086
87 static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
Alex Lorenz3d712c42017-09-14 13:16:14 +000088 cl::Optional, cl::cat(Category),
89 cl::sub(*cl::AllSubCommands));
Alexander Kornienko9ed8c4e2012-08-28 22:15:41 +000090
91 static cl::list<std::string> SourcePaths(
Alexander Kornienko3474b552015-08-17 10:01:42 +000092 cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag,
Alex Lorenz3d712c42017-09-14 13:16:14 +000093 cl::cat(Category), cl::sub(*cl::AllSubCommands));
Alexander Kornienkob5e774e2013-12-12 09:59:42 +000094
Alexander Kornienko61686092014-11-04 08:51:24 +000095 static cl::list<std::string> ArgsAfter(
96 "extra-arg",
97 cl::desc("Additional argument to append to the compiler command line"),
Alex Lorenz3d712c42017-09-14 13:16:14 +000098 cl::cat(Category), cl::sub(*cl::AllSubCommands));
Alexander Kornienko61686092014-11-04 08:51:24 +000099
100 static cl::list<std::string> ArgsBefore(
101 "extra-arg-before",
102 cl::desc("Additional argument to prepend to the compiler command line"),
Alex Lorenz3d712c42017-09-14 13:16:14 +0000103 cl::cat(Category), cl::sub(*cl::AllSubCommands));
Alexander Kornienko61686092014-11-04 08:51:24 +0000104
Eric Liue6f85432017-10-24 13:10:58 +0000105 cl::ResetAllOptionOccurrences();
106
Chris Bieneman0a9f6072015-01-21 23:26:11 +0000107 cl::HideUnrelatedOptions(Category);
Alexander Kornienko9ed8c4e2012-08-28 22:15:41 +0000108
Serge Pavlovc46064c2017-05-24 11:57:37 +0000109 std::string ErrorMessage;
110 Compilations =
111 FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
Eric Liue6f85432017-10-24 13:10:58 +0000112 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>("[CommonOptionsParser]: " +
119 ErrorMessage,
120 llvm::inconvertibleErrorCode());
121 }
122
Alexander Kornienkoc1694c62016-02-23 10:29:02 +0000123 cl::PrintOptionValues();
124
Alexander Kornienko01387262012-08-22 20:52:52 +0000125 SourcePathList = SourcePaths;
Alexander Kornienko3474b552015-08-17 10:01:42 +0000126 if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
127 SourcePathList.empty())
Eric Liue6f85432017-10-24 13:10:58 +0000128 return llvm::Error::success();
Alexander Kornienko01387262012-08-22 20:52:52 +0000129 if (!Compilations) {
Alexander Kornienko01387262012-08-22 20:52:52 +0000130 if (!BuildPath.empty()) {
David Blaikiecdba84c2014-08-08 16:06:15 +0000131 Compilations =
132 CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
Alexander Kornienko01387262012-08-22 20:52:52 +0000133 } else {
David Blaikiecdba84c2014-08-08 16:06:15 +0000134 Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
135 ErrorMessage);
Alexander Kornienko01387262012-08-22 20:52:52 +0000136 }
Manuel Klimek60033842015-12-03 10:38:53 +0000137 if (!Compilations) {
138 llvm::errs() << "Error while trying to load a compilation database:\n"
139 << ErrorMessage << "Running without flags.\n";
140 Compilations.reset(
141 new FixedCompilationDatabase(".", std::vector<std::string>()));
142 }
Alexander Kornienko01387262012-08-22 20:52:52 +0000143 }
Alexander Kornienko61686092014-11-04 08:51:24 +0000144 auto AdjustingCompilations =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000145 std::make_unique<ArgumentsAdjustingCompilations>(
Alexander Kornienko61686092014-11-04 08:51:24 +0000146 std::move(Compilations));
Eric Liu826b7832017-10-26 10:38:14 +0000147 Adjuster =
148 getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN);
149 Adjuster = combineAdjusters(
150 std::move(Adjuster),
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000151 getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
Eric Liu826b7832017-10-26 10:38:14 +0000152 AdjustingCompilations->appendArgumentsAdjuster(Adjuster);
Alexander Kornienko61686092014-11-04 08:51:24 +0000153 Compilations = std::move(AdjustingCompilations);
Eric Liue6f85432017-10-24 13:10:58 +0000154 return llvm::Error::success();
155}
156
157llvm::Expected<CommonOptionsParser> CommonOptionsParser::create(
158 int &argc, const char **argv, llvm::cl::OptionCategory &Category,
159 llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
160 CommonOptionsParser Parser;
161 llvm::Error Err =
162 Parser.init(argc, argv, Category, OccurrencesFlag, Overview);
163 if (Err)
164 return std::move(Err);
165 return std::move(Parser);
166}
167
168CommonOptionsParser::CommonOptionsParser(
169 int &argc, const char **argv, cl::OptionCategory &Category,
170 llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
171 llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
172 if (Err) {
173 llvm::report_fatal_error(
174 "CommonOptionsParser: failed to parse command-line arguments. " +
175 llvm::toString(std::move(Err)));
176 }
Alexander Kornienko01387262012-08-22 20:52:52 +0000177}