arguments.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #pragma once
  2. #include <map>
  3. #include <set>
  4. #include <string>
  5. #include <vector>
  6. #include "program_args/any.h"
  7. namespace program {
  8. /**
  9. * @brief A string-literal object that requires input arguments to be two or
  10. * more characters
  11. */
  12. struct LongArg {
  13. template <size_t N> constexpr LongArg(char const (&str)[N]) : str(str) {
  14. static_assert(N > 1, "cannot create longargs with 0 or 1 character");
  15. }
  16. operator std::string const &() const { return str; }
  17. std::string str;
  18. };
  19. template <typename Impl> class Arguments {
  20. private:
  21. using option_id = std::string;
  22. struct Action;
  23. struct Argument;
  24. struct Flag;
  25. struct Option;
  26. template <typename, typename> struct WithDefault;
  27. public:
  28. Arguments() = default;
  29. Arguments(int argc, char const * const * const argv)
  30. : Arguments(argc, argv, (void const *)nullptr) {}
  31. std::vector<std::string> args() const {
  32. return {arguments.begin() + argument_names.size(), arguments.end()};
  33. }
  34. protected:
  35. template <typename T> Arguments(T const * parent) : parent_(parent) {}
  36. template <typename T>
  37. Arguments(int argc, char const * const * const argv, T const * parent);
  38. template <typename T> T const * parent() const { return parent_.get<T>(); }
  39. protected:
  40. /**
  41. * @brief Define an "action"/"subcommand"/"verb" to be executed. An example of
  42. * this pattern would be how git visualizes sub-commands in its interface,
  43. * even though in implementation it appears different.
  44. * @invariant Will fail to compile if bound to something that isn't a subtype
  45. * of Arguments
  46. * @param name A name of the action for usage messages
  47. * @param description An optional description object
  48. * @return A binding object that can implicitly cast to a subtype of Arguments
  49. *
  50. * @throws ArgumentMixingError if both argument() and action() have been
  51. * invoked in this
  52. */
  53. auto action(LongArg name, std::string const & description = "");
  54. /**
  55. * @brief Define an argument to be passed in to this program
  56. *
  57. * @param index The 0-based index of this argument in the program args array.
  58. * @param name A name of the argument for usage messages
  59. * @param description An optional description object
  60. * @return A binding object that will write its data in to an object of arity
  61. * 1
  62. *
  63. * @throws ArgumentMixingError if both argument() and action() have been
  64. * invoked in this
  65. * @throws ArgumentStructureError if this argument is required, but a prior
  66. * argument was optional
  67. * @throws IllegalPositionError if index is already in use in this
  68. * @throws IllegalPositionError if no argument is available at index
  69. */
  70. auto argument(size_t index, LongArg name,
  71. std::string const & description = "");
  72. /**
  73. * @brief Return all unbound arguments
  74. * @param name An optional name to describe these arguments
  75. * @param description An optional description object
  76. * @returns All unbound arguments in {@sa Arguments::arguments}
  77. * @throws ArgumentMixingError if both argument() and action() have been
  78. invoked in this
  79. * @throws ArgumentStructureError if rest is called with multiple names
  80. */
  81. std::vector<std::string> rest(LongArg name = "args",
  82. std::string const & description = "");
  83. /**
  84. * @brief Define a flag (option with an arity of zero).
  85. * If a flag binds to a boolean and has a name, then t will be invertable with
  86. * "--no-" prefix. If a flag binds to an integer, then it increments the value
  87. * with each repetition.
  88. * @invariant One or both of name and abbrev must be provided
  89. * @param name The name of the flag, to be parsed from the commandline with a
  90. * "--" prefix
  91. * @param abbrev A single-character version of a flag, to be parsed from the
  92. * commandline with a '-' prefix
  93. * @param description An optional description object
  94. */
  95. auto flag(LongArg name, char abbrev, std::string const & description = "");
  96. auto flag(LongArg name, std::string const & description = "");
  97. auto flag(char abbrev, std::string const & description = "");
  98. /**
  99. * @brief Define an option. If an option is repeated, then it can be used to
  100. * fill out multiple entries in a map or vector.
  101. * @invariant One or both of name and abbrev must be provided
  102. * @param name The name of the option, to be parsed from the commandline with
  103. * a "--" prefix
  104. * @param abbrev A single-character version of an option, to be parsed from
  105. * the commandline with a '-' prefix
  106. * @param description An optional description object
  107. */
  108. auto option(LongArg name, char abbrev, std::string const & description = "");
  109. auto option(LongArg name, std::string const & description = "");
  110. auto option(char abbrev, std::string const & description = "");
  111. private:
  112. void usage() const;
  113. void add_options(std::string const & name, char abbrev,
  114. std::string const & description,
  115. std::vector<std::string> aliases = {});
  116. bool has_actions() const { return !action_descriptions.empty(); }
  117. bool has_arguments() const {
  118. return !(rest_name.empty() && argument_names.empty());
  119. }
  120. option_id id(std::string const & arg) const;
  121. option_id id(char arg) const { return id({'-', arg}); }
  122. bool is_option(std::string const & arg) const;
  123. bool is_option(char arg) const { return is_option({'-', arg}); }
  124. bool is_flag(std::string const & arg) const;
  125. bool is_flag(char arg) const { return is_flag({'-', arg}); }
  126. private:
  127. // A helper for what limited introspection is required for handling actions in
  128. // test
  129. friend struct ArgumentTestHelper;
  130. template <typename> friend class Arguments;
  131. friend int main(int, char const * const *);
  132. operator bool() const { return primed_; }
  133. template <typename... Parents> int invoke(Parents const &... parents) const {
  134. return typed_main(parents..., static_cast<Impl const &>(*this));
  135. }
  136. template <typename T>
  137. std::shared_ptr<T> make_action(std::string const & name) const {
  138. if (action_name_ != name) { return nullptr; }
  139. auto ptr = make_action_(static_cast<Impl const &>(*this));
  140. return std::static_pointer_cast<T>(ptr);
  141. }
  142. private:
  143. using make_action_t = std::function<std::shared_ptr<void>(Impl const &)>;
  144. using action_hook_t =
  145. std::function<make_action_t(size_t, char const * const *)>;
  146. // Metadata variables
  147. bool primed_{false};
  148. detail::Any parent_;
  149. std::string rest_name;
  150. std::map<option_id, std::string> argument_descriptions;
  151. std::map<size_t, option_id> argument_names;
  152. std::map<option_id, std::string> option_descriptions;
  153. std::map<std::string, option_id> option_names;
  154. std::set<option_id> flag_names;
  155. std::map<std::string, action_hook_t> actions;
  156. std::string action_name_{""};
  157. make_action_t make_action_{nullptr};
  158. std::map<std::string, std::string> action_descriptions;
  159. // Data/Output variables
  160. std::string program;
  161. constexpr static size_t const no_optional_args{~0ul};
  162. size_t optional_from{no_optional_args};
  163. std::vector<std::string> arguments;
  164. std::map<std::string, std::vector<std::string>> options;
  165. std::map<std::string, int> flags;
  166. };
  167. template <typename Impl> struct Arguments<Impl>::Action {
  168. Arguments<Impl> * self;
  169. std::string name;
  170. std::string description;
  171. template <typename T> operator T() const;
  172. bool primed() const;
  173. explicit operator bool() const;
  174. };
  175. template <typename Impl> struct Arguments<Impl>::Argument {
  176. Arguments<Impl> * self;
  177. size_t index;
  178. bool is_optional;
  179. std::string name;
  180. std::string description;
  181. template <typename T> auto operator=(T && value);
  182. template <typename T> operator T() const;
  183. bool primed() const;
  184. explicit operator bool() const;
  185. };
  186. template <typename Impl> struct Arguments<Impl>::Flag {
  187. Arguments<Impl> * self;
  188. std::string name;
  189. char abbrev;
  190. std::string description;
  191. bool default_value;
  192. auto operator=(bool && value);
  193. operator bool() const;
  194. template <typename T> operator T() const;
  195. bool primed(bool inv) const;
  196. };
  197. template <typename Impl> struct Arguments<Impl>::Option {
  198. Arguments<Impl> * self;
  199. std::string name;
  200. char abbrev;
  201. std::string description;
  202. template <typename T> auto operator=(std::initializer_list<T> value);
  203. template <typename T> auto operator=(T && value);
  204. template <typename T> operator T() const;
  205. bool primed() const;
  206. explicit operator bool() const;
  207. };
  208. template <typename Impl>
  209. template <typename B, typename V>
  210. struct Arguments<Impl>::WithDefault {
  211. B impl;
  212. V default_value;
  213. template <typename T> operator T() const;
  214. };
  215. }
  216. #include "arguments_impl.hpp"
  217. template <typename Args, typename... Actions>
  218. int typed_main(Args const &, Actions const &...);
  219. #include <boost/preprocessor.hpp>
  220. #define TRY_INVOKE(r, data, elem) \
  221. if (self.elem) { return self.elem.invoke(parents..., self); }
  222. #define PROGRAM_ARGS_INVOKE(tname, ...) \
  223. template <> \
  224. template <typename... Parents> \
  225. int program::Arguments<tname>::invoke(Parents const &... parents) const { \
  226. tname const & self = static_cast<tname const &>(*this); \
  227. BOOST_PP_SEQ_FOR_EACH(TRY_INVOKE, _, \
  228. BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
  229. usage(); \
  230. return 1; \
  231. }
  232. #define PROGRAM_ARGS_MAIN(tname) \
  233. int main(int argc, char const * const * const argv) try { \
  234. return tname(argc, argv).invoke(); \
  235. } catch (program::ProgramArgumentsError const & pae) { \
  236. std::cerr << "Error in program argument handling: " << pae.what() << "\n"; \
  237. }
  238. #define TYPED_MAIN(tname) \
  239. PROGRAM_ARGS_MAIN(tname) \
  240. template <> int typed_main(tname const & args)
  241. #define PROGRAM_DEFER(...) [this]() { return __VA_ARGS__; }