arguments_impl.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 T>
  140. auto Arguments<Impl>::Rest::operator=(T && value) {
  141. return WithDefault<Rest, T>{*this, std::forward<T>(value)};
  142. }
  143. template <typename Impl>
  144. Arguments<Impl>::Rest::operator std::vector<std::string>() const {
  145. return self->args();
  146. }
  147. template <typename Impl> Arguments<Impl>::Rest::operator bool() const {
  148. return self->arguments.size() > self->argument_names.size();
  149. }
  150. }
  151. namespace program {
  152. template <typename Impl>
  153. template <typename B, typename V>
  154. template <typename T>
  155. Arguments<Impl>::WithDefault<B, V>::operator T() const {
  156. if (impl) { return impl; }
  157. if constexpr (std::is_invocable_r<T, V>{}) {
  158. return T{default_value()};
  159. } else {
  160. return T{default_value};
  161. }
  162. }
  163. }
  164. namespace program {
  165. template <typename Impl>
  166. template <typename T>
  167. Arguments<Impl>::Arguments(int argc, char const * const * const argv,
  168. T const * parent) {
  169. Impl generator(parent);
  170. *this = static_cast<Arguments const &>(generator);
  171. if (argument_names.size() &&
  172. argument_names.rbegin()->first != argument_names.size() - 1) {
  173. throw IllegalPositionError("Higher positional than number recorded",
  174. argument_names.rbegin()->first);
  175. }
  176. primed_ = true;
  177. program = argv[0];
  178. for (size_t i = 1; i < argc; ++i) {
  179. std::string arg = argv[i];
  180. char const * const next = argv[i + 1];
  181. char abbrev = arg[1];
  182. if (arg == "--help") {
  183. usage();
  184. PROGRAM_ARGS_EXIT(0);
  185. } else if (arg == "--") {
  186. arguments.insert(arguments.end(), &next, &argv[argc]);
  187. break;
  188. } else if (auto hook = actions[arg]) {
  189. action_name_ = arg;
  190. make_action_ = hook(argc - i, argv + i);
  191. return;
  192. } else if (arg == "help" && next && actions[next]) {
  193. char const * const help[] = {next, "--help"};
  194. action_name_ = next;
  195. make_action_ = hook(2, help);
  196. return;
  197. } else if (arg[0] != '-') {
  198. arguments.emplace_back(arg);
  199. } else if (is_flag(arg)) {
  200. if (arg.substr(0, 5) == "--no-") {
  201. flags[id(arg)] = 0;
  202. } else {
  203. ++flags[id(arg)];
  204. }
  205. } else if (is_option(arg)) {
  206. options[id(arg)].emplace_back(argv[++i]);
  207. } else if (is_flag(abbrev) && arg.find_last_not_of("0123456789") == 1) {
  208. flags[id(abbrev)] = std::stoi(arg.substr(2));
  209. } else if (is_flag(abbrev)) {
  210. for (auto c : arg.substr(1)) {
  211. if (!is_flag(c)) { throw NotAnArgumentError({'-', c}); }
  212. ++flags[id(c)];
  213. }
  214. } else if (is_option(abbrev)) {
  215. options[id(abbrev)].emplace_back(arg.substr(2));
  216. } else {
  217. throw NotAnArgumentError(arg);
  218. }
  219. }
  220. }
  221. template <typename Impl> void Arguments<Impl>::usage() const {
  222. std::cout << program << " [options...]";
  223. for (auto & [index, name] : argument_names) {
  224. std::cout << " " << (index == optional_from ? "[" : "") << name;
  225. }
  226. if (rest_name.size()) { std::cout << " [" << rest_name << "...]"; }
  227. if (optional_from != no_optional_args) { std::cout << "]"; }
  228. std::cout << "\nArgument Arguments:\n";
  229. for (auto & [name, desc] : argument_descriptions) {
  230. std::cout << " " << name << ": " << desc << "\n";
  231. }
  232. std::cout << "Options:\n";
  233. for (auto & [opt, desc] : option_descriptions) {
  234. std::cout << " " << opt << ": " << desc << "\n";
  235. }
  236. }
  237. template <typename Impl>
  238. void Arguments<Impl>::add_options(std::string const & name, char abbrev,
  239. std::string const & description,
  240. std::vector<std::string> aliases) {
  241. for (auto & str : aliases) {
  242. str = "--" + str;
  243. }
  244. if (name.size() > 1) { aliases.push_back("--" + name); }
  245. if (abbrev) { aliases.push_back(std::string{'-', abbrev}); }
  246. for (auto & str : aliases) {
  247. if (!option_names.emplace(str, name).second) {
  248. throw ArgumentStructureError("Duplicate option string", str);
  249. }
  250. }
  251. option_descriptions.emplace(join(",", aliases), description);
  252. }
  253. template <typename Impl>
  254. auto Arguments<Impl>::id(std::string const & arg) const -> option_id {
  255. if (!is_option(arg)) { throw NotAnArgumentError(arg); }
  256. return option_names.at(arg);
  257. }
  258. template <typename Impl>
  259. bool Arguments<Impl>::is_option(std::string const & arg) const {
  260. return option_names.count(arg);
  261. }
  262. template <typename Impl>
  263. bool Arguments<Impl>::is_flag(std::string const & arg) const {
  264. return is_option(arg) && flag_names.count(id(arg));
  265. }
  266. template <typename Impl>
  267. auto Arguments<Impl>::action(LongArg name, std::string const & description) {
  268. return Action{this, name, description};
  269. }
  270. template <typename Impl>
  271. auto Arguments<Impl>::argument(size_t index, LongArg name,
  272. std::string const & description) {
  273. return Argument{this, index, false, name, description};
  274. }
  275. template <typename Impl>
  276. auto Arguments<Impl>::rest(LongArg name, std::string const & description) {
  277. if (has_actions()) { throw ArgumentMixingError(); }
  278. if (!rest_name.empty() && rest_name != name.str) {
  279. throw ArgumentStructureError("duplicate rest() parameter", name);
  280. }
  281. rest_name = name;
  282. argument_descriptions.emplace(name, description);
  283. return Rest{this};
  284. }
  285. template <typename Impl>
  286. auto Arguments<Impl>::flag(LongArg name, std::string const & description) {
  287. return Flag{this, name, 0, description, false};
  288. }
  289. template <typename Impl>
  290. auto Arguments<Impl>::flag(LongArg name, char abbrev,
  291. std::string const & description) {
  292. return Flag{this, name, abbrev, description, false};
  293. }
  294. template <typename Impl>
  295. auto Arguments<Impl>::flag(char abbrev, std::string const & description) {
  296. return Flag{this, {abbrev}, abbrev, description, false};
  297. }
  298. template <typename Impl>
  299. auto Arguments<Impl>::option(LongArg name, std::string const & description) {
  300. return Option{this, name, 0, description};
  301. }
  302. template <typename Impl>
  303. auto Arguments<Impl>::option(LongArg name, char abbrev,
  304. std::string const & description) {
  305. return Option{this, name, abbrev, description};
  306. }
  307. template <typename Impl>
  308. auto Arguments<Impl>::option(char abbrev, std::string const & description) {
  309. return Option{this, {abbrev}, abbrev, description};
  310. }
  311. template <typename Impl>
  312. template <typename DA, typename T, size_t... Is, typename... Ps>
  313. int Arguments<Impl>::invoke_action(DA const & default_action, T const & tuple,
  314. std::index_sequence<Is...>,
  315. Ps const &... ps) const {
  316. // Only actions that were reached in the constructor will ever have the
  317. // primed_ flag set to true. Therefore, there is a guarantee that this
  318. // function will only call invoke() on a child one or zero times.
  319. auto invoke_one = [this, &ps...](auto const & action) {
  320. if (!action.primed_) { return std::make_pair(false, 0); }
  321. return std::make_pair(true, action.invoke(ps..., self()));
  322. };
  323. // Because of that, it is safe to use a map from bool => status
  324. // Since we only care about the case where an action was invoked.
  325. std::map<bool, int> const rval{invoke_one(std::get<Is>(tuple))...};
  326. if (rval.count(true)) { return rval.at(true); }
  327. // If no action was invoked, then we need to handle the fallthrough case
  328. // For certain circumstances, such as how git allows custom actions with
  329. // a plugin system, we allow you to specify a default action of self.
  330. if constexpr (std::is_same_v<DA, require_action_t>) {
  331. usage();
  332. return 1;
  333. } else if constexpr (std::is_same_v<DA, Impl>) {
  334. return typed_main(ps..., self());
  335. } else {
  336. return default_action.invoke(ps..., self());
  337. }
  338. }
  339. }
  340. namespace program {
  341. template <typename... Ts> auto actions(Ts const &... ts) {
  342. return std::forward_as_tuple(ts...);
  343. }
  344. template <typename... Ts> auto count(Ts const &...) {
  345. return std::make_index_sequence<sizeof...(Ts)>{};
  346. }
  347. }