ArgList.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ArgList.h - Argument List Management ---------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_OPTION_ARGLIST_H
  14. #define LLVM_OPTION_ARGLIST_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Option/Arg.h"
  23. #include "llvm/Option/OptSpecifier.h"
  24. #include "llvm/Option/Option.h"
  25. #include <algorithm>
  26. #include <cstddef>
  27. #include <initializer_list>
  28. #include <iterator>
  29. #include <list>
  30. #include <memory>
  31. #include <string>
  32. #include <utility>
  33. #include <vector>
  34. namespace llvm {
  35. class raw_ostream;
  36. namespace opt {
  37. /// arg_iterator - Iterates through arguments stored inside an ArgList.
  38. template<typename BaseIter, unsigned NumOptSpecifiers = 0>
  39. class arg_iterator {
  40. /// The current argument and the end of the sequence we're iterating.
  41. BaseIter Current, End;
  42. /// Optional filters on the arguments which will be match. To avoid a
  43. /// zero-sized array, we store one specifier even if we're asked for none.
  44. OptSpecifier Ids[NumOptSpecifiers ? NumOptSpecifiers : 1];
  45. void SkipToNextArg() {
  46. for (; Current != End; ++Current) {
  47. // Skip erased elements.
  48. if (!*Current)
  49. continue;
  50. // Done if there are no filters.
  51. if (!NumOptSpecifiers)
  52. return;
  53. // Otherwise require a match.
  54. const Option &O = (*Current)->getOption();
  55. for (auto Id : Ids) {
  56. if (!Id.isValid())
  57. break;
  58. if (O.matches(Id))
  59. return;
  60. }
  61. }
  62. }
  63. using Traits = std::iterator_traits<BaseIter>;
  64. public:
  65. using value_type = typename Traits::value_type;
  66. using reference = typename Traits::reference;
  67. using pointer = typename Traits::pointer;
  68. using iterator_category = std::forward_iterator_tag;
  69. using difference_type = std::ptrdiff_t;
  70. arg_iterator(
  71. BaseIter Current, BaseIter End,
  72. const OptSpecifier (&Ids)[NumOptSpecifiers ? NumOptSpecifiers : 1] = {})
  73. : Current(Current), End(End) {
  74. for (unsigned I = 0; I != NumOptSpecifiers; ++I)
  75. this->Ids[I] = Ids[I];
  76. SkipToNextArg();
  77. }
  78. reference operator*() const { return *Current; }
  79. pointer operator->() const { return Current; }
  80. arg_iterator &operator++() {
  81. ++Current;
  82. SkipToNextArg();
  83. return *this;
  84. }
  85. arg_iterator operator++(int) {
  86. arg_iterator tmp(*this);
  87. ++(*this);
  88. return tmp;
  89. }
  90. friend bool operator==(arg_iterator LHS, arg_iterator RHS) {
  91. return LHS.Current == RHS.Current;
  92. }
  93. friend bool operator!=(arg_iterator LHS, arg_iterator RHS) {
  94. return !(LHS == RHS);
  95. }
  96. };
  97. /// ArgList - Ordered collection of driver arguments.
  98. ///
  99. /// The ArgList class manages a list of Arg instances as well as
  100. /// auxiliary data and convenience methods to allow Tools to quickly
  101. /// check for the presence of Arg instances for a particular Option
  102. /// and to iterate over groups of arguments.
  103. class ArgList {
  104. public:
  105. using arglist_type = SmallVector<Arg *, 16>;
  106. using iterator = arg_iterator<arglist_type::iterator>;
  107. using const_iterator = arg_iterator<arglist_type::const_iterator>;
  108. using reverse_iterator = arg_iterator<arglist_type::reverse_iterator>;
  109. using const_reverse_iterator =
  110. arg_iterator<arglist_type::const_reverse_iterator>;
  111. template<unsigned N> using filtered_iterator =
  112. arg_iterator<arglist_type::const_iterator, N>;
  113. template<unsigned N> using filtered_reverse_iterator =
  114. arg_iterator<arglist_type::const_reverse_iterator, N>;
  115. private:
  116. /// The internal list of arguments.
  117. arglist_type Args;
  118. using OptRange = std::pair<unsigned, unsigned>;
  119. static OptRange emptyRange() { return {-1u, 0u}; }
  120. /// The first and last index of each different OptSpecifier ID.
  121. DenseMap<unsigned, OptRange> OptRanges;
  122. /// Get the range of indexes in which options with the specified IDs might
  123. /// reside, or (0, 0) if there are no such options.
  124. OptRange getRange(std::initializer_list<OptSpecifier> Ids) const;
  125. protected:
  126. // Make the default special members protected so they won't be used to slice
  127. // derived objects, but can still be used by derived objects to implement
  128. // their own special members.
  129. ArgList() = default;
  130. // Explicit move operations to ensure the container is cleared post-move
  131. // otherwise it could lead to a double-delete in the case of moving of an
  132. // InputArgList which deletes the contents of the container. If we could fix
  133. // up the ownership here (delegate storage/ownership to the derived class so
  134. // it can be a container of unique_ptr) this would be simpler.
  135. ArgList(ArgList &&RHS)
  136. : Args(std::move(RHS.Args)), OptRanges(std::move(RHS.OptRanges)) {
  137. RHS.Args.clear();
  138. RHS.OptRanges.clear();
  139. }
  140. ArgList &operator=(ArgList &&RHS) {
  141. Args = std::move(RHS.Args);
  142. RHS.Args.clear();
  143. OptRanges = std::move(RHS.OptRanges);
  144. RHS.OptRanges.clear();
  145. return *this;
  146. }
  147. // Protect the dtor to ensure this type is never destroyed polymorphically.
  148. ~ArgList() = default;
  149. // Implicitly convert a value to an OptSpecifier. Used to work around a bug
  150. // in MSVC's implementation of narrowing conversion checking.
  151. static OptSpecifier toOptSpecifier(OptSpecifier S) { return S; }
  152. public:
  153. /// @name Arg Access
  154. /// @{
  155. /// append - Append \p A to the arg list.
  156. void append(Arg *A);
  157. const arglist_type &getArgs() const { return Args; }
  158. unsigned size() const { return Args.size(); }
  159. /// @}
  160. /// @name Arg Iteration
  161. /// @{
  162. iterator begin() { return {Args.begin(), Args.end()}; }
  163. iterator end() { return {Args.end(), Args.end()}; }
  164. reverse_iterator rbegin() { return {Args.rbegin(), Args.rend()}; }
  165. reverse_iterator rend() { return {Args.rend(), Args.rend()}; }
  166. const_iterator begin() const { return {Args.begin(), Args.end()}; }
  167. const_iterator end() const { return {Args.end(), Args.end()}; }
  168. const_reverse_iterator rbegin() const { return {Args.rbegin(), Args.rend()}; }
  169. const_reverse_iterator rend() const { return {Args.rend(), Args.rend()}; }
  170. template<typename ...OptSpecifiers>
  171. iterator_range<filtered_iterator<sizeof...(OptSpecifiers)>>
  172. filtered(OptSpecifiers ...Ids) const {
  173. OptRange Range = getRange({toOptSpecifier(Ids)...});
  174. auto B = Args.begin() + Range.first;
  175. auto E = Args.begin() + Range.second;
  176. using Iterator = filtered_iterator<sizeof...(OptSpecifiers)>;
  177. return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
  178. Iterator(E, E, {toOptSpecifier(Ids)...}));
  179. }
  180. template<typename ...OptSpecifiers>
  181. iterator_range<filtered_reverse_iterator<sizeof...(OptSpecifiers)>>
  182. filtered_reverse(OptSpecifiers ...Ids) const {
  183. OptRange Range = getRange({toOptSpecifier(Ids)...});
  184. auto B = Args.rend() - Range.second;
  185. auto E = Args.rend() - Range.first;
  186. using Iterator = filtered_reverse_iterator<sizeof...(OptSpecifiers)>;
  187. return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
  188. Iterator(E, E, {toOptSpecifier(Ids)...}));
  189. }
  190. /// @}
  191. /// @name Arg Removal
  192. /// @{
  193. /// eraseArg - Remove any option matching \p Id.
  194. void eraseArg(OptSpecifier Id);
  195. /// @}
  196. /// @name Arg Access
  197. /// @{
  198. /// hasArg - Does the arg list contain any option matching \p Id.
  199. ///
  200. /// \p Claim Whether the argument should be claimed, if it exists.
  201. template<typename ...OptSpecifiers>
  202. bool hasArgNoClaim(OptSpecifiers ...Ids) const {
  203. return getLastArgNoClaim(Ids...) != nullptr;
  204. }
  205. template<typename ...OptSpecifiers>
  206. bool hasArg(OptSpecifiers ...Ids) const {
  207. return getLastArg(Ids...) != nullptr;
  208. }
  209. /// Return true if the arg list contains multiple arguments matching \p Id.
  210. bool hasMultipleArgs(OptSpecifier Id) const {
  211. auto Args = filtered(Id);
  212. return (Args.begin() != Args.end()) && (++Args.begin()) != Args.end();
  213. }
  214. /// Return the last argument matching \p Id, or null.
  215. template<typename ...OptSpecifiers>
  216. Arg *getLastArg(OptSpecifiers ...Ids) const {
  217. Arg *Res = nullptr;
  218. for (Arg *A : filtered(Ids...)) {
  219. Res = A;
  220. Res->claim();
  221. }
  222. return Res;
  223. }
  224. /// Return the last argument matching \p Id, or null. Do not "claim" the
  225. /// option (don't mark it as having been used).
  226. template<typename ...OptSpecifiers>
  227. Arg *getLastArgNoClaim(OptSpecifiers ...Ids) const {
  228. for (Arg *A : filtered_reverse(Ids...))
  229. return A;
  230. return nullptr;
  231. }
  232. /// getArgString - Return the input argument string at \p Index.
  233. virtual const char *getArgString(unsigned Index) const = 0;
  234. /// getNumInputArgStrings - Return the number of original argument strings,
  235. /// which are guaranteed to be the first strings in the argument string
  236. /// list.
  237. virtual unsigned getNumInputArgStrings() const = 0;
  238. /// @}
  239. /// @name Argument Lookup Utilities
  240. /// @{
  241. /// getLastArgValue - Return the value of the last argument, or a default.
  242. StringRef getLastArgValue(OptSpecifier Id, StringRef Default = "") const;
  243. /// getAllArgValues - Get the values of all instances of the given argument
  244. /// as strings.
  245. std::vector<std::string> getAllArgValues(OptSpecifier Id) const;
  246. /// @}
  247. /// @name Translation Utilities
  248. /// @{
  249. /// hasFlag - Given an option \p Pos and its negative form \p Neg, return
  250. /// true if the option is present, false if the negation is present, and
  251. /// \p Default if neither option is given. If both the option and its
  252. /// negation are present, the last one wins.
  253. bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default=true) const;
  254. /// hasFlag - Given an option \p Pos, an alias \p PosAlias and its negative
  255. /// form \p Neg, return true if the option or its alias is present, false if
  256. /// the negation is present, and \p Default if none of the options are
  257. /// given. If multiple options are present, the last one wins.
  258. bool hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
  259. bool Default = true) const;
  260. /// Render only the last argument match \p Id0, if present.
  261. template<typename ...OptSpecifiers>
  262. void AddLastArg(ArgStringList &Output, OptSpecifiers ...Ids) const {
  263. if (Arg *A = getLastArg(Ids...)) // Calls claim() on all Ids's Args.
  264. A->render(*this, Output);
  265. }
  266. /// AddAllArgsExcept - Render all arguments matching any of the given ids
  267. /// and not matching any of the excluded ids.
  268. void AddAllArgsExcept(ArgStringList &Output, ArrayRef<OptSpecifier> Ids,
  269. ArrayRef<OptSpecifier> ExcludeIds) const;
  270. /// AddAllArgs - Render all arguments matching any of the given ids.
  271. void AddAllArgs(ArgStringList &Output, ArrayRef<OptSpecifier> Ids) const;
  272. /// AddAllArgs - Render all arguments matching the given ids.
  273. void AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
  274. OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
  275. /// AddAllArgValues - Render the argument values of all arguments
  276. /// matching the given ids.
  277. void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
  278. OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
  279. /// AddAllArgsTranslated - Render all the arguments matching the
  280. /// given ids, but forced to separate args and using the provided
  281. /// name instead of the first option value.
  282. ///
  283. /// \param Joined - If true, render the argument as joined with
  284. /// the option specifier.
  285. void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
  286. const char *Translation,
  287. bool Joined = false) const;
  288. /// ClaimAllArgs - Claim all arguments which match the given
  289. /// option id.
  290. void ClaimAllArgs(OptSpecifier Id0) const;
  291. /// ClaimAllArgs - Claim all arguments.
  292. ///
  293. void ClaimAllArgs() const;
  294. /// @}
  295. /// @name Arg Synthesis
  296. /// @{
  297. /// Construct a constant string pointer whose
  298. /// lifetime will match that of the ArgList.
  299. virtual const char *MakeArgStringRef(StringRef Str) const = 0;
  300. const char *MakeArgString(const Twine &Str) const {
  301. SmallString<256> Buf;
  302. return MakeArgStringRef(Str.toStringRef(Buf));
  303. }
  304. /// Create an arg string for (\p LHS + \p RHS), reusing the
  305. /// string at \p Index if possible.
  306. const char *GetOrMakeJoinedArgString(unsigned Index, StringRef LHS,
  307. StringRef RHS) const;
  308. void print(raw_ostream &O) const;
  309. void dump() const;
  310. /// @}
  311. };
  312. class InputArgList final : public ArgList {
  313. private:
  314. /// List of argument strings used by the contained Args.
  315. ///
  316. /// This is mutable since we treat the ArgList as being the list
  317. /// of Args, and allow routines to add new strings (to have a
  318. /// convenient place to store the memory) via MakeIndex.
  319. mutable ArgStringList ArgStrings;
  320. /// Strings for synthesized arguments.
  321. ///
  322. /// This is mutable since we treat the ArgList as being the list
  323. /// of Args, and allow routines to add new strings (to have a
  324. /// convenient place to store the memory) via MakeIndex.
  325. mutable std::list<std::string> SynthesizedStrings;
  326. /// The number of original input argument strings.
  327. unsigned NumInputArgStrings;
  328. /// Release allocated arguments.
  329. void releaseMemory();
  330. public:
  331. InputArgList() : NumInputArgStrings(0) {}
  332. InputArgList(const char* const *ArgBegin, const char* const *ArgEnd);
  333. InputArgList(InputArgList &&RHS)
  334. : ArgList(std::move(RHS)), ArgStrings(std::move(RHS.ArgStrings)),
  335. SynthesizedStrings(std::move(RHS.SynthesizedStrings)),
  336. NumInputArgStrings(RHS.NumInputArgStrings) {}
  337. InputArgList &operator=(InputArgList &&RHS) {
  338. releaseMemory();
  339. ArgList::operator=(std::move(RHS));
  340. ArgStrings = std::move(RHS.ArgStrings);
  341. SynthesizedStrings = std::move(RHS.SynthesizedStrings);
  342. NumInputArgStrings = RHS.NumInputArgStrings;
  343. return *this;
  344. }
  345. ~InputArgList() { releaseMemory(); }
  346. const char *getArgString(unsigned Index) const override {
  347. return ArgStrings[Index];
  348. }
  349. void replaceArgString(unsigned Index, const Twine &S) {
  350. ArgStrings[Index] = MakeArgString(S);
  351. }
  352. unsigned getNumInputArgStrings() const override {
  353. return NumInputArgStrings;
  354. }
  355. /// @name Arg Synthesis
  356. /// @{
  357. public:
  358. /// MakeIndex - Get an index for the given string(s).
  359. unsigned MakeIndex(StringRef String0) const;
  360. unsigned MakeIndex(StringRef String0, StringRef String1) const;
  361. using ArgList::MakeArgString;
  362. const char *MakeArgStringRef(StringRef Str) const override;
  363. /// @}
  364. };
  365. /// DerivedArgList - An ordered collection of driver arguments,
  366. /// whose storage may be in another argument list.
  367. class DerivedArgList final : public ArgList {
  368. const InputArgList &BaseArgs;
  369. /// The list of arguments we synthesized.
  370. mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs;
  371. public:
  372. /// Construct a new derived arg list from \p BaseArgs.
  373. DerivedArgList(const InputArgList &BaseArgs);
  374. const char *getArgString(unsigned Index) const override {
  375. return BaseArgs.getArgString(Index);
  376. }
  377. unsigned getNumInputArgStrings() const override {
  378. return BaseArgs.getNumInputArgStrings();
  379. }
  380. const InputArgList &getBaseArgs() const {
  381. return BaseArgs;
  382. }
  383. /// @name Arg Synthesis
  384. /// @{
  385. /// AddSynthesizedArg - Add a argument to the list of synthesized arguments
  386. /// (to be freed).
  387. void AddSynthesizedArg(Arg *A);
  388. using ArgList::MakeArgString;
  389. const char *MakeArgStringRef(StringRef Str) const override;
  390. /// AddFlagArg - Construct a new FlagArg for the given option \p Id and
  391. /// append it to the argument list.
  392. void AddFlagArg(const Arg *BaseArg, const Option Opt) {
  393. append(MakeFlagArg(BaseArg, Opt));
  394. }
  395. /// AddPositionalArg - Construct a new Positional arg for the given option
  396. /// \p Id, with the provided \p Value and append it to the argument
  397. /// list.
  398. void AddPositionalArg(const Arg *BaseArg, const Option Opt,
  399. StringRef Value) {
  400. append(MakePositionalArg(BaseArg, Opt, Value));
  401. }
  402. /// AddSeparateArg - Construct a new Positional arg for the given option
  403. /// \p Id, with the provided \p Value and append it to the argument
  404. /// list.
  405. void AddSeparateArg(const Arg *BaseArg, const Option Opt,
  406. StringRef Value) {
  407. append(MakeSeparateArg(BaseArg, Opt, Value));
  408. }
  409. /// AddJoinedArg - Construct a new Positional arg for the given option
  410. /// \p Id, with the provided \p Value and append it to the argument list.
  411. void AddJoinedArg(const Arg *BaseArg, const Option Opt,
  412. StringRef Value) {
  413. append(MakeJoinedArg(BaseArg, Opt, Value));
  414. }
  415. /// MakeFlagArg - Construct a new FlagArg for the given option \p Id.
  416. Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const;
  417. /// MakePositionalArg - Construct a new Positional arg for the
  418. /// given option \p Id, with the provided \p Value.
  419. Arg *MakePositionalArg(const Arg *BaseArg, const Option Opt,
  420. StringRef Value) const;
  421. /// MakeSeparateArg - Construct a new Positional arg for the
  422. /// given option \p Id, with the provided \p Value.
  423. Arg *MakeSeparateArg(const Arg *BaseArg, const Option Opt,
  424. StringRef Value) const;
  425. /// MakeJoinedArg - Construct a new Positional arg for the
  426. /// given option \p Id, with the provided \p Value.
  427. Arg *MakeJoinedArg(const Arg *BaseArg, const Option Opt,
  428. StringRef Value) const;
  429. /// @}
  430. };
  431. } // end namespace opt
  432. } // end namespace llvm
  433. #endif // LLVM_OPTION_ARGLIST_H
  434. #ifdef __GNUC__
  435. #pragma GCC diagnostic pop
  436. #endif