Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/CommonOptionsParser.cpp
Line
Count
Source (jump to first uncovered line)
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
26
#include "clang/Tooling/CommonOptionsParser.h"
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
55
void ArgumentsAdjustingCompilations::appendArgumentsAdjuster(
56
303
    ArgumentsAdjuster Adjuster) {
57
303
  Adjusters.push_back(std::move(Adjuster));
58
303
}
59
60
std::vector<CompileCommand> ArgumentsAdjustingCompilations::getCompileCommands(
61
219
    StringRef FilePath) const {
62
219
  return adjustCommands(Compilations->getCompileCommands(FilePath));
63
219
}
64
65
std::vector<std::string>
66
0
ArgumentsAdjustingCompilations::getAllFiles() const {
67
0
  return Compilations->getAllFiles();
68
0
}
69
70
std::vector<CompileCommand>
71
144
ArgumentsAdjustingCompilations::getAllCompileCommands() const {
72
144
  return adjustCommands(Compilations->getAllCompileCommands());
73
144
}
74
75
std::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(
76
363
    std::vector<CompileCommand> Commands) const {
77
363
  for (CompileCommand &Command : Commands)
78
472
    for (const auto &Adjuster : Adjusters)
79
489
      Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename);
80
363
  return Commands;
81
363
}
82
83
llvm::Error CommonOptionsParser::init(
84
    int &argc, const char **argv, cl::OptionCategory &Category,
85
139
    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
86
87
139
  static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
88
139
                                        cl::Optional, cl::cat(Category),
89
139
                                        cl::sub(cl::SubCommand::getAll()));
90
91
139
  static cl::list<std::string> SourcePaths(
92
139
      cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag,
93
139
      cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
94
95
139
  static cl::list<std::string> ArgsAfter(
96
139
      "extra-arg",
97
139
      cl::desc("Additional argument to append to the compiler command line"),
98
139
      cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
99
100
139
  static cl::list<std::string> ArgsBefore(
101
139
      "extra-arg-before",
102
139
      cl::desc("Additional argument to prepend to the compiler command line"),
103
139
      cl::cat(Category), cl::sub(cl::SubCommand::getAll()));
104
105
139
  cl::ResetAllOptionOccurrences();
106
107
139
  cl::HideUnrelatedOptions(Category);
108
109
139
  std::string ErrorMessage;
110
139
  Compilations =
111
139
      FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
112
139
  if (!ErrorMessage.empty())
113
0
    ErrorMessage.append("\n");
114
139
  llvm::raw_string_ostream OS(ErrorMessage);
115
  // Stop initializing if command-line option parsing failed.
116
139
  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
117
1
    OS.flush();
118
1
    return llvm::make_error<llvm::StringError>(ErrorMessage,
119
1
                                               llvm::inconvertibleErrorCode());
120
1
  }
121
122
138
  cl::PrintOptionValues();
123
124
138
  SourcePathList = SourcePaths;
125
138
  if ((OccurrencesFlag == cl::ZeroOrMore || 
OccurrencesFlag == cl::Optional113
) &&
126
138
      
SourcePathList.empty()25
)
127
1
    return llvm::Error::success();
128
137
  if (!Compilations) {
129
24
    if (!BuildPath.empty()) {
130
10
      Compilations =
131
10
          CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
132
14
    } else {
133
14
      Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
134
14
                                                               ErrorMessage);
135
14
    }
136
24
    if (!Compilations) {
137
2
      llvm::errs() << "Error while trying to load a compilation database:\n"
138
2
                   << ErrorMessage << "Running without flags.\n";
139
2
      Compilations.reset(
140
2
          new FixedCompilationDatabase(".", std::vector<std::string>()));
141
2
    }
142
24
  }
143
137
  auto AdjustingCompilations =
144
137
      std::make_unique<ArgumentsAdjustingCompilations>(
145
137
          std::move(Compilations));
146
137
  Adjuster =
147
137
      getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN);
148
137
  Adjuster = combineAdjusters(
149
137
      std::move(Adjuster),
150
137
      getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
151
137
  AdjustingCompilations->appendArgumentsAdjuster(Adjuster);
152
137
  Compilations = std::move(AdjustingCompilations);
153
137
  return llvm::Error::success();
154
138
}
155
156
llvm::Expected<CommonOptionsParser> CommonOptionsParser::create(
157
    int &argc, const char **argv, llvm::cl::OptionCategory &Category,
158
139
    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
159
139
  CommonOptionsParser Parser;
160
139
  llvm::Error Err =
161
139
      Parser.init(argc, argv, Category, OccurrencesFlag, Overview);
162
139
  if (Err)
163
1
    return std::move(Err);
164
138
  return std::move(Parser);
165
139
}
166
167
CommonOptionsParser::CommonOptionsParser(
168
    int &argc, const char **argv, cl::OptionCategory &Category,
169
0
    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
170
0
  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
171
0
  if (Err) {
172
0
    llvm::report_fatal_error(
173
0
        Twine("CommonOptionsParser: failed to parse command-line arguments. ") +
174
0
        llvm::toString(std::move(Err)));
175
0
  }
176
0
}