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/ADT/ArrayRef.h"
10 #include "llvm/ADT/SmallVector.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Config/llvm-config.h"
15 #include "llvm/Option/Arg.h"
16 #include "llvm/Option/ArgList.h"
17 #include "llvm/Option/Option.h"
18 #include "llvm/Option/OptSpecifier.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <memory>
25 #include <string>
26 #include <utility>
27 #include <vector>
28 
29 using namespace llvm;
30 using namespace llvm::opt;
31 
append(Arg * A)32 void ArgList::append(Arg *A) {
33   Args.push_back(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(std::make_pair(O.getID(), emptyRange())).first->second;
40     R.first = std::min<unsigned>(R.first, Args.size() - 1);
41     R.second = Args.size();
42   }
43 }
44 
eraseArg(OptSpecifier Id)45 void 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(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(Id.getID());
54 }
55 
56 ArgList::OptRange
getRange(std::initializer_list<OptSpecifier> Ids) const57 ArgList::getRange(std::initializer_list<OptSpecifier> Ids) const {
58   OptRange R = emptyRange();
59   for (auto Id : Ids) {
60     auto I = OptRanges.find(Id.getID());
61     if (I != OptRanges.end()) {
62       R.first = std::min(R.first, I->second.first);
63       R.second = std::max(R.second, 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 
hasFlag(OptSpecifier Pos,OptSpecifier Neg,bool Default) const72 bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const {
73   if (Arg *A = getLastArg(Pos, Neg))
74     return A->getOption().matches(Pos);
75   return Default;
76 }
77 
hasFlagNoClaim(OptSpecifier Pos,OptSpecifier Neg,bool Default) const78 bool ArgList::hasFlagNoClaim(OptSpecifier Pos, OptSpecifier Neg,
79                              bool Default) const {
80   if (Arg *A = getLastArgNoClaim(Pos, Neg))
81     return A->getOption().matches(Pos);
82   return Default;
83 }
84 
hasFlag(OptSpecifier Pos,OptSpecifier PosAlias,OptSpecifier Neg,bool Default) const85 bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
86                       bool Default) const {
87   if (Arg *A = getLastArg(Pos, PosAlias, Neg))
88     return A->getOption().matches(Pos) || A->getOption().matches(PosAlias);
89   return Default;
90 }
91 
getLastArgValue(OptSpecifier Id,StringRef Default) const92 StringRef ArgList::getLastArgValue(OptSpecifier Id, StringRef Default) const {
93   if (Arg *A = getLastArg(Id))
94     return A->getValue();
95   return Default;
96 }
97 
getAllArgValues(OptSpecifier Id) const98 std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const {
99   SmallVector<const char *, 16> Values;
100   AddAllArgValues(Values, Id);
101   return std::vector<std::string>(Values.begin(), Values.end());
102 }
103 
addOptInFlag(ArgStringList & Output,OptSpecifier Pos,OptSpecifier Neg) const104 void ArgList::addOptInFlag(ArgStringList &Output, OptSpecifier Pos,
105                            OptSpecifier Neg) const {
106   if (Arg *A = getLastArg(Pos, Neg))
107     if (A->getOption().matches(Pos))
108       A->render(*this, Output);
109 }
110 
AddAllArgsExcept(ArgStringList & Output,ArrayRef<OptSpecifier> Ids,ArrayRef<OptSpecifier> ExcludeIds) const111 void 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)) {
118         Excluded = true;
119         break;
120       }
121     }
122     if (!Excluded) {
123       for (OptSpecifier Id : Ids) {
124         if (Arg->getOption().matches(Id)) {
125           Arg->claim();
126           Arg->render(*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.
addAllArgs(ArgStringList & Output,ArrayRef<OptSpecifier> Ids) const135 void ArgList::addAllArgs(ArgStringList &Output,
136                          ArrayRef<OptSpecifier> Ids) const {
137   ArrayRef<OptSpecifier> Exclude = std::nullopt;
138   AddAllArgsExcept(Output, Ids, Exclude);
139 }
140 
AddAllArgs(ArgStringList & Output,OptSpecifier Id0) const141 void ArgList::AddAllArgs(ArgStringList &Output, OptSpecifier Id0) const {
142   for (auto *Arg : filtered(Id0)) {
143     Arg->claim();
144     Arg->render(*this, Output);
145   }
146 }
147 
AddAllArgValues(ArgStringList & Output,OptSpecifier Id0,OptSpecifier Id1,OptSpecifier Id2) const148 void ArgList::AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
149                               OptSpecifier Id1, OptSpecifier Id2) const {
150   for (auto *Arg : filtered(Id0, Id1, Id2)) {
151     Arg->claim();
152     const auto &Values = Arg->getValues();
153     Output.append(Values.begin(), Values.end());
154   }
155 }
156 
AddAllArgsTranslated(ArgStringList & Output,OptSpecifier Id0,const char * Translation,bool Joined) const157 void ArgList::AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
158                                    const char *Translation,
159                                    bool Joined) const {
160   for (auto *Arg : filtered(Id0)) {
161     Arg->claim();
162 
163     if (Joined) {
164       Output.push_back(MakeArgString(StringRef(Translation) +
165                                      Arg->getValue(0)));
166     } else {
167       Output.push_back(Translation);
168       Output.push_back(Arg->getValue(0));
169     }
170   }
171 }
172 
ClaimAllArgs(OptSpecifier Id0) const173 void ArgList::ClaimAllArgs(OptSpecifier Id0) const {
174   for (auto *Arg : filtered(Id0))
175     Arg->claim();
176 }
177 
ClaimAllArgs() const178 void ArgList::ClaimAllArgs() const {
179   for (auto *Arg : *this)
180     if (!Arg->isClaimed())
181       Arg->claim();
182 }
183 
GetOrMakeJoinedArgString(unsigned Index,StringRef LHS,StringRef RHS) const184 const 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(LHS) &&
189       Cur.ends_with(RHS))
190     return Cur.data();
191 
192   return MakeArgString(LHS + RHS);
193 }
194 
print(raw_ostream & O) const195 void 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)
dump() const203 LLVM_DUMP_METHOD void ArgList::dump() const { print(dbgs()); }
204 #endif
205 
releaseMemory()206 void InputArgList::releaseMemory() {
207   // An InputArgList always owns its arguments.
208   for (Arg *A : *this)
209     delete A;
210 }
211 
InputArgList(const char * const * ArgBegin,const char * const * ArgEnd)212 InputArgList::InputArgList(const char* const *ArgBegin,
213                            const char* const *ArgEnd)
214   : NumInputArgStrings(ArgEnd - ArgBegin) {
215   ArgStrings.append(ArgBegin, ArgEnd);
216 }
217 
MakeIndex(StringRef String0) const218 unsigned InputArgList::MakeIndex(StringRef String0) const {
219   unsigned Index = ArgStrings.size();
220 
221   // Tuck away so we have a reliable const char *.
222   SynthesizedStrings.push_back(std::string(String0));
223   ArgStrings.push_back(SynthesizedStrings.back().c_str());
224 
225   return Index;
226 }
227 
MakeIndex(StringRef String0,StringRef String1) const228 unsigned InputArgList::MakeIndex(StringRef String0,
229                                  StringRef String1) const {
230   unsigned Index0 = MakeIndex(String0);
231   unsigned Index1 = MakeIndex(String1);
232   assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!");
233   (void) Index1;
234   return Index0;
235 }
236 
MakeArgStringRef(StringRef Str) const237 const char *InputArgList::MakeArgStringRef(StringRef Str) const {
238   return getArgString(MakeIndex(Str));
239 }
240 
DerivedArgList(const InputArgList & BaseArgs)241 DerivedArgList::DerivedArgList(const InputArgList &BaseArgs)
242     : BaseArgs(BaseArgs) {}
243 
MakeArgStringRef(StringRef Str) const244 const char *DerivedArgList::MakeArgStringRef(StringRef Str) const {
245   return BaseArgs.MakeArgString(Str);
246 }
247 
AddSynthesizedArg(Arg * A)248 void DerivedArgList::AddSynthesizedArg(Arg *A) {
249   SynthesizedArgs.push_back(std::unique_ptr<Arg>(A));
250 }
251 
MakeFlagArg(const Arg * BaseArg,const Option Opt) const252 Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option Opt) const {
253   SynthesizedArgs.push_back(
254       std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
255                        BaseArgs.MakeIndex(Opt.getName()), BaseArg));
256   return SynthesizedArgs.back().get();
257 }
258 
MakePositionalArg(const Arg * BaseArg,const Option Opt,StringRef Value) const259 Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option Opt,
260                                        StringRef Value) const {
261   unsigned Index = BaseArgs.MakeIndex(Value);
262   SynthesizedArgs.push_back(
263       std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
264                        Index, BaseArgs.getArgString(Index), BaseArg));
265   return SynthesizedArgs.back().get();
266 }
267 
MakeSeparateArg(const Arg * BaseArg,const Option Opt,StringRef Value) const268 Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option Opt,
269                                      StringRef Value) const {
270   unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
271   SynthesizedArgs.push_back(
272       std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
273                        Index, BaseArgs.getArgString(Index + 1), BaseArg));
274   return SynthesizedArgs.back().get();
275 }
276 
MakeJoinedArg(const Arg * BaseArg,const Option Opt,StringRef Value) const277 Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option Opt,
278                                    StringRef Value) const {
279   unsigned Index = BaseArgs.MakeIndex((Opt.getName() + Value).str());
280   SynthesizedArgs.push_back(std::make_unique<Arg>(
281       Opt, MakeArgString(Opt.getPrefix() + Opt.getName()), Index,
282       BaseArgs.getArgString(Index) + Opt.getName().size(), BaseArg));
283   return SynthesizedArgs.back().get();
284 }
285