]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Option/ArgList.h
Merge ^/head r319779 through r319800.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Option / ArgList.h
1 //===--- ArgList.h - Argument List Management -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_OPTION_ARGLIST_H
11 #define LLVM_OPTION_ARGLIST_H
12
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"
21 #include <list>
22 #include <memory>
23 #include <string>
24 #include <vector>
25
26 namespace llvm {
27 namespace opt {
28 class ArgList;
29 class Option;
30
31 /// arg_iterator - Iterates through arguments stored inside an ArgList.
32 template<typename BaseIter, unsigned NumOptSpecifiers = 0>
33 class arg_iterator {
34   /// The current argument and the end of the sequence we're iterating.
35   BaseIter Current, End;
36
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];
40
41   void SkipToNextArg() {
42     for (; Current != End; ++Current) {
43       // Skip erased elements.
44       if (!*Current)
45         continue;
46
47       // Done if there are no filters.
48       if (!NumOptSpecifiers)
49         return;
50
51       // Otherwise require a match.
52       const Option &O = (*Current)->getOption();
53       for (auto Id : Ids) {
54         if (!Id.isValid())
55           break;
56         if (O.matches(Id))
57           return;
58       }
59     }
60   }
61
62   typedef std::iterator_traits<BaseIter> Traits;
63
64 public:
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;
70
71   arg_iterator(
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];
77     SkipToNextArg();
78   }
79
80   // FIXME: This conversion function makes no sense.
81   operator const Arg*() { return *Current; }
82
83   reference operator*() const { return *Current; }
84   pointer operator->() const { return Current; }
85
86   arg_iterator &operator++() {
87     ++Current;
88     SkipToNextArg();
89     return *this;
90   }
91
92   arg_iterator operator++(int) {
93     arg_iterator tmp(*this);
94     ++(*this);
95     return tmp;
96   }
97
98   friend bool operator==(arg_iterator LHS, arg_iterator RHS) {
99     return LHS.Current == RHS.Current;
100   }
101   friend bool operator!=(arg_iterator LHS, arg_iterator RHS) {
102     return !(LHS == RHS);
103   }
104 };
105
106 /// ArgList - Ordered collection of driver arguments.
107 ///
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.
112 class ArgList {
113 public:
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;
120
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>;
125
126 private:
127   /// The internal list of arguments.
128   arglist_type Args;
129
130   typedef std::pair<unsigned, unsigned> OptRange;
131   static OptRange emptyRange() { return {-1u, 0u}; }
132
133   /// The first and last index of each different OptSpecifier ID.
134   DenseMap<unsigned, OptRange> OptRanges;
135
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;
139
140 protected:
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.
144   ArgList() = default;
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)) {
152     RHS.Args.clear();
153     RHS.OptRanges.clear();
154   }
155   ArgList &operator=(ArgList &&RHS) {
156     Args = std::move(RHS.Args);
157     RHS.Args.clear();
158     OptRanges = std::move(RHS.OptRanges);
159     RHS.OptRanges.clear();
160     return *this;
161   }
162   // Protect the dtor to ensure this type is never destroyed polymorphically.
163   ~ArgList() = default;
164
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; }
168
169 public:
170   /// @name Arg Access
171   /// @{
172
173   /// append - Append \p A to the arg list.
174   void append(Arg *A);
175
176   const arglist_type &getArgs() const { return Args; }
177
178   unsigned size() const { return Args.size(); }
179
180   /// @}
181   /// @name Arg Iteration
182   /// @{
183
184   iterator begin() { return {Args.begin(), Args.end()}; }
185   iterator end() { return {Args.end(), Args.end()}; }
186
187   reverse_iterator rbegin() { return {Args.rbegin(), Args.rend()}; }
188   reverse_iterator rend() { return {Args.rend(), Args.rend()}; }
189
190   const_iterator begin() const { return {Args.begin(), Args.end()}; }
191   const_iterator end() const { return {Args.end(), Args.end()}; }
192
193   const_reverse_iterator rbegin() const { return {Args.rbegin(), Args.rend()}; }
194   const_reverse_iterator rend() const { return {Args.rend(), Args.rend()}; }
195
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)...}));
205   }
206
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)...}));
216   }
217
218   /// @}
219   /// @name Arg Removal
220   /// @{
221
222   /// eraseArg - Remove any option matching \p Id.
223   void eraseArg(OptSpecifier Id);
224
225   /// @}
226   /// @name Arg Access
227   /// @{
228
229   /// hasArg - Does the arg list contain any option matching \p Id.
230   ///
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;
235   }
236   template<typename ...OptSpecifiers>
237   bool hasArg(OptSpecifiers ...Ids) const {
238     return getLastArg(Ids...) != nullptr;
239   }
240
241   /// Return the last argument matching \p Id, or null.
242   template<typename ...OptSpecifiers>
243   Arg *getLastArg(OptSpecifiers ...Ids) const {
244     Arg *Res = nullptr;
245     for (Arg *A : filtered(Ids...)) {
246       Res = A;
247       Res->claim();
248     }
249     return Res;
250   }
251
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...))
257       return A;
258     return nullptr;
259   }
260
261   /// getArgString - Return the input argument string at \p Index.
262   virtual const char *getArgString(unsigned Index) const = 0;
263
264   /// getNumInputArgStrings - Return the number of original argument strings,
265   /// which are guaranteed to be the first strings in the argument string
266   /// list.
267   virtual unsigned getNumInputArgStrings() const = 0;
268
269   /// @}
270   /// @name Argument Lookup Utilities
271   /// @{
272
273   /// getLastArgValue - Return the value of the last argument, or a default.
274   StringRef getLastArgValue(OptSpecifier Id, StringRef Default = "") const;
275
276   /// getAllArgValues - Get the values of all instances of the given argument
277   /// as strings.
278   std::vector<std::string> getAllArgValues(OptSpecifier Id) const;
279
280   /// @}
281   /// @name Translation Utilities
282   /// @{
283
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;
289
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;
296
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;
301
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;
308
309   /// AddAllArgs - Render all arguments matching the given ids.
310   void AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
311                   OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
312
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;
317
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.
321   ///
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;
327
328   /// ClaimAllArgs - Claim all arguments which match the given
329   /// option id.
330   void ClaimAllArgs(OptSpecifier Id0) const;
331
332   /// ClaimAllArgs - Claim all arguments.
333   ///
334   void ClaimAllArgs() const;
335
336   /// @}
337   /// @name Arg Synthesis
338   /// @{
339
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));
346   }
347
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;
352
353   void print(raw_ostream &O) const;
354   void dump() const;
355
356   /// @}
357 };
358
359 class InputArgList final : public ArgList {
360 private:
361   /// List of argument strings used by the contained Args.
362   ///
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;
367
368   /// Strings for synthesized arguments.
369   ///
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;
374
375   /// The number of original input argument strings.
376   unsigned NumInputArgStrings;
377
378   /// Release allocated arguments.
379   void releaseMemory();
380
381 public:
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) {
388     releaseMemory();
389     ArgList::operator=(std::move(RHS));
390     ArgStrings = std::move(RHS.ArgStrings);
391     SynthesizedStrings = std::move(RHS.SynthesizedStrings);
392     NumInputArgStrings = RHS.NumInputArgStrings;
393     return *this;
394   }
395   ~InputArgList() { releaseMemory(); }
396
397   const char *getArgString(unsigned Index) const override {
398     return ArgStrings[Index];
399   }
400
401   unsigned getNumInputArgStrings() const override {
402     return NumInputArgStrings;
403   }
404
405   /// @name Arg Synthesis
406   /// @{
407
408 public:
409   /// MakeIndex - Get an index for the given string(s).
410   unsigned MakeIndex(StringRef String0) const;
411   unsigned MakeIndex(StringRef String0, StringRef String1) const;
412
413   using ArgList::MakeArgString;
414   const char *MakeArgStringRef(StringRef Str) const override;
415
416   /// @}
417 };
418
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;
423
424   /// The list of arguments we synthesized.
425   mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs;
426
427 public:
428   /// Construct a new derived arg list from \p BaseArgs.
429   DerivedArgList(const InputArgList &BaseArgs);
430
431   const char *getArgString(unsigned Index) const override {
432     return BaseArgs.getArgString(Index);
433   }
434
435   unsigned getNumInputArgStrings() const override {
436     return BaseArgs.getNumInputArgStrings();
437   }
438
439   const InputArgList &getBaseArgs() const {
440     return BaseArgs;
441   }
442
443   /// @name Arg Synthesis
444   /// @{
445
446   /// AddSynthesizedArg - Add a argument to the list of synthesized arguments
447   /// (to be freed).
448   void AddSynthesizedArg(Arg *A);
449
450   using ArgList::MakeArgString;
451   const char *MakeArgStringRef(StringRef Str) const override;
452
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));
457   }
458
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
461   /// list.
462   void AddPositionalArg(const Arg *BaseArg, const Option Opt,
463                         StringRef Value) {
464     append(MakePositionalArg(BaseArg, Opt, Value));
465   }
466
467
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
470   /// list.
471   void AddSeparateArg(const Arg *BaseArg, const Option Opt,
472                       StringRef Value) {
473     append(MakeSeparateArg(BaseArg, Opt, Value));
474   }
475
476
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,
480                     StringRef Value) {
481     append(MakeJoinedArg(BaseArg, Opt, Value));
482   }
483
484
485   /// MakeFlagArg - Construct a new FlagArg for the given option \p Id.
486   Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const;
487
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;
492
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;
497
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;
502
503   /// @}
504 };
505
506 } // end namespace opt
507 } // end namespace llvm
508
509 #endif