arguments.h 8.4 KB

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