1//===- ArgList.cpp - Argument List Management -----------------------------===//
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#include "llvm/Option/ArgList.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/Config/llvm-config.h"
16#include "llvm/Option/Arg.h"
17#include "llvm/Option/OptSpecifier.h"
18#include "llvm/Option/OptTable.h"
19#include "llvm/Option/Option.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/raw_ostream.h"
23#include <algorithm>
24#include <cassert>
25#include <memory>
26#include <string>
27#include <vector>
28
29using namespace llvm;
30using namespace llvm::opt;
31
32void ArgList::append(Arg *A) {
33 Args.push_back(Elt: A);
34
35 // Update ranges for the option and all of its groups.
36 for (Option O = A->getOption().getUnaliasedOption(); O.isValid();
37 O = O.getGroup()) {
38 auto &R =
39 OptRanges.insert(KV: std::make_pair(x: O.getID(), y: emptyRange())).first->second;
40 R.first = std::min<unsigned>(a: R.first, b: Args.size() - 1);
41 R.second = Args.size();
42 }
43}
44
45void ArgList::eraseArg(OptSpecifier Id) {
46 // Zero out the removed entries but keep them around so that we don't
47 // need to invalidate OptRanges.
48 for (Arg *const &A : filtered(Ids: Id)) {
49 // Avoid the need for a non-const filtered iterator variant.
50 Arg **ArgsBegin = Args.data();
51 ArgsBegin[&A - ArgsBegin] = nullptr;
52 }
53 OptRanges.erase(Val: Id.getID());
54}
55
56ArgList::OptRange
57ArgList::getRange(std::initializer_list<OptSpecifier> Ids) const {
58 OptRange R = emptyRange();
59 for (auto Id : Ids) {
60 auto I = OptRanges.find(Val: Id.getID());
61 if (I != OptRanges.end()) {
62 R.first = std::min(a: R.first, b: I->second.first);
63 R.second = std::max(a: R.second, b: I->second.second);
64 }
65 }
66 // Map an empty {-1, 0} range to {0, 0} so it can be used to form iterators.
67 if (R.first == -1u)
68 R.first = 0;
69 return R;
70}
71
72bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const {
73 if (Arg *A = getLastArg(Ids: Pos, Ids: Neg))
74 return A->getOption().matches(ID: Pos);
75 return Default;
76}
77
78bool ArgList::hasFlagNoClaim(OptSpecifier Pos, OptSpecifier Neg,
79 bool Default) const {
80 if (Arg *A = getLastArgNoClaim(Ids: Pos, Ids: Neg))
81 return A->getOption().matches(ID: Pos);
82 return Default;
83}
84
85bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
86 bool Default) const {
87 if (Arg *A = getLastArg(Ids: Pos, Ids: PosAlias, Ids: Neg))
88 return A->getOption().matches(ID: Pos) || A->getOption().matches(ID: PosAlias);
89 return Default;
90}
91
92StringRef ArgList::getLastArgValue(OptSpecifier Id, StringRef Default) const {
93 if (Arg *A = getLastArg(Ids: Id))
94 return A->getValue();
95 return Default;
96}
97
98std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const {
99 SmallVector<const char *, 16> Values;
100 AddAllArgValues(Output&: Values, Id0: Id);
101 return std::vector<std::string>(Values.begin(), Values.end());
102}
103
104void ArgList::addOptInFlag(ArgStringList &Output, OptSpecifier Pos,
105 OptSpecifier Neg) const {
106 if (Arg *A = getLastArg(Ids: Pos, Ids: Neg))
107 if (A->getOption().matches(ID: Pos))
108 A->render(Args: *this, Output);
109}
110
111void ArgList::AddAllArgsExcept(ArgStringList &Output,
112 ArrayRef<OptSpecifier> Ids,
113 ArrayRef<OptSpecifier> ExcludeIds) const {
114 for (const Arg *Arg : *this) {
115 bool Excluded = false;
116 for (OptSpecifier Id : ExcludeIds) {
117 if (Arg->getOption().matches(ID: Id)) {
118 Excluded = true;
119 break;
120 }
121 }
122 if (!Excluded) {
123 for (OptSpecifier Id : Ids) {
124 if (Arg->getOption().matches(ID: Id)) {
125 Arg->claim();
126 Arg->render(Args: *this, Output);
127 break;
128 }
129 }
130 }
131 }
132}
133
134/// This is a nicer interface when you don't have a list of Ids to exclude.
135void ArgList::addAllArgs(ArgStringList &Output,
136 ArrayRef<OptSpecifier> Ids) const {
137 ArrayRef<OptSpecifier> Exclude = {};
138 AddAllArgsExcept(Output, Ids, ExcludeIds: Exclude);
139}
140
141void ArgList::AddAllArgs(ArgStringList &Output, OptSpecifier Id0) const {
142 for (auto *Arg : filtered(Ids: Id0)) {
143 Arg->claim();
144 Arg->render(Args: *this, Output);
145 }
146}
147
148void ArgList::AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
149 OptSpecifier Id1, OptSpecifier Id2) const {
150 for (auto *Arg : filtered(Ids: Id0, Ids: Id1, Ids: Id2)) {
151 Arg->claim();
152 const auto &Values = Arg->getValues();
153 Output.append(in_start: Values.begin(), in_end: Values.end());
154 }
155}
156
157void ArgList::AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
158 const char *Translation,
159 bool Joined) const {
160 for (auto *Arg : filtered(Ids: Id0)) {
161 Arg->claim();
162
163 if (Joined) {
164 Output.push_back(Elt: MakeArgString(Str: StringRef(Translation) +
165 Arg->getValue(N: 0)));
166 } else {
167 Output.push_back(Elt: Translation);
168 Output.push_back(Elt: Arg->getValue(N: 0));
169 }
170 }
171}
172
173void ArgList::ClaimAllArgs(OptSpecifier Id0) const {
174 for (auto *Arg : filtered(Ids: Id0))
175 Arg->claim();
176}
177
178void ArgList::ClaimAllArgs() const {
179 for (auto *Arg : *this)
180 if (!Arg->isClaimed())
181 Arg->claim();
182}
183
184const char *ArgList::GetOrMakeJoinedArgString(unsigned Index,
185 StringRef LHS,
186 StringRef RHS) const {
187 StringRef Cur = getArgString(Index);
188 if (Cur.size() == LHS.size() + RHS.size() && Cur.starts_with(Prefix: LHS) &&
189 Cur.ends_with(Suffix: RHS))
190 return Cur.data();
191
192 return MakeArgString(Str: LHS + RHS);
193}
194
195void ArgList::print(raw_ostream &O) const {
196 for (Arg *A : *this) {
197 O << "* ";
198 A->print(O);
199 }
200}
201
202#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
203LLVM_DUMP_METHOD void ArgList::dump() const { print(dbgs()); }
204#endif
205
206StringRef ArgList::getSubCommand(
207 ArrayRef<OptTable::SubCommand> AllSubCommands,
208 std::function<void(ArrayRef<StringRef>)> HandleMultipleSubcommands,
209 std::function<void(ArrayRef<StringRef>)> HandleOtherPositionals,
210 bool AllowSubCommandNamesAsPositionals) const {
211
212 SmallVector<StringRef, 4> SubCommands;
213 SmallVector<StringRef, 4> OtherPositionals;
214 for (const Arg *A : *this) {
215 if (A->getOption().getKind() != Option::InputClass)
216 continue;
217
218 StringRef CmdName = A->getValue();
219 bool IsCandidate =
220 !AllowSubCommandNamesAsPositionals || SubCommands.empty();
221 if (IsCandidate &&
222 llvm::any_of(Range&: AllSubCommands, P: [&](const OptTable::SubCommand &CMD) {
223 return CmdName == CMD.Name;
224 }))
225 SubCommands.push_back(Elt: CmdName);
226 else
227 OtherPositionals.push_back(Elt: CmdName);
228 }
229
230 // Invoke callbacks if necessary.
231 if (SubCommands.size() > 1) {
232 HandleMultipleSubcommands(SubCommands);
233 return {};
234 }
235 if (!OtherPositionals.empty())
236 HandleOtherPositionals(OtherPositionals);
237
238 if (SubCommands.size() == 1)
239 return SubCommands.front();
240 return {}; // No valid usage of subcommand found.
241}
242
243void InputArgList::releaseMemory() {
244 // An InputArgList always owns its arguments.
245 for (Arg *A : *this)
246 delete A;
247}
248
249InputArgList::InputArgList(const char* const *ArgBegin,
250 const char* const *ArgEnd)
251 : NumInputArgStrings(ArgEnd - ArgBegin) {
252 ArgStrings.append(in_start: ArgBegin, in_end: ArgEnd);
253}
254
255unsigned InputArgList::MakeIndex(StringRef String0) const {
256 unsigned Index = ArgStrings.size();
257
258 // Tuck away so we have a reliable const char *.
259 SynthesizedStrings.push_back(x: std::string(String0));
260 ArgStrings.push_back(Elt: SynthesizedStrings.back().c_str());
261
262 return Index;
263}
264
265unsigned InputArgList::MakeIndex(StringRef String0,
266 StringRef String1) const {
267 unsigned Index0 = MakeIndex(String0);
268 unsigned Index1 = MakeIndex(String0: String1);
269 assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!");
270 (void) Index1;
271 return Index0;
272}
273
274const char *InputArgList::MakeArgStringRef(StringRef Str) const {
275 return getArgString(Index: MakeIndex(String0: Str));
276}
277
278DerivedArgList::DerivedArgList(const InputArgList &BaseArgs)
279 : BaseArgs(BaseArgs) {}
280
281const char *DerivedArgList::MakeArgStringRef(StringRef Str) const {
282 return BaseArgs.MakeArgString(Str);
283}
284
285void DerivedArgList::AddSynthesizedArg(Arg *A) {
286 SynthesizedArgs.push_back(Elt: std::unique_ptr<Arg>(A));
287}
288
289Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option Opt) const {
290 SynthesizedArgs.push_back(
291 Elt: std::make_unique<Arg>(args: Opt, args: MakeArgString(Str: Opt.getPrefix() + Opt.getName()),
292 args: BaseArgs.MakeIndex(String0: Opt.getName()), args&: BaseArg));
293 return SynthesizedArgs.back().get();
294}
295
296Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option Opt,
297 StringRef Value) const {
298 unsigned Index = BaseArgs.MakeIndex(String0: Value);
299 SynthesizedArgs.push_back(
300 Elt: std::make_unique<Arg>(args: Opt, args: MakeArgString(Str: Opt.getPrefix() + Opt.getName()),
301 args&: Index, args: BaseArgs.getArgString(Index), args&: BaseArg));
302 return SynthesizedArgs.back().get();
303}
304
305Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option Opt,
306 StringRef Value) const {
307 unsigned Index = BaseArgs.MakeIndex(String0: Opt.getName(), String1: Value);
308 SynthesizedArgs.push_back(
309 Elt: std::make_unique<Arg>(args: Opt, args: MakeArgString(Str: Opt.getPrefix() + Opt.getName()),
310 args&: Index, args: BaseArgs.getArgString(Index: Index + 1), args&: BaseArg));
311 return SynthesizedArgs.back().get();
312}
313
314Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option Opt,
315 StringRef Value) const {
316 unsigned Index = BaseArgs.MakeIndex(String0: (Opt.getName() + Value).str());
317 SynthesizedArgs.push_back(Elt: std::make_unique<Arg>(
318 args: Opt, args: MakeArgString(Str: Opt.getPrefix() + Opt.getName()), args&: Index,
319 args: BaseArgs.getArgString(Index) + Opt.getName().size(), args&: BaseArg));
320 return SynthesizedArgs.back().get();
321}
322