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