FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
arg_parser.hpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#pragma once
7
8#include <kernel/runtime.hpp>
10#include <kernel/util/property_map.hpp>
11#include <kernel/util/string.hpp>
12
13#include <any>
14#include <deque>
15#include <functional>
16#include <iostream>
17#include <memory>
18#include <sstream>
19#include <stdexcept>
20#include <utility>
21
22namespace FEAT
23{
24 // Architecture Notes. Read class documentation of ArgParser first.
25 // The core of this argument parser implementation consists of four classes
26 // - ArgParser is the actual parser
27 // - Parameter is the user-facing interface of a parameter
28 // - ParameterCore is the inner interface of a parameter used by the ArgParser
29 // - ParameterBuilder is a class implementing the builder pattern to define parameters
30 //
31 // The split into Parameter and ParameterCore is a matter of type-erasure.
32 // We want to both present a neat and well-typed interface to the user and
33 // automatically handle the parameters in the parser.
34 // But the parser can not handle the templated Parameters directly, because
35 // they form a non-homogenous collection. To solve this the Parameter class
36 // is just a thin wrapper around a type-erased ParameterCore.
37 // The parser can handle the ParameterCores, and the Parameter presents a
38 // well-typed interface.
39 //
40 // To achieve this type-erasure the ParameterCore stores its parsed values
41 // in a std::any (essentially a void* and a type tag). Any type dependent
42 // logic required by the ParameterCore (parsing and validation, for now)
43 // is handled by supplying functions that accept std::any to the ParameterCore.
44 // These functions are constructed during the parameter definition
45 // (when type information is still available), by wrapping the properly
46 // typed functions into std::any_casts.
47 //
48 // Thus the ArgParser holds a list of shared pointers to ParameterCores and has
49 // the Parameters as members. The parameters hold a shared pointer to their
50 // respective ParameterCore as well. The ArgParser then uses its list of
51 // parameter cores to match arguments to parameters during parsing.
52 //
53 // Start reading at ArgParser::parameter to see how parameters are created and defined.
54 // Start reading at ArgParser::parse to see how parsing is implemented.
55
56 namespace Intern
57 {
59 template<typename>
60 struct is_std_deque : std::false_type
61 {
62 };
63
65 template<typename T, typename A>
66 struct is_std_deque<std::deque<T, A>> : std::true_type
67 {
68 };
69
71 template<typename T>
72 constexpr bool is_std_deque_v = is_std_deque<T>::value;
73
75 template<typename>
76 struct is_std_map : std::false_type
77 {
78 };
79
81 template<typename K, typename V, typename C, typename A>
82 struct is_std_map<std::map<K, V, C, A>> : std::true_type
83 {
84 };
85
87 template<typename T>
88 constexpr bool is_std_map_v = is_std_map<T>::value;
89
91 template<typename T, typename = void>
92 struct has_input_operator : std::false_type
93 {
94 };
95
97 template<typename T>
98 struct has_input_operator<T, std::void_t<decltype((std::declval<std::istringstream&>() >> std::declval<T&>()))>>
99 : std::true_type
100 {
101 };
102
104 template<typename T>
105 constexpr bool can_default_parse_v = has_input_operator<T>::value;
106
108 template<typename T, typename A>
109 constexpr bool can_default_parse_v<std::deque<T, A>> = has_input_operator<T>::value;
110
112 template<typename K, typename V, typename C, typename A>
113 constexpr bool can_default_parse_v<std::map<K, V, C, A>> =
115
117 template<typename T_>
118 static void parse_deque(std::any& any, const String& s)
119 {
120 std::deque<T_> collection;
121 for(const String& value_str : s.split_by_whitespaces())
122 {
123 T_ tmp{};
124 if(!value_str.parse(tmp))
125 {
126 throw std::invalid_argument("Parsing failed for string '" + s + "'");
127 }
128 collection.push_back(tmp);
129 }
130
131 any = collection;
132 }
133
135 template<typename K_, typename V_>
136 static void parse_map(std::any& any, const String& s)
137 {
138 std::map<K_, V_> map;
139 auto strs = s.split_by_whitespaces();
140
141 if(!(strs.size() % 2 == 0))
142 {
143 throw std::invalid_argument("Parsing failed for string '" + s + "': Odd number of strings in key-value pairs.");
144 }
145
146 for(Index i(0); i < strs.size(); i += 2)
147 {
148 K_ key{};
149 V_ value{};
150
151 if(!strs[i].parse(key))
152 {
153 throw std::invalid_argument("Parsing failed for string '" + s + "': Could not parse key '" + strs[i] + "'");
154 }
155
156 if(!strs[i + 1].parse(value))
157 {
158 throw std::invalid_argument("Parsing failed for string '" + s + "': Could not parse value '" + strs[i] + "'");
159 }
160
161 map.insert({key, value});
162 }
163
164 any = map;
165 }
166
168 template<typename T_>
169 static void parse_single(std::any& any, const String& s)
170 {
171 if(!s.parse(std::any_cast<T_&>(any)))
172 {
173 throw std::invalid_argument("Parsing failed for string '" + s + "'");
174 }
175 }
176
196 template<typename T_>
197 static void (*make_parser())(std::any&, const String&)
198 {
199 // If T_ has no input operator then instantiating a parser function for T_ will fail,
200 // because String::parse depends on that operator.
201 // But we want to give the user a chance to set a custom parser,
202 // so we guard the instantiation of the default parser behind
203 // can_default_parse_v
204
205 if constexpr(!can_default_parse_v<T_>)
206 {
207 return nullptr;
208 }
209 else
210 {
211 if constexpr(is_std_deque_v<T_>)
212 {
213 return parse_deque<typename T_::value_type>;
214 }
215 else if constexpr(is_std_map_v<T_>)
216 {
217 return parse_map<typename T_::key_type, typename T_::mapped_type>;
218 }
219 else
220 {
221 return parse_single<T_>;
222 }
223 }
224 }
225
236 template<typename T_>
237 static void (*make_printer())(std::ostream&, const std::any&)
238 {
239 if constexpr(is_std_deque_v<T_>)
240 {
241 return [](std::ostream& s, const std::any& v)
242 {
243 s << "[";
244 for(const auto& i : std::any_cast<const T_&>(v))
245 {
246 s << i << ", ";
247 }
248 s << "]";
249 };
250 }
251 else if constexpr(is_std_map_v<T_>)
252 {
253 return [](std::ostream& s, const std::any& v)
254 {
255 s << "{";
256 for(const auto& [key, value] : std::any_cast<const T_&>(v))
257 {
258 s << key << ": " << value << ", ";
259 }
260 s << "}";
261 };
262 }
263 else
264 {
265 return [](std::ostream& s, const std::any& v) { s << std::any_cast<const T_&>(v); };
266 }
267 }
268
276 enum class ParameterType : std::uint8_t
277 {
278 flag,
279 option,
280 collection_option,
281 };
282
299 {
300 public:
302 using ParserType = std::function<void(std::any&, const String&)>;
304 using ValidatorType = std::function<void(const std::any&)>;
306 using PrinterType = std::function<void(std::ostream&, const std::any&)>;
308 using DeriverType = std::function<void(std::any&, const std::deque<std::reference_wrapper<std::any>>&)>;
310 using PredicateType = std::function<bool(const std::any&)>;
311
313 using Need = std::pair<std::weak_ptr<ParameterCore>, PredicateType>;
314
316 using HideIf = std::pair<std::weak_ptr<ParameterCore>, PredicateType>;
317
318 // Parsing information
319 ParameterType type = ParameterType::flag;
320 String short_flag{""};
321 String long_flag{""};
322 String environment_variable{""};
323 String property_path{""};
324
325 // Strings for usage documentation
326 String custom_name;
327 String placeholder;
328 String help_string;
329
330 // Metadata
331 int priority = 0;
332 bool required = false;
333 bool bootstrap = false;
334 bool set_by_user = false;
335 bool hidden = false;
336 std::deque<Need> needs;
337 std::deque<HideIf> hide_if;
338 std::deque<std::weak_ptr<ParameterCore>> derives_from;
339
340 // Raw and parsed values
341 std::deque<String> arguments;
342 std::any default_value;
343 std::any value;
344
345 // Type-erased functions
346 ParserType parser;
347 ValidatorType validator;
348 PrinterType printer;
349 DeriverType deriver;
350
352 template<typename T_>
353 explicit ParameterCore(T_ def_value) :
354 default_value(def_value),
355 value(default_value),
356 printer(Intern::make_printer<T_>())
357 {
358 if constexpr(std::is_same_v<T_, bool>)
359 {
360 // Boolean flags do not consume any arguments beyond the flag itself
361 type = ParameterType::flag;
362 }
363 else if constexpr(Intern::is_std_deque_v<T_> || Intern::is_std_map_v<T_>)
364 {
365 // Collection options append all arguments until the next flag
366 type = ParameterType::collection_option;
367 }
368 else
369 {
370 type = ParameterType::option;
371 }
372 }
373
380 String name() const;
381
383 void add_argument(const String& s, int incoming_priority);
384
390 void validate(std::deque<String>& errors) const;
391
397 void parse(std::deque<String>& errors);
398
406 void derive_self();
407
411 void hide();
412
414 void reset();
415 };
416
417 } // namespace Intern
418
419 template<typename T_>
420 class ParameterBuilder;
421
427 template<typename T_>
429 {
430 private:
431 std::shared_ptr<Intern::ParameterCore> _core;
432
433 public:
434 template<typename U_>
435 friend class ParameterBuilder;
436
437 explicit Parameter(std::shared_ptr<Intern::ParameterCore>&& core) : _core(std::move(core))
438 {
439 }
440
441 explicit Parameter(std::shared_ptr<Intern::ParameterCore> core) : _core(std::move(core))
442 {
443 }
444
450 bool set_by_user() const
451 {
452 return _core->set_by_user;
453 }
454
456 const T_& value() const
457 {
458 XASSERTM(
459 !_core->hidden,
460 "Trying to access hidden parameter " + _core->name() + ". Check your parameter definitions.");
461 return std::any_cast<const T_&>(_core->value);
462 }
463
465 const T_& operator*() const
466 {
467 XASSERTM(
468 !_core->hidden,
469 "Trying to access hidden parameter " + _core->name() + ". Check your parameter definitions.");
470 return std::any_cast<const T_&>(_core->value);
471 }
472
474 const T_* operator->() const
475 {
476 XASSERTM(
477 !_core->hidden,
478 "Trying to access hidden parameter " + _core->name() + ". Check your parameter definitions.");
479 return std::any_cast<const T_>(&(_core->value));
480 }
481 };
482
484 template<typename T_>
486 {
487 private:
488 std::shared_ptr<Intern::ParameterCore> _core;
489
490 String _env_prefix;
491 String _property_path_prefix;
492 String _flag_prefix;
493
494 public:
495 explicit ParameterBuilder(
496 std::shared_ptr<Intern::ParameterCore> core,
497 String env_prefix,
498 String property_path_prefix,
499 String flag_prefix) :
500 _core(std::move(core)),
501 _env_prefix(std::move(env_prefix)),
502 _property_path_prefix(std::move(property_path_prefix)),
503 _flag_prefix(std::move(flag_prefix))
504 {
505 }
506
513 {
514 // Prepend dash if required
515 if(!s.starts_with("-"))
516 {
517 s = "-" + s;
518 }
519
520 XASSERTM(s.size() == 2, "Short flag must have length two");
521 XASSERTM(s[0] == '-', "Short must start with a '-'");
522 XASSERTM(s[1] != '-', "Short must not end with a '-'");
523
524 _core->short_flag = std::move(s);
525 return *this;
526 }
527
535 {
536 XASSERTM(!s.empty(), "Long flag must not be empty");
537
538 // Remove leading dashes
539 if(s.starts_with("--"))
540 {
541 s = s.substr(2);
542 }
543
544 // Append flag prefix if applicable
545 if(!_flag_prefix.empty())
546 {
547 s = _flag_prefix + "-" + s;
548 }
549
550 _core->long_flag = "--" + s;
551 return *this;
552 }
553
563 {
564 if(!_env_prefix.empty())
565 {
566 _core->environment_variable = _env_prefix + "_" + s;
567 }
568 else
569 {
570 _core->environment_variable = std::move(s);
571 }
572 return *this;
573 }
574
587 {
588 if(!_property_path_prefix.empty())
589 {
590 _core->property_path = _property_path_prefix + "/" + s;
591 }
592 else
593 {
594 _core->property_path = std::move(s);
595 }
596 return *this;
597 }
598
618 {
619 s.trim();
620 _core->help_string = std::move(s);
621 return *this;
622 }
623
643 {
644 _core->placeholder = std::move(s);
645 return *this;
646 }
647
659 {
660 _core->custom_name = std::move(s);
661 return *this;
662 }
663
676 ParameterBuilder& parser(T_ (*parser_fn)(const String&))
677 {
678 // SAFETY:
679 // Functions exist for the lifetime of the program.
680 // Thus a valid function pointer will never dangle
681 // and calling this lambda later is always safe
682 const auto lambda = [parser_fn](std::any& any, const String& s) { any = parser_fn(s); };
683 _core->parser = lambda;
684
685 return *this;
686 }
687
704 ParameterBuilder& validator(void (*validator_fn)(const T_&))
705 {
706 XASSERTM(validator_fn != nullptr, "Validator must be valid function pointer!");
707
708 // NOTE:
709 // We accept a function pointer here, because it
710 // forbids the user from passing us a lambda-expression
711 // that captures something from its environment
712
713 // SAFETY:
714 // Functions exist for the lifetime of the program.
715 // Thus a valid function pointer will never dangle
716 // and calling this lambda later is always safe
717 const auto lambda = [validator_fn](const std::any& any) { validator_fn(std::any_cast<const T_&>(any)); };
718 _core->validator = lambda;
719
720 return *this;
721 }
722
741 ParameterBuilder& validator(bool (*validator_fn)(const T_&))
742 {
743 XASSERTM(validator_fn != nullptr, "Validator must be valid function pointer!");
744
745 // NOTE:
746 // We accept a function pointer here, because it
747 // forbids the user from passing us a lambda-expression
748 // that captures something from its environment
749
750 // SAFETY:
751 // Functions exist for the lifetime of the program.
752 // Thus a valid function pointer will never dangle
753 // and calling this lambda later is always safe
754 const auto lambda = [validator_fn](const std::any& any)
755 {
756 if(!validator_fn(std::any_cast<const T_&>(any)))
757 {
758 throw std::invalid_argument("Failed boolean test");
759 }
760 };
761 _core->validator = lambda;
762
763 return *this;
764 }
765
773 {
774 _core->required = true;
775
776 return *this;
777 }
778
798 template<typename U_>
800 {
801 XASSERTM(parameter._core != nullptr, "Needed parameter must be defined already!");
802
803 _core->needs.emplace_back(parameter._core, [](const std::any& /*unused*/) { return true; });
804
805 return *this;
806 }
807
829 template<typename U_>
830 ParameterBuilder& needs_if(const Parameter<U_>& parameter, bool (*condition)(const T_&))
831 {
832 XASSERTM(parameter._core != nullptr, "Needed parameter must be defined already!");
833
834 _core->needs.emplace_back(
835 parameter._core,
836 [condition](const std::any& value) { return condition(std::any_cast<const T_&>(value)); });
837
838 return *this;
839 }
840
860 template<typename U_>
861 ParameterBuilder& hide_if(const Parameter<U_>& parameter, bool (*condition)(const T_&))
862 {
863 XASSERTM(parameter._core != nullptr, "Needed parameter must be defined already!");
864
865 _core->hide_if.emplace_back(
866 parameter._core,
867 [condition](const std::any& value) { return condition(std::any_cast<const T_&>(value)); });
868
869 return *this;
870 }
871
887 template<typename V_ = T_, typename = std::enable_if_t<std::is_same_v<std::deque<String>, V_>>>
889 {
890 _core->bootstrap = true;
891
892 return *this;
893 }
894
907 template<typename U_>
908 ParameterBuilder& derives_from(const Parameter<U_>& param, T_ (*fn)(const U_&))
909 {
910 XASSERTM(param._core != nullptr, "Derivee needs to be initialized");
911
912 // NOTE(mmuegge): It is totally possible to abstract over derives_from_1
913 // and derives_from_2: The easiest way would probably be to convert the
914 // std::deque passed into the deriver into a tuple of the same length as
915 // the number of parameters this parameter is derived from, then cast the
916 // tuple to the proper types via a fold-expression, then use std::apply to
917 // call fn with the arguments from the tuple. All of that code is
918 // possible, but just plain ugly and hard to understand. So I choose the
919 // easy route for now.
920
921 _core->derives_from.clear();
922 _core->derives_from.emplace_back(param._core);
923 _core->deriver = [fn](std::any& out, const std::deque<std::reference_wrapper<std::any>>& args)
924 {
925 XASSERT(args.size() >= 1);
926 out = fn(std::any_cast<const U_&>(args[0]));
927 };
928
929 return *this;
930 }
931
933 template<typename U_, typename Fn_>
935 {
936 return derives_from(param, static_cast<T_ (*)(const U_&)>(std::forward<Fn_>(fn)));
937 }
938
952 template<typename U_, typename V_>
953 ParameterBuilder& derives_from(const Parameter<U_>& param_one, const Parameter<V_>& param_two, T_ (*fn)(const U_&, const V_&))
954 {
955 XASSERTM(param_one._core != nullptr, "Derivee needs to be initialized");
956 XASSERTM(param_two._core != nullptr, "Derivee needs to be initialized");
957
958 _core->derives_from.clear();
959 _core->derives_from.emplace_back(param_one._core);
960 _core->derives_from.emplace_back(param_two._core);
961 _core->deriver = [fn](std::any& out, const std::deque<std::reference_wrapper<std::any>>& args)
962 {
963 XASSERT(args.size() >= 2);
964 out = fn(std::any_cast<const U_&>(args[0]), std::any_cast<const V_&>(args[1]));
965 };
966
967 return *this;
968 }
969
971 template<typename U_, typename V_, typename Fn_>
972 ParameterBuilder& derives_from(const Parameter<U_>& param_one, const Parameter<V_>& param_two, Fn_&& fn)
973 {
974 return derives_from(param_one, param_two, static_cast<T_ (*)(const U_&, const V_&)>(std::forward<Fn_>(fn)));
975 }
976
991 template<typename U_, typename V_, typename W_>
993 const Parameter<U_>& param_one,
994 const Parameter<V_>& param_two,
995 const Parameter<W_>& param_three,
996 T_ (*fn)(const U_&, const V_&, const W_&))
997 {
998 XASSERTM(param_one._core != nullptr, "Derivee needs to be initialized");
999 XASSERTM(param_two._core != nullptr, "Derivee needs to be initialized");
1000 XASSERTM(param_three._core != nullptr, "Derivee needs to be initialized");
1001
1002 _core->derives_from.clear();
1003 _core->derives_from.emplace_back(param_one._core);
1004 _core->derives_from.emplace_back(param_two._core);
1005 _core->derives_from.emplace_back(param_three._core);
1006 _core->deriver = [fn](std::any& out, const std::deque<std::reference_wrapper<std::any>>& args)
1007 {
1008 XASSERT(args.size() >= 3);
1009 out =
1010 fn(std::any_cast<const U_&>(args[0]), std::any_cast<const V_&>(args[1]), std::any_cast<const W_&>(args[2]));
1011 };
1012
1013 return *this;
1014 }
1015
1017 template<typename U_, typename V_, typename W_, typename Fn_>
1019 derives_from(const Parameter<U_>& param_one, const Parameter<V_>& param_two, const Parameter<W_>& param_three, Fn_&& fn)
1020 {
1021 return derives_from(
1022 param_one,
1023 param_two,
1024 param_three,
1025 static_cast<T_ (*)(const U_&, const V_&, const W_&)>(std::forward<Fn_>(fn)));
1026 }
1027
1028 // NOTE: This conversion operator exists to convert the ParameterBuilder produced by ArgParser::parameter
1029 // into a parameter without forcing the user to call an additional function for every parameter.
1030 // For that reason it is deliberately implicit
1032 operator Parameter<T_>() // NOLINT
1033 {
1034 if(_core->placeholder.empty())
1035 {
1036 if(!_core->long_flag.empty())
1037 {
1038 _core->placeholder = _core->long_flag.substr(2);
1039 }
1040 else if(!_core->short_flag.empty())
1041 {
1042 _core->placeholder = _core->short_flag.substr(1);
1043 }
1044 }
1045
1046 if(!_core->parser)
1047 {
1048 _core->parser = Intern::make_parser<T_>();
1049 }
1050 return Parameter<T_>(_core);
1051 }
1052 };
1053
1229 {
1230 private:
1231 std::deque<std::shared_ptr<Intern::ParameterCore>> _parameters;
1232 std::deque<String> _errors;
1233
1238
1245
1248
1249 static constexpr int priority_default = 0;
1250 static constexpr int priority_env = 1;
1251 static constexpr int priority_property = 2;
1252 static constexpr int priority_cli = 3;
1253
1254 public:
1255 ArgParser() = default;
1256
1258 ArgParser(String env_prefix, String property_prefix, String flag_prefix) :
1259 _env_prefix(std::move(env_prefix)),
1260 _property_prefix(std::move(property_prefix)),
1261 _flag_prefix(std::move(flag_prefix))
1262 {
1263 }
1264
1276 void allow_unknown_cli_flags(bool allow = true)
1277 {
1279 }
1280
1282 const std::deque<String>& errors() const
1283 {
1284 return _errors;
1285 }
1286
1294 void set_description(String&& description)
1295 {
1296 _description = std::move(description);
1297 }
1298
1306 [[nodiscard]] String help_text() const;
1307
1316 [[nodiscard]] String display() const;
1317
1335 [[nodiscard]] bool bootstrap(int argc, const char* const* argv, PropertyMap& pmap);
1336
1348 [[nodiscard]] bool parse(int argc, const char* const* argv, const PropertyMap* property_map = nullptr);
1349
1357 [[nodiscard]] bool parse(const PropertyMap& property_map)
1358 {
1359 return parse(0, nullptr, &property_map);
1360 }
1361
1373 [[nodiscard]] bool parse(int argc, const char* const* argv, const String& property_map_path)
1374 {
1375 PropertyMap pmap;
1376 pmap.read(property_map_path);
1377 return parse(argc, argv, &pmap);
1378 }
1379
1387 [[nodiscard]] bool parse(const String& property_map_path)
1388 {
1389 PropertyMap pmap;
1390 pmap.read(property_map_path);
1391 return parse(0, nullptr, &pmap);
1392 }
1393
1403
1413
1414 protected:
1422 template<typename T_>
1423 ParameterBuilder<T_> parameter(T_&& default_value = T_{})
1424 {
1425 // Create type-erased parameter core
1426 std::shared_ptr<Intern::ParameterCore> core =
1427 std::make_shared<Intern::ParameterCore>(std::forward<T_>(default_value));
1428
1429 // Store type-erased core for parsing purposes.
1430 // This allows the parser to treat all parameters the same,
1431 // irrespective of the types of their values.
1432 _parameters.push_back(core);
1433
1434 // Return builder to user for defining the parameter fully
1436 }
1437
1458 template<typename Parser_>
1459 Parser_ parser(String env_prefix = "", String property_path_prefix = "", String flag_prefix = "")
1460 {
1461 // NOTE: On the implementation of this function. Rather than parsing fully
1462 // recursively, and having to deal with tracking of used arguments and
1463 // error handling across parsers, we just add all parameters of the
1464 // sub-parser (with their prefix) to this parser. The parse method of this
1465 // parser will then parse the parameters the same way it parses its own
1466 // parameters. This might be terribly inconvenient later, but is very easy
1467 // to implement for now.
1468 const auto append = [](const String& a, const String& b, char delimiter) -> String
1469 {
1470 if(a.empty())
1471 {
1472 return b;
1473 }
1474 else if(!b.empty())
1475 {
1476 return a + delimiter + b;
1477 }
1478 else
1479 {
1480 return "";
1481 }
1482 };
1483
1484 // Create sub-parser
1485 Parser_ parser(
1486 append(_env_prefix, env_prefix, '_'),
1487 append(_property_prefix, property_path_prefix, '/'),
1488 append(_flag_prefix, flag_prefix, '-'));
1489
1490 // Add sub-parsers parameters to our own
1491 _parameters.insert(_parameters.end(), parser._parameters.begin(), parser._parameters.end());
1492
1493 // Return parser to store it in current parser
1494 return parser;
1495 }
1496
1497 private:
1501
1502 void _collect_env();
1503 void _collect_property_map(const PropertyMap* property_map);
1504 void _collect_args(int argc, const char* const* argv);
1505
1508 {
1509 for(auto& core : _parameters)
1510 {
1511 core->validate(_errors);
1512 }
1513 }
1514
1516 void _derive()
1517 {
1518 for(auto& core : _parameters)
1519 {
1520 core->derive_self();
1521 }
1522 }
1523
1525 void _hide()
1526 {
1527 for(auto& core : _parameters)
1528 {
1529 core->hide();
1530 }
1531 }
1532
1534 void _property_map(PropertyMap& pmap, const std::function<String(const Intern::ParameterCore&)>& extractor);
1535
1537 static void parameter_help(const Intern::ParameterCore& core, std::stringstream& s);
1538
1539 static bool is_flag(const String& s)
1540 {
1541 return !s.empty() && s[0] == '-';
1542 }
1543 };
1544} // namespace FEAT
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
#define XASSERTM(expr, msg)
Assertion macro definition with custom message.
Definition: assertion.hpp:263
Argument parser base class.
static void parameter_help(const Intern::ParameterCore &core, std::stringstream &s)
Write flags, property path, environment variable and help text for given parameter to stringstream.
Definition: arg_parser.cpp:597
void _derive()
Derive parameters from other parameters.
void _hide()
Hide parameters if requested.
Parser_ parser(String env_prefix="", String property_path_prefix="", String flag_prefix="")
Add a sub-parser to this parser.
bool _allow_unknown_cli_flags
If true, unknown CLI flags do not produce errors.
ParameterBuilder< T_ > parameter(T_ &&default_value=T_{})
Add a Parameter to this parser.
void _validate()
Validate parameters after parsing.
String display() const
Produce formatted output of all values in this parser.
Definition: arg_parser.cpp:244
ArgParser(String env_prefix, String property_prefix, String flag_prefix)
Prefix constructor.
bool parse(const String &property_map_path)
Populate this parser.
bool parse(int argc, const char *const *argv, const PropertyMap *property_map=nullptr)
Populate this parser.
Definition: arg_parser.cpp:348
String _flag_prefix
Prefix for long flags. Gets preprended to this parsers long flags.
void allow_unknown_cli_flags(bool allow=true)
Allow parser to ignore unknown CLI flags.
void set_description(String &&description)
Set program description.
void _property_map(PropertyMap &pmap, const std::function< String(const Intern::ParameterCore &)> &extractor)
Create a PropertyMap from all property-parameters using the given extractor.
Definition: arg_parser.cpp:566
void add_values_to_property_map(PropertyMap &pmap)
Adds the values of all property-parameters to the given PropertyMap.
Definition: arg_parser.cpp:412
void add_defaults_to_property_map(PropertyMap &pmap)
Adds the default values of all property-parameters to the given PropertyMap.
Definition: arg_parser.cpp:400
bool _check_for_unique_parameters()
Definition: arg_parser.cpp:424
bool parse(const PropertyMap &property_map)
Populate this parser.
bool bootstrap(int argc, const char *const *argv, PropertyMap &pmap)
Load PropertyMaps based on command line parameters or environment variables.
Definition: arg_parser.cpp:305
String _program
Path to program, i.e. argv[0].
String _env_prefix
Prefix for environment variables. Gets preprended to this parsers environment variables.
String _description
Description of this parser. Displayed in help text.
bool parse(int argc, const char *const *argv, const String &property_map_path)
Populate this parser.
String _property_prefix
Prefix for property map paths. Gets preprended to this parsers property map paths.
String help_text() const
Generate help text for this parser.
Definition: arg_parser.cpp:225
const std::deque< String > & errors() const
Error accessor.
Type-erased core of a Parameter.
Definition: arg_parser.hpp:299
String name() const
Tries to create a user-readable name for this parameter.
Definition: arg_parser.cpp:20
std::pair< std::weak_ptr< ParameterCore >, PredicateType > Need
Type of "A needs B" declaration with condition.
Definition: arg_parser.hpp:313
std::pair< std::weak_ptr< ParameterCore >, PredicateType > HideIf
Type of "Hide A if B" declaration.
Definition: arg_parser.hpp:316
void parse(std::deque< String > &errors)
Parse this parameter.
Definition: arg_parser.cpp:113
std::function< void(std::any &, const std::deque< std::reference_wrapper< std::any > > &)> DeriverType
Type of type-erased deriver function.
Definition: arg_parser.hpp:308
std::function< void(std::ostream &, const std::any &)> PrinterType
Type of type-erased printer function.
Definition: arg_parser.hpp:306
void hide()
Hides other parameters based on this parameters hide_if declarations.
Definition: arg_parser.cpp:192
void derive_self()
Sets this parameters value based on other parameters.
Definition: arg_parser.cpp:168
std::function< void(std::any &, const String &)> ParserType
Type of type-erased parser function.
Definition: arg_parser.hpp:302
std::function< void(const std::any &)> ValidatorType
Type of type-erased validator function.
Definition: arg_parser.hpp:304
ParameterCore(T_ def_value)
Constructor.
Definition: arg_parser.hpp:353
void validate(std::deque< String > &errors) const
Validate this parameter.
Definition: arg_parser.cpp:68
std::function< bool(const std::any &)> PredicateType
Type of type-erased predicate function.
Definition: arg_parser.hpp:310
void reset()
Reset this parameter to default.
Definition: arg_parser.cpp:214
void add_argument(const String &s, int incoming_priority)
Add an argument to this parameter.
Definition: arg_parser.cpp:50
Builder-pattern for defining parameters. See methods for details.
Definition: arg_parser.hpp:486
ParameterBuilder & derives_from(const Parameter< U_ > &param_one, const Parameter< V_ > &param_two, T_(*fn)(const U_ &, const V_ &))
Derive this parameter from two other parameters if it has not been set by the user.
Definition: arg_parser.hpp:953
ParameterBuilder & validator(void(*validator_fn)(const T_ &))
Set a validator for this paramater.
Definition: arg_parser.hpp:704
ParameterBuilder & bootstrap()
Mark this parameter as a bootstrap parameter.
Definition: arg_parser.hpp:888
ParameterBuilder & validator(bool(*validator_fn)(const T_ &))
Set a validator for this paramater.
Definition: arg_parser.hpp:741
ParameterBuilder & property(String &&s)
Set the property map path for a parameter.
Definition: arg_parser.hpp:586
ParameterBuilder & required()
Mark this parameter as required.
Definition: arg_parser.hpp:772
ParameterBuilder & needs(const Parameter< U_ > &parameter)
Mark another parameter as needed by this one.
Definition: arg_parser.hpp:799
ParameterBuilder & short_flag(String &&s)
Set the short flag for a parameter.
Definition: arg_parser.hpp:512
ParameterBuilder & name(String &&s)
Set a name for this parameter.
Definition: arg_parser.hpp:658
ParameterBuilder & long_flag(String s)
Set the long flag for a parameter.
Definition: arg_parser.hpp:534
ParameterBuilder & env(const String &s)
Set the environment variable for a parameter.
Definition: arg_parser.hpp:562
ParameterBuilder & derives_from(const Parameter< U_ > &param_one, const Parameter< V_ > &param_two, const Parameter< W_ > &param_three, T_(*fn)(const U_ &, const V_ &, const W_ &))
Derive this parameter from three other parameters if it has not been set by the user.
Definition: arg_parser.hpp:992
ParameterBuilder & placeholder(String &&s)
Set a placeholder text for the argument of this parameter.
Definition: arg_parser.hpp:642
ParameterBuilder & needs_if(const Parameter< U_ > &parameter, bool(*condition)(const T_ &))
Conditionally mark another parameter as needed by this one.
Definition: arg_parser.hpp:830
ParameterBuilder & derives_from(const Parameter< U_ > &param, T_(*fn)(const U_ &))
Derive this parameter from another parameter if it has not been set by the user.
Definition: arg_parser.hpp:908
ParameterBuilder & parser(T_(*parser_fn)(const String &))
Set a custom parser for this parameter.
Definition: arg_parser.hpp:676
ParameterBuilder & derives_from(const Parameter< U_ > &param_one, const Parameter< V_ > &param_two, const Parameter< W_ > &param_three, Fn_ &&fn)
ArgParser::derive_from wrapper for casting lambdas to function pointers.
ParameterBuilder & help_string(String &&s)
Set help string for this parameter.
Definition: arg_parser.hpp:617
ParameterBuilder & derives_from(const Parameter< U_ > &param, Fn_ &&fn)
ArgParser::derive_from wrapper for casting lambdas to function pointers.
Definition: arg_parser.hpp:934
ParameterBuilder & derives_from(const Parameter< U_ > &param_one, const Parameter< V_ > &param_two, Fn_ &&fn)
ArgParser::derive_from wrapper for casting lambdas to function pointers.
Definition: arg_parser.hpp:972
ParameterBuilder & hide_if(const Parameter< U_ > &parameter, bool(*condition)(const T_ &))
Conditionally mark another parameter as hidden.
Definition: arg_parser.hpp:861
Parameter of an ArgParser.
Definition: arg_parser.hpp:429
bool set_by_user() const
Check if argument was set by user.
Definition: arg_parser.hpp:450
const T_ * operator->() const
Accessor for parameter value.
Definition: arg_parser.hpp:474
const T_ & operator*() const
Accessor for parameter value.
Definition: arg_parser.hpp:465
const T_ & value() const
Accessor for parameter value.
Definition: arg_parser.hpp:456
A class organizing a tree of key-value pairs.
void read(String filename, bool replace=true)
Parses a file in INI-format.
String class implementation.
Definition: string.hpp:47
std::deque< String > split_by_whitespaces() const
Splits the string by white-spaces.
Definition: string.hpp:519
bool starts_with(const String &head) const
Checks whether this string starts with another string.
Definition: string.hpp:732
FEAT namespace.
Definition: adjactor.hpp:12
@ value
specifies whether the space should supply basis function values
std::uint64_t Index
Index data type.
Check if type has an operator>> implementation, i.e. can be parsed by String::parse.
Definition: arg_parser.hpp:93
Check if type is some instantiation of std::deque.
Definition: arg_parser.hpp:61
Check if type is some instantiation of std::map.
Definition: arg_parser.hpp:77