1 //===--- ArgList.h - Argument List Management -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_OPTION_ARGLIST_H
11 #define LLVM_OPTION_ARGLIST_H
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/OptSpecifier.h"
20 #include "llvm/Option/Option.h"
31 /// arg_iterator - Iterates through arguments stored inside an ArgList.
32 template<typename BaseIter, unsigned NumOptSpecifiers = 0>
34 /// The current argument and the end of the sequence we're iterating.
35 BaseIter Current, End;
37 /// Optional filters on the arguments which will be match. To avoid a
38 /// zero-sized array, we store one specifier even if we're asked for none.
39 OptSpecifier Ids[NumOptSpecifiers ? NumOptSpecifiers : 1];
41 void SkipToNextArg() {
42 for (; Current != End; ++Current) {
43 // Skip erased elements.
47 // Done if there are no filters.
48 if (!NumOptSpecifiers)
51 // Otherwise require a match.
52 const Option &O = (*Current)->getOption();
62 typedef std::iterator_traits<BaseIter> Traits;
65 typedef typename Traits::value_type value_type;
66 typedef typename Traits::reference reference;
67 typedef typename Traits::pointer pointer;
68 typedef std::forward_iterator_tag iterator_category;
69 typedef std::ptrdiff_t difference_type;
72 BaseIter Current, BaseIter End,
73 const OptSpecifier (&Ids)[NumOptSpecifiers ? NumOptSpecifiers : 1] = {})
74 : Current(Current), End(End) {
75 for (unsigned I = 0; I != NumOptSpecifiers; ++I)
76 this->Ids[I] = Ids[I];
80 // FIXME: This conversion function makes no sense.
81 operator const Arg*() { return *Current; }
83 reference operator*() const { return *Current; }
84 pointer operator->() const { return Current; }
86 arg_iterator &operator++() {
92 arg_iterator operator++(int) {
93 arg_iterator tmp(*this);
98 friend bool operator==(arg_iterator LHS, arg_iterator RHS) {
99 return LHS.Current == RHS.Current;
101 friend bool operator!=(arg_iterator LHS, arg_iterator RHS) {
102 return !(LHS == RHS);
106 /// ArgList - Ordered collection of driver arguments.
108 /// The ArgList class manages a list of Arg instances as well as
109 /// auxiliary data and convenience methods to allow Tools to quickly
110 /// check for the presence of Arg instances for a particular Option
111 /// and to iterate over groups of arguments.
114 typedef SmallVector<Arg*, 16> arglist_type;
115 typedef arg_iterator<arglist_type::iterator> iterator;
116 typedef arg_iterator<arglist_type::const_iterator> const_iterator;
117 typedef arg_iterator<arglist_type::reverse_iterator> reverse_iterator;
118 typedef arg_iterator<arglist_type::const_reverse_iterator>
119 const_reverse_iterator;
121 template<unsigned N> using filtered_iterator =
122 arg_iterator<arglist_type::const_iterator, N>;
123 template<unsigned N> using filtered_reverse_iterator =
124 arg_iterator<arglist_type::const_reverse_iterator, N>;
127 /// The internal list of arguments.
130 typedef std::pair<unsigned, unsigned> OptRange;
131 static OptRange emptyRange() { return {-1u, 0u}; }
133 /// The first and last index of each different OptSpecifier ID.
134 DenseMap<unsigned, OptRange> OptRanges;
136 /// Get the range of indexes in which options with the specified IDs might
137 /// reside, or (0, 0) if there are no such options.
138 OptRange getRange(std::initializer_list<OptSpecifier> Ids) const;
141 // Make the default special members protected so they won't be used to slice
142 // derived objects, but can still be used by derived objects to implement
143 // their own special members.
145 // Explicit move operations to ensure the container is cleared post-move
146 // otherwise it could lead to a double-delete in the case of moving of an
147 // InputArgList which deletes the contents of the container. If we could fix
148 // up the ownership here (delegate storage/ownership to the derived class so
149 // it can be a container of unique_ptr) this would be simpler.
150 ArgList(ArgList &&RHS)
151 : Args(std::move(RHS.Args)), OptRanges(std::move(RHS.OptRanges)) {
153 RHS.OptRanges.clear();
155 ArgList &operator=(ArgList &&RHS) {
156 Args = std::move(RHS.Args);
158 OptRanges = std::move(RHS.OptRanges);
159 RHS.OptRanges.clear();
162 // Protect the dtor to ensure this type is never destroyed polymorphically.
163 ~ArgList() = default;
165 // Implicitly convert a value to an OptSpecifier. Used to work around a bug
166 // in MSVC's implementation of narrowing conversion checking.
167 static OptSpecifier toOptSpecifier(OptSpecifier S) { return S; }
173 /// append - Append \p A to the arg list.
176 const arglist_type &getArgs() const { return Args; }
178 unsigned size() const { return Args.size(); }
181 /// @name Arg Iteration
184 iterator begin() { return {Args.begin(), Args.end()}; }
185 iterator end() { return {Args.end(), Args.end()}; }
187 reverse_iterator rbegin() { return {Args.rbegin(), Args.rend()}; }
188 reverse_iterator rend() { return {Args.rend(), Args.rend()}; }
190 const_iterator begin() const { return {Args.begin(), Args.end()}; }
191 const_iterator end() const { return {Args.end(), Args.end()}; }
193 const_reverse_iterator rbegin() const { return {Args.rbegin(), Args.rend()}; }
194 const_reverse_iterator rend() const { return {Args.rend(), Args.rend()}; }
196 template<typename ...OptSpecifiers>
197 iterator_range<filtered_iterator<sizeof...(OptSpecifiers)>>
198 filtered(OptSpecifiers ...Ids) const {
199 OptRange Range = getRange({toOptSpecifier(Ids)...});
200 auto B = Args.begin() + Range.first;
201 auto E = Args.begin() + Range.second;
202 using Iterator = filtered_iterator<sizeof...(OptSpecifiers)>;
203 return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
204 Iterator(E, E, {toOptSpecifier(Ids)...}));
207 template<typename ...OptSpecifiers>
208 iterator_range<filtered_reverse_iterator<sizeof...(OptSpecifiers)>>
209 filtered_reverse(OptSpecifiers ...Ids) const {
210 OptRange Range = getRange({toOptSpecifier(Ids)...});
211 auto B = Args.rend() - Range.second;
212 auto E = Args.rend() - Range.first;
213 using Iterator = filtered_reverse_iterator<sizeof...(OptSpecifiers)>;
214 return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
215 Iterator(E, E, {toOptSpecifier(Ids)...}));
219 /// @name Arg Removal
222 /// eraseArg - Remove any option matching \p Id.
223 void eraseArg(OptSpecifier Id);
229 /// hasArg - Does the arg list contain any option matching \p Id.
231 /// \p Claim Whether the argument should be claimed, if it exists.
232 template<typename ...OptSpecifiers>
233 bool hasArgNoClaim(OptSpecifiers ...Ids) const {
234 return getLastArgNoClaim(Ids...) != nullptr;
236 template<typename ...OptSpecifiers>
237 bool hasArg(OptSpecifiers ...Ids) const {
238 return getLastArg(Ids...) != nullptr;
241 /// Return the last argument matching \p Id, or null.
242 template<typename ...OptSpecifiers>
243 Arg *getLastArg(OptSpecifiers ...Ids) const {
245 for (Arg *A : filtered(Ids...)) {
252 /// Return the last argument matching \p Id, or null. Do not "claim" the
253 /// option (don't mark it as having been used).
254 template<typename ...OptSpecifiers>
255 Arg *getLastArgNoClaim(OptSpecifiers ...Ids) const {
256 for (Arg *A : filtered_reverse(Ids...))
261 /// getArgString - Return the input argument string at \p Index.
262 virtual const char *getArgString(unsigned Index) const = 0;
264 /// getNumInputArgStrings - Return the number of original argument strings,
265 /// which are guaranteed to be the first strings in the argument string
267 virtual unsigned getNumInputArgStrings() const = 0;
270 /// @name Argument Lookup Utilities
273 /// getLastArgValue - Return the value of the last argument, or a default.
274 StringRef getLastArgValue(OptSpecifier Id, StringRef Default = "") const;
276 /// getAllArgValues - Get the values of all instances of the given argument
278 std::vector<std::string> getAllArgValues(OptSpecifier Id) const;
281 /// @name Translation Utilities
284 /// hasFlag - Given an option \p Pos and its negative form \p Neg, return
285 /// true if the option is present, false if the negation is present, and
286 /// \p Default if neither option is given. If both the option and its
287 /// negation are present, the last one wins.
288 bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default=true) const;
290 /// hasFlag - Given an option \p Pos, an alias \p PosAlias and its negative
291 /// form \p Neg, return true if the option or its alias is present, false if
292 /// the negation is present, and \p Default if none of the options are
293 /// given. If multiple options are present, the last one wins.
294 bool hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
295 bool Default = true) const;
297 /// AddLastArg - Render only the last argument match \p Id0, if present.
298 void AddLastArg(ArgStringList &Output, OptSpecifier Id0) const;
299 void AddLastArg(ArgStringList &Output, OptSpecifier Id0,
300 OptSpecifier Id1) const;
302 /// AddAllArgsExcept - Render all arguments matching any of the given ids
303 /// and not matching any of the excluded ids.
304 void AddAllArgsExcept(ArgStringList &Output, ArrayRef<OptSpecifier> Ids,
305 ArrayRef<OptSpecifier> ExcludeIds) const;
306 /// AddAllArgs - Render all arguments matching any of the given ids.
307 void AddAllArgs(ArgStringList &Output, ArrayRef<OptSpecifier> Ids) const;
309 /// AddAllArgs - Render all arguments matching the given ids.
310 void AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
311 OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
313 /// AddAllArgValues - Render the argument values of all arguments
314 /// matching the given ids.
315 void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
316 OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
318 /// AddAllArgsTranslated - Render all the arguments matching the
319 /// given ids, but forced to separate args and using the provided
320 /// name instead of the first option value.
322 /// \param Joined - If true, render the argument as joined with
323 /// the option specifier.
324 void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
325 const char *Translation,
326 bool Joined = false) const;
328 /// ClaimAllArgs - Claim all arguments which match the given
330 void ClaimAllArgs(OptSpecifier Id0) const;
332 /// ClaimAllArgs - Claim all arguments.
334 void ClaimAllArgs() const;
337 /// @name Arg Synthesis
340 /// Construct a constant string pointer whose
341 /// lifetime will match that of the ArgList.
342 virtual const char *MakeArgStringRef(StringRef Str) const = 0;
343 const char *MakeArgString(const Twine &Str) const {
344 SmallString<256> Buf;
345 return MakeArgStringRef(Str.toStringRef(Buf));
348 /// \brief Create an arg string for (\p LHS + \p RHS), reusing the
349 /// string at \p Index if possible.
350 const char *GetOrMakeJoinedArgString(unsigned Index, StringRef LHS,
351 StringRef RHS) const;
353 void print(raw_ostream &O) const;
359 class InputArgList final : public ArgList {
361 /// List of argument strings used by the contained Args.
363 /// This is mutable since we treat the ArgList as being the list
364 /// of Args, and allow routines to add new strings (to have a
365 /// convenient place to store the memory) via MakeIndex.
366 mutable ArgStringList ArgStrings;
368 /// Strings for synthesized arguments.
370 /// This is mutable since we treat the ArgList as being the list
371 /// of Args, and allow routines to add new strings (to have a
372 /// convenient place to store the memory) via MakeIndex.
373 mutable std::list<std::string> SynthesizedStrings;
375 /// The number of original input argument strings.
376 unsigned NumInputArgStrings;
378 /// Release allocated arguments.
379 void releaseMemory();
382 InputArgList(const char* const *ArgBegin, const char* const *ArgEnd);
383 InputArgList(InputArgList &&RHS)
384 : ArgList(std::move(RHS)), ArgStrings(std::move(RHS.ArgStrings)),
385 SynthesizedStrings(std::move(RHS.SynthesizedStrings)),
386 NumInputArgStrings(RHS.NumInputArgStrings) {}
387 InputArgList &operator=(InputArgList &&RHS) {
389 ArgList::operator=(std::move(RHS));
390 ArgStrings = std::move(RHS.ArgStrings);
391 SynthesizedStrings = std::move(RHS.SynthesizedStrings);
392 NumInputArgStrings = RHS.NumInputArgStrings;
395 ~InputArgList() { releaseMemory(); }
397 const char *getArgString(unsigned Index) const override {
398 return ArgStrings[Index];
401 unsigned getNumInputArgStrings() const override {
402 return NumInputArgStrings;
405 /// @name Arg Synthesis
409 /// MakeIndex - Get an index for the given string(s).
410 unsigned MakeIndex(StringRef String0) const;
411 unsigned MakeIndex(StringRef String0, StringRef String1) const;
413 using ArgList::MakeArgString;
414 const char *MakeArgStringRef(StringRef Str) const override;
419 /// DerivedArgList - An ordered collection of driver arguments,
420 /// whose storage may be in another argument list.
421 class DerivedArgList final : public ArgList {
422 const InputArgList &BaseArgs;
424 /// The list of arguments we synthesized.
425 mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs;
428 /// Construct a new derived arg list from \p BaseArgs.
429 DerivedArgList(const InputArgList &BaseArgs);
431 const char *getArgString(unsigned Index) const override {
432 return BaseArgs.getArgString(Index);
435 unsigned getNumInputArgStrings() const override {
436 return BaseArgs.getNumInputArgStrings();
439 const InputArgList &getBaseArgs() const {
443 /// @name Arg Synthesis
446 /// AddSynthesizedArg - Add a argument to the list of synthesized arguments
448 void AddSynthesizedArg(Arg *A);
450 using ArgList::MakeArgString;
451 const char *MakeArgStringRef(StringRef Str) const override;
453 /// AddFlagArg - Construct a new FlagArg for the given option \p Id and
454 /// append it to the argument list.
455 void AddFlagArg(const Arg *BaseArg, const Option Opt) {
456 append(MakeFlagArg(BaseArg, Opt));
459 /// AddPositionalArg - Construct a new Positional arg for the given option
460 /// \p Id, with the provided \p Value and append it to the argument
462 void AddPositionalArg(const Arg *BaseArg, const Option Opt,
464 append(MakePositionalArg(BaseArg, Opt, Value));
468 /// AddSeparateArg - Construct a new Positional arg for the given option
469 /// \p Id, with the provided \p Value and append it to the argument
471 void AddSeparateArg(const Arg *BaseArg, const Option Opt,
473 append(MakeSeparateArg(BaseArg, Opt, Value));
477 /// AddJoinedArg - Construct a new Positional arg for the given option
478 /// \p Id, with the provided \p Value and append it to the argument list.
479 void AddJoinedArg(const Arg *BaseArg, const Option Opt,
481 append(MakeJoinedArg(BaseArg, Opt, Value));
485 /// MakeFlagArg - Construct a new FlagArg for the given option \p Id.
486 Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const;
488 /// MakePositionalArg - Construct a new Positional arg for the
489 /// given option \p Id, with the provided \p Value.
490 Arg *MakePositionalArg(const Arg *BaseArg, const Option Opt,
491 StringRef Value) const;
493 /// MakeSeparateArg - Construct a new Positional arg for the
494 /// given option \p Id, with the provided \p Value.
495 Arg *MakeSeparateArg(const Arg *BaseArg, const Option Opt,
496 StringRef Value) const;
498 /// MakeJoinedArg - Construct a new Positional arg for the
499 /// given option \p Id, with the provided \p Value.
500 Arg *MakeJoinedArg(const Arg *BaseArg, const Option Opt,
501 StringRef Value) const;
506 } // end namespace opt
507 } // end namespace llvm