arguments.h 10 KB

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