arguments_impl.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #pragma once
  2. #include <iostream>
  3. #include <utility>
  4. #include "arguments.h"
  5. #include "exception.h"
  6. #include "utilities.h"
  7. #ifndef PROGRAM_ARGS_NOEXIT_ON_HELP
  8. #define PROGRAM_ARGS_EXIT(X) std::exit(X)
  9. #else
  10. #define PROGRAM_ARGS_EXIT(X) (void)X
  11. #endif
  12. namespace program {
  13. template <typename Impl>
  14. template <typename T>
  15. Arguments<Impl>::Action::operator T() const {
  16. static_assert(std::is_base_of_v<Arguments<T>, T>,
  17. "Action can only bind to Arguments");
  18. if (!primed()) {
  19. self->actions.emplace(name, [](int argc, char const * const * argv) {
  20. return [=](Impl const & args) {
  21. return std::make_shared<T>(T(argc, argv, &args));
  22. };
  23. });
  24. } else if (auto ptr = self->make_action<T>(name)) {
  25. return *ptr;
  26. }
  27. return T();
  28. }
  29. template <typename Impl> Arguments<Impl>::Action::operator bool() const {
  30. return primed() && self->arguments.size() > 0;
  31. }
  32. template <typename Impl> bool Arguments<Impl>::Action::primed() const {
  33. if (self->primed_) { return true; }
  34. if (self->has_arguments()) { throw ArgumentMixingError(); }
  35. self->action_descriptions.emplace(name, description);
  36. return false;
  37. }
  38. }
  39. namespace program {
  40. template <typename Impl>
  41. template <typename T>
  42. Arguments<Impl>::Argument::operator T() const {
  43. if (!primed()) {
  44. return T();
  45. } else if (self->arguments.size() > index) {
  46. return convert<T>(name, self->arguments.at(index));
  47. }
  48. throw IllegalPositionError("No argument provided", index);
  49. }
  50. template <typename Impl> Arguments<Impl>::Argument::operator bool() const {
  51. return primed() && self->arguments.size() > index;
  52. }
  53. template <typename Impl>
  54. template <typename T>
  55. auto Arguments<Impl>::Argument::operator=(T && value) {
  56. is_optional = true;
  57. if (description.size()) {
  58. using ::program::to_string;
  59. description += "\n Default Value: " + to_string(value);
  60. }
  61. return WithDefault<Argument, T>{*this, std::forward<T>(value)};
  62. }
  63. template <typename Impl> bool Arguments<Impl>::Argument::primed() const {
  64. if (self->primed_) { return true; }
  65. if (self->has_actions()) { throw ArgumentMixingError(); }
  66. if (is_optional) {
  67. self->optional_from = std::min(self->optional_from, index);
  68. } else if (self->optional_from < index) {
  69. throw ArgumentStructureError{"Required positional after optional", name};
  70. }
  71. if (!self->argument_names.emplace(index, name).second) {
  72. throw IllegalPositionError("Duplicate positional", index);
  73. }
  74. self->argument_descriptions.emplace(name, description);
  75. return false;
  76. }
  77. }
  78. namespace program {
  79. template <typename Impl>
  80. template <typename T>
  81. Arguments<Impl>::Flag::operator T() const {
  82. return primed(false) ? static_cast<T>(self->flags.at(name)) : T();
  83. }
  84. template <typename Impl> Arguments<Impl>::Flag::operator bool() const {
  85. return primed(true) ? static_cast<bool>(self->flags.at(name)) : default_value;
  86. }
  87. template <typename Impl> auto Arguments<Impl>::Flag::operator=(bool && value) {
  88. if (description.size()) {
  89. description += "\n Default Value: ";
  90. description += (value ? "true" : "false");
  91. }
  92. default_value = value;
  93. return *this;
  94. }
  95. template <typename Impl> bool Arguments<Impl>::Flag::primed(bool inv) const {
  96. if (self->primed_) { return self->flags.count(name); }
  97. std::vector<std::string> aliases;
  98. if (name.size() > 1 && inv) { aliases.push_back("no-" + name); }
  99. self->add_options(name, abbrev, description, aliases);
  100. self->flag_names.emplace(name);
  101. return false;
  102. }
  103. }
  104. namespace program {
  105. template <typename Impl>
  106. template <typename T>
  107. Arguments<Impl>::Option::operator T() const {
  108. return (*this) ? convert<T>(name, self->options.at(name)) : T();
  109. }
  110. template <typename Impl> Arguments<Impl>::Option::operator bool() const {
  111. return primed() && self->options.count(name);
  112. }
  113. template <typename Impl>
  114. template <typename T>
  115. auto Arguments<Impl>::Option::operator=(T && value) {
  116. if (description.size()) {
  117. using ::program::to_string;
  118. description += "\n Default Value: " + to_string(value);
  119. }
  120. return WithDefault<Option, T>{*this, std::forward<T>(value)};
  121. }
  122. template <typename Impl>
  123. template <typename T>
  124. auto Arguments<Impl>::Option::operator=(std::initializer_list<T> value) {
  125. if (description.size()) {
  126. using ::program::to_string;
  127. description += "\n Default Value: " + to_string(value);
  128. }
  129. return WithDefault<Option, std::initializer_list<T>>{*this, value};
  130. }
  131. template <typename Impl> bool Arguments<Impl>::Option::primed() const {
  132. if (self->primed_) { return true; }
  133. self->add_options(name, abbrev, description);
  134. return false;
  135. }
  136. }
  137. namespace program {
  138. template <typename Impl>
  139. template <typename B, typename V>
  140. template <typename T>
  141. Arguments<Impl>::WithDefault<B, V>::operator T() const {
  142. if (impl) { return impl; }
  143. if constexpr (std::is_invocable_r<T, V>{}) {
  144. return T(default_value());
  145. } else {
  146. return T{default_value};
  147. }
  148. }
  149. }
  150. namespace program {
  151. template <typename Impl>
  152. template <typename T>
  153. Arguments<Impl>::Arguments(int argc, char const * const * const argv,
  154. T const * parent) {
  155. Impl generator(parent);
  156. *this = static_cast<Arguments const &>(generator);
  157. if (argument_names.size() &&
  158. argument_names.rbegin()->first != argument_names.size() - 1) {
  159. throw IllegalPositionError("Higher positional than number recorded",
  160. argument_names.rbegin()->first);
  161. }
  162. primed_ = true;
  163. program = argv[0];
  164. for (size_t i = 1; i < argc; ++i) {
  165. std::string arg = argv[i];
  166. char const * const next = argv[i + 1];
  167. char abbrev = arg[1];
  168. if (arg == "--help") {
  169. usage();
  170. PROGRAM_ARGS_EXIT(0);
  171. } else if (arg == "--") {
  172. arguments.insert(arguments.end(), &next, &argv[argc]);
  173. break;
  174. } else if (auto hook = actions[arg]) {
  175. action_name_ = arg;
  176. make_action_ = hook(argc - i, argv + i);
  177. return;
  178. } else if (arg == "help" && next && actions[next]) {
  179. char const * const help[] = {next, "--help"};
  180. action_name_ = next;
  181. make_action_ = hook(2, help);
  182. return;
  183. } else if (arg[0] != '-') {
  184. arguments.emplace_back(arg);
  185. } else if (is_flag(arg)) {
  186. if (arg.substr(0, 5) == "--no-") {
  187. flags[id(arg)] = 0;
  188. } else {
  189. ++flags[id(arg)];
  190. }
  191. } else if (is_option(arg)) {
  192. options[id(arg)].emplace_back(argv[++i]);
  193. } else if (is_flag(abbrev) && arg.find_last_not_of("0123456789") == 1) {
  194. flags[id(abbrev)] = std::stoi(arg.substr(2));
  195. } else if (is_flag(abbrev)) {
  196. for (auto c : arg.substr(1)) {
  197. if (!is_flag(c)) { throw NotAnArgumentError({'-', c}); }
  198. ++flags[id(c)];
  199. }
  200. } else if (is_option(abbrev)) {
  201. options[id(abbrev)].emplace_back(arg.substr(2));
  202. } else {
  203. throw NotAnArgumentError(arg);
  204. }
  205. }
  206. }
  207. template <typename Impl> void Arguments<Impl>::usage() const {
  208. std::cout << program << " [options...]";
  209. for (auto & [index, name] : argument_names) {
  210. std::cout << " " << (index == optional_from ? "[" : "") << name;
  211. }
  212. if (rest_name.size()) { std::cout << " [" << rest_name << "...]"; }
  213. if (optional_from != no_optional_args) { std::cout << "]"; }
  214. std::cout << "\nArgument Arguments:\n";
  215. for (auto & [name, desc] : argument_descriptions) {
  216. std::cout << " " << name << ": " << desc << "\n";
  217. }
  218. std::cout << "Options:\n";
  219. for (auto & [opt, desc] : option_descriptions) {
  220. std::cout << " " << opt << ": " << desc << "\n";
  221. }
  222. }
  223. template <typename Impl>
  224. void Arguments<Impl>::add_options(std::string const & name, char abbrev,
  225. std::string const & description,
  226. std::vector<std::string> aliases) {
  227. for (auto & str : aliases) {
  228. str = "--" + str;
  229. }
  230. if (name.size() > 1) { aliases.push_back("--" + name); }
  231. if (abbrev) { aliases.push_back(std::string{'-', abbrev}); }
  232. for (auto & str : aliases) {
  233. if (!option_names.emplace(str, name).second) {
  234. throw ArgumentStructureError("Duplicate option string", str);
  235. }
  236. }
  237. option_descriptions.emplace(join(",", aliases), description);
  238. }
  239. template <typename Impl>
  240. auto Arguments<Impl>::id(std::string const & arg) const -> option_id {
  241. if (!is_option(arg)) { throw NotAnArgumentError(arg); }
  242. return option_names.at(arg);
  243. }
  244. template <typename Impl>
  245. bool Arguments<Impl>::is_option(std::string const & arg) const {
  246. return option_names.count(arg);
  247. }
  248. template <typename Impl>
  249. bool Arguments<Impl>::is_flag(std::string const & arg) const {
  250. return is_option(arg) && flag_names.count(id(arg));
  251. }
  252. template <typename Impl>
  253. auto Arguments<Impl>::action(LongArg name, std::string const & description) {
  254. return Action{this, name, description};
  255. }
  256. template <typename Impl>
  257. auto Arguments<Impl>::argument(size_t index, LongArg name,
  258. std::string const & description) {
  259. return Argument{this, index, false, name, description};
  260. }
  261. template <typename Impl>
  262. std::vector<std::string>
  263. Arguments<Impl>::rest(LongArg name, std::string const & description) {
  264. if (has_actions()) { throw ArgumentMixingError(); }
  265. if (!rest_name.empty() && rest_name != name.str) {
  266. throw ArgumentStructureError("duplicate rest() parameter", name);
  267. }
  268. rest_name = name;
  269. argument_descriptions.emplace(name, description);
  270. size_t const i = std::min(arguments.size(), argument_names.size());
  271. return {arguments.begin() + i, arguments.end()};
  272. }
  273. template <typename Impl>
  274. auto Arguments<Impl>::flag(LongArg name, std::string const & description) {
  275. return Flag{this, name, 0, description, false};
  276. }
  277. template <typename Impl>
  278. auto Arguments<Impl>::flag(LongArg name, char abbrev,
  279. std::string const & description) {
  280. return Flag{this, name, abbrev, description, false};
  281. }
  282. template <typename Impl>
  283. auto Arguments<Impl>::flag(char abbrev, std::string const & description) {
  284. return Flag{this, {abbrev}, abbrev, description, false};
  285. }
  286. template <typename Impl>
  287. auto Arguments<Impl>::option(LongArg name, std::string const & description) {
  288. return Option{this, name, 0, description};
  289. }
  290. template <typename Impl>
  291. auto Arguments<Impl>::option(LongArg name, char abbrev,
  292. std::string const & description) {
  293. return Option{this, name, abbrev, description};
  294. }
  295. template <typename Impl>
  296. auto Arguments<Impl>::option(char abbrev, std::string const & description) {
  297. return Option{this, {abbrev}, abbrev, description};
  298. }
  299. template <typename Impl>
  300. template <typename DA, typename T, size_t... Is, typename... Ps>
  301. int Arguments<Impl>::invoke_action(DA const & default_action, T const & tuple,
  302. std::index_sequence<Is...>,
  303. Ps const &... ps) const {
  304. // Only actions that were reached in the constructor will ever have the
  305. // primed_ flag set to true. Therefore, there is a guarantee that this
  306. // function will only call invoke() on a child one or zero times.
  307. auto invoke_one = [this, &ps...](auto const & action) {
  308. if (!action.primed_) { return std::make_pair(false, 0); }
  309. return std::make_pair(true, action.invoke(ps..., self()));
  310. };
  311. // Because of that, it is safe to use a map from bool => status
  312. // Since we only care about the case where an action was invoked.
  313. std::map<bool, int> const rval{invoke_one(std::get<Is>(tuple))...};
  314. if (rval.count(true)) { return rval.at(true); }
  315. // If no action was invoked, then we need to handle the fallthrough case
  316. // For certain circumstances, such as how git allows custom actions with
  317. // a plugin system, we allow you to specify a default action of self.
  318. if constexpr (std::is_same_v<DA, require_action_t>) {
  319. usage();
  320. return 1;
  321. } else if constexpr (std::is_same_v<DA, Impl>) {
  322. return typed_main(ps..., self());
  323. } else {
  324. return default_action.invoke(ps..., self());
  325. }
  326. }
  327. }
  328. namespace program {
  329. template <typename... Ts> auto actions(Ts const &... ts) {
  330. return std::forward_as_tuple(ts...);
  331. }
  332. template <typename... Ts> auto count(Ts const &...) {
  333. return std::make_index_sequence<sizeof...(Ts)>{};
  334. }
  335. }