FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
arg_parser.cpp
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#include <kernel/util/arg_parser.hpp>
7
8#include <numeric>
9#include <sstream>
10#include <set>
11
12namespace FEAT::Intern
13{
21 {
22 if(!custom_name.empty())
23 {
24 return custom_name;
25 }
26 if(!long_flag.empty())
27 {
28 return long_flag.substr(2);
29 }
30
31 if(!short_flag.empty())
32 {
33 return short_flag.substr(1);
34 }
35
36 if(!property_path.empty())
37 {
38 return property_path;
39 }
40
41 if(!environment_variable.empty())
42 {
43 return environment_variable;
44 }
45
46 return "<anonymous>";
47 }
48
50 void ParameterCore::add_argument(const String& s, int incoming_priority)
51 {
52 if(priority < incoming_priority)
53 {
54 // New argument is of higher priority than all previous arguments
55 // Clear the list and set new priority
56 arguments.clear();
57 arguments.push_back(s.trim());
58 priority = incoming_priority;
59 }
60 else if(priority == incoming_priority)
61 {
62 // New argument is of same priority
63 // Store it for now
64 arguments.push_back(s.trim());
65 }
66 }
67
68 void ParameterCore::validate(std::deque<String>& errors) const
69 {
70 if(required && !set_by_user)
71 {
72 errors.push_back("Error: Parameter " + name() + " not given, but is required!");
73 return;
74 }
75
76 if(validator)
77 {
78 try
79 {
80 validator(value);
81 }
82 catch(std::bad_any_cast& e)
83 {
84 XABORTM(e.what());
85 }
86 catch(std::invalid_argument& e)
87 {
88 errors.push_back("Error: Validation of parameter " + name() + " failed with message: " + e.what());
89 }
90 }
91
92 for(const auto& [core, condition] : needs)
93 {
94 if(core.expired())
95 {
96 XABORTM("Expired weak ptr to parameter core of " + name());
97 }
98
99 auto ptr = core.lock();
100
101 if(set_by_user && condition(value))
102 {
103 if(!ptr->set_by_user)
104 {
105 errors.push_back(
106 "Error: Parameter " + name() + " needs parameter " + ptr->name() + ", but parameter " + ptr->name() +
107 " was not set by user");
108 }
109 }
110 }
111 }
112
113 void ParameterCore::parse(std::deque<String>& errors)
114 {
115 if(arguments.empty())
116 {
117 // Nothing to parse
118 return;
119 }
120
121 set_by_user = true;
122
123 // Merge arguments of collection options
124 // NOTE: This is slightly inefficient, because
125 // the collection parser is just going to split the string
126 // by whitespace anyway. But CLI arguments come pre-split
127 // and this way we can handle all argument sources with the same parser
128 if(type == ParameterType::collection_option)
129 {
130 String merged = std::accumulate(
131 arguments.begin(),
132 arguments.end(),
133 String(""),
134 [](const String& a, const String& b) { return a + " " + b; });
135
136 // Replace arguments with merged version
137 arguments.clear();
138 arguments.push_back(merged.trim());
139 }
140
141 if(arguments.size() > 1)
142 {
143 errors.push_back("Error: Parameter " + name() + " was set multiple times. Only the first value is considered!");
144 }
145
146 if(!parser)
147 {
148 errors.push_back(
149 "Error: No parser for parameter " + name() +
150 ". Ensure operator>> is available for your type or set a custom parser!");
151 return;
152 }
153
154 try
155 {
156 parser(value, arguments.front());
157 }
158 catch(std::bad_any_cast& e)
159 {
160 XABORTM(e.what());
161 }
162 catch(std::invalid_argument& e)
163 {
164 errors.push_back("Error: Parsing for parameter " + name() + " failed with message: " + e.what());
165 }
166 }
167
169 {
170 if(!set_by_user && deriver)
171 {
172 // Build deque of values
173 std::deque<std::reference_wrapper<std::any>> args;
174
175 for(const auto& core : derives_from)
176 {
177 if(core.expired())
178 {
179 XABORTM("Expired weak ptr to parameter core of " + name());
180 }
181
182 auto ptr = core.lock();
183
184 args.emplace_back(ptr->value);
185 }
186
187 // Call deriver
188 deriver(value, args);
189 }
190 }
191
193 {
194 for(auto& [core, condition] : hide_if)
195 {
196 if(condition(value))
197 {
198 if(core.expired())
199 {
200 XABORTM("Expired weak ptr to parameter core of " + name());
201 }
202
203 auto ptr = core.lock();
204
205 if(condition(value))
206 {
207 ptr->hidden = true;
208 }
209 }
210 }
211 }
212
215 {
216 value = default_value;
217 priority = 0;
218 arguments.clear();
219 set_by_user = false;
220 }
221} // namespace FEAT::Intern
222
223namespace FEAT
224{
225 [[nodiscard]] String ArgParser::help_text() const
226 {
227 std::stringstream stream;
228
229 if(!_description.empty())
230 {
231 stream << _description << "\n\n";
232 }
233 stream << "Usage: " << _program << " [OPTIONS]\n\n";
234 stream << "Options:\n";
235
236 for(const auto& core : _parameters)
237 {
238 parameter_help(*core, stream);
239 }
240
241 return stream.str();
242 }
243
244 [[nodiscard]] String ArgParser::display() const
245 {
246 std::stringstream stream;
247
248 // Name padding is size of longest parameter name plus 3 chars for aesthetics
249 String::size_type name_padding(0);
250 for(const auto& core : _parameters)
251 {
252 name_padding = std::max(name_padding, core->name().size());
253 }
254 name_padding += 3;
255
256 const String::size_type source_padding(10);
257 const String::size_type header_width(75);
258
259 // Print header
260 stream << String("Parameter").pad_back(name_padding, ' ');
261 stream << "|";
262 stream << String("Source").pad_back(source_padding, ' ');
263 stream << "|";
264 stream << "Value\n";
265 stream << String("").pad_back(header_width, '-') << "\n";
266
267 for(const auto& core : _parameters)
268 {
269 // Skip hidden parameters
270 if(core->hidden)
271 {
272 continue;
273 }
274
275 XASSERT(core->value.has_value());
276
277 stream << core->name().pad_back(name_padding, '.');
278 stream << "|";
279
280 switch(core->priority)
281 {
282 case priority_default: stream << "default |"; break;
283 case priority_env: stream << "env |"; break;
284 case priority_property: stream << "property |"; break;
285 case priority_cli: stream << "cli |"; break;
286 default: stream << " |";
287 }
288
289 if(core->type == Intern::ParameterType::flag)
290 {
291 stream << (std::any_cast<const bool&>(core->value) ? "true" : "false");
292 }
293 else
294 {
295 XASSERT(bool(core->printer));
296 core->printer(stream, core->value);
297 }
298
299 stream << "\n";
300 }
301
302 return stream.str();
303 }
304
305 [[nodiscard]] bool ArgParser::bootstrap(int argc, const char* const* argv, PropertyMap& pmap)
306 {
307 // Reset errors
308 _errors.clear();
309
310 // Set default values, reset priorities, clear arguments
311 for(auto& core : _parameters)
312 {
313 core->reset();
314 }
315
316 // Collect values in environment variables
317 _collect_env();
318
319 // Collect command line args
320 _collect_args(argc, argv);
321
322 // Parse bootstrap parameters and load property maps
323 PropertyMap result;
324 for(auto& core : _parameters)
325 {
326 if(core->bootstrap)
327 {
328 core->parse(_errors);
329 // SAFETY: Cast to std::deque<String> is ok, because only Parameter<std::deque<String>> may be marked as bootstrap
330 for(const String& path : std::any_cast<std::deque<String>>(core->value))
331 {
332 PropertyMap tmp_map;
333 tmp_map.read(path);
334 pmap.merge(tmp_map, true);
335 }
336 }
337 }
338
339 // Reset again, to discourage users from using this as an alternative to the parse function
340 for(auto& core : _parameters)
341 {
342 core->reset();
343 }
344
345 return _errors.empty();
346 }
347
348 [[nodiscard]] bool ArgParser::parse(int argc, const char* const* argv, const PropertyMap* property_map)
349 {
350 // Reset errors
351 _errors.clear();
352
354 {
355 return false;
356 }
357
358 // Set default values, reset priorities, clear arguments
359 for(auto& core : _parameters)
360 {
361 core->reset();
362 }
363
364 // Collect values in environment variables
365 _collect_env();
366
367 // Collect values in property map
368 if(property_map != nullptr)
369 {
370 _collect_property_map(property_map);
371 }
372
373 // Collect command line args
374 _collect_args(argc, argv);
375
376 // Parse collected data types into proper data types
377 for(auto& core : _parameters)
378 {
379 core->parse(_errors);
380 }
381
382 // Run validators
383 _validate();
384
385 // Derive values
386 _derive();
387
388 // Hide parameters
389 _hide();
390
391 // Sort parameters alphabetically for help and display output
392 std::sort(
393 _parameters.begin(),
394 _parameters.end(),
395 [](auto& a, auto& b) { return a->name().compare_no_case(b->name()) < 0; });
396
397 return _errors.empty();
398 }
399
401 {
403 pmap,
404 [](const Intern::ParameterCore& core)
405 {
406 std::stringstream ss;
407 core.printer(ss, core.default_value);
408 return ss.str();
409 });
410 }
411
413 {
415 pmap,
416 [](const Intern::ParameterCore& core)
417 {
418 std::stringstream ss;
419 core.printer(ss, core.value);
420 return ss.str();
421 });
422 }
423
425 {
426 std::set<String> short_flags;
427 std::set<String> long_flags;
428 std::set<String> environment_variables;
429 std::set<String> property_paths;
430
431 bool result = true;
432
433 auto handle_flag = [&](std::set<String>& set, const String& s)
434 {
435 if(s.empty())
436 {
437 return;
438 }
439
440 if(set.find(s) != set.end())
441 {
442 _errors.push_back("Error: Flag " + s + " is used by multiple parameters");
443 result = false;
444 }
445 else
446 {
447 set.insert(s);
448 }
449 };
450
451 for(auto& core : _parameters)
452 {
453 handle_flag(short_flags, core->short_flag);
454 handle_flag(long_flags, core->long_flag);
455 handle_flag(environment_variables, core->environment_variable);
456 handle_flag(property_paths, core->property_path);
457 }
458
459 return result;
460 }
461
462 void ArgParser::_collect_env()
463 {
464 for(auto& core : _parameters)
465 {
466 const char* value = std::getenv(core->environment_variable.c_str());
467 if(value != nullptr)
468 {
469 String s(value);
470 core->add_argument(s, priority_env);
471 }
472 }
473 }
474
475 void ArgParser::_collect_property_map(const PropertyMap* property_map)
476 {
477 for(auto& core : _parameters)
478 {
479 auto [string, success] = property_map->query(core->property_path);
480 if(success)
481 {
482 core->add_argument(string, priority_property);
483 }
484 }
485 }
486
487 void ArgParser::_collect_args(int argc, const char* const* argv)
488 {
489 if(argc == 0)
490 {
491 return;
492 }
493
494 _program = String(argv[0]);
495
496 std::deque<String> args;
497
498 for(int i(1); i < argc; i++)
499 {
500 args.emplace_back(argv[i]);
501 }
502
503 Index idx(0);
504 while(idx < args.size())
505 {
506 const String& flag = args[idx++];
507
508 if(!is_flag(flag))
509 {
510 XABORTM("Error: Expected flag in position " + stringify(idx));
511 }
512
513 bool handled = false;
514 for(auto& core : _parameters)
515 {
516 if(flag.compare_no_case(core->short_flag) != 0 && flag.compare_no_case(core->long_flag) != 0)
517 {
518 continue;
519 }
520
521 handled = true;
522
523 if(core->type == Intern::ParameterType::flag)
524 {
525 if(std::any_cast<const bool&>(core->default_value))
526 {
527 core->add_argument("false", priority_cli);
528 }
529 else
530 {
531 core->add_argument("true", priority_cli);
532 }
533 }
534 else if(core->type == Intern::ParameterType::option)
535 {
536 // Normal option. Consume a single argument
537 core->add_argument(args[idx++], priority_cli);
538 }
539 else if(core->type == Intern::ParameterType::collection_option)
540 {
541 // Collect arguments until next flag
542 while(idx < args.size() && !is_flag(args[idx]))
543 {
544 core->add_argument(args[idx++], priority_cli);
545 }
546 }
547 }
548
549 if(!handled)
550 {
552 {
553 // We found no parameter for this flag. Generate error
554 _errors.push_back("Error: Unknown flag " + flag);
555 }
556
557 // Then advance to next flag
558 while(idx < args.size() && !is_flag(args[idx]))
559 {
560 idx++;
561 }
562 }
563 }
564 }
565
566 void ArgParser::_property_map(PropertyMap& pmap, const std::function<String(const Intern::ParameterCore&)>& extractor)
567 {
568 for(auto& core : _parameters)
569 {
570 if(core->property_path.empty())
571 {
572 // Not a property-parameter. Skip it.
573 continue;
574 }
575
576 const auto path_components = core->property_path.split_by_charset("/");
577 PropertyMap* section = &pmap;
578 // Iterate over sections. Last entry of path_components is entry.
579 for(Index i(0); i < path_components.size() - 1; i++)
580 {
581 PropertyMap* subsection = section->get_sub_section(path_components[i]);
582 if(subsection == nullptr)
583 {
584 section = section->add_section(path_components[i]);
585 }
586 else
587 {
588 section = subsection;
589 }
590 }
591
592 // Write entry
593 section->add_entry(path_components.back(), extractor(*core));
594 }
595 }
596
597 void ArgParser::parameter_help(const Intern::ParameterCore& core, std::stringstream& s)
598 {
599 if(
600 core.short_flag.empty() && core.long_flag.empty() && core.property_path.empty() &&
601 core.environment_variable.empty())
602 {
603 return;
604 }
605
606 s << "\t";
607
608 auto format_flag = [&s](Intern::ParameterType type, const String& flag, const String& placeholder)
609 {
610 if(type == Intern::ParameterType::flag)
611 {
612 s << flag;
613 }
614 if(type == Intern::ParameterType::option)
615 {
616 s << flag << " <" << placeholder << ">";
617 }
618 if(type == Intern::ParameterType::collection_option)
619 {
620 s << flag << " <" << placeholder << "s...>";
621 }
622 };
623
624 auto format_other = [&s](const std::string_view prefix, const String& value)
625 { s << "[" << prefix << ":" << value << "]"; };
626
627 // -a, --arg, [property:arg], [env:FEAT_ARG]
628
629 bool has_prev = false;
630 if(!core.short_flag.empty())
631 {
632 format_flag(core.type, core.short_flag, core.placeholder);
633 has_prev = true;
634 }
635
636 if(!core.long_flag.empty())
637 {
638 if(has_prev)
639 {
640 s << ", ";
641 }
642
643 format_flag(core.type, core.long_flag, core.placeholder);
644
645 has_prev = true;
646 }
647
648 if(!core.property_path.empty())
649 {
650 if(has_prev)
651 {
652 s << ", ";
653 }
654
655 format_other("property", core.property_path);
656
657 has_prev = true;
658 }
659
660 if(!core.environment_variable.empty())
661 {
662 if(has_prev)
663 {
664 s << ", ";
665 }
666
667 format_other("env", core.environment_variable);
668
669 has_prev = true;
670 }
671
672 if(has_prev)
673 {
674 s << "\n";
675 }
676
677 if(core.required)
678 {
679 s << "\t\tRequired argument.\n";
680 }
681
682 for(const String& line : core.help_string.split_by_charset("\n"))
683 {
684 s << "\t\t" << line.trim() << "\n";
685 }
686
687 s << "\n";
688 }
689} // namespace FEAT
#define XABORTM(msg)
Abortion macro definition with custom message.
Definition: assertion.hpp:192
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
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.
bool _allow_unknown_cli_flags
If true, unknown CLI flags do not produce errors.
void _validate()
Validate parameters after parsing.
String display() const
Produce formatted output of all values in this parser.
Definition: arg_parser.cpp:244
bool parse(int argc, const char *const *argv, const PropertyMap *property_map=nullptr)
Populate this parser.
Definition: arg_parser.cpp:348
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 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 _description
Description of this parser. Displayed in help text.
String help_text() const
Generate help text for this parser.
Definition: arg_parser.cpp:225
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
void parse(std::deque< String > &errors)
Parse this parameter.
Definition: arg_parser.cpp:113
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
void validate(std::deque< String > &errors) const
Validate this parameter.
Definition: arg_parser.cpp:68
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
A class organizing a tree of key-value pairs.
PropertyMap * add_section(String name)
Adds a new sub-section to this map.
PropertyMap * get_sub_section(String name)
Retrieves a sub-section by its name.
bool add_entry(String key, String value, bool replace=true)
Adds a new key-value pair to this map.
void merge(const PropertyMap &section, bool replace=true)
Merges another PropertyMap into this.
void read(String filename, bool replace=true)
Parses a file in INI-format.
String class implementation.
Definition: string.hpp:47
String pad_back(size_type len, char c=' ') const
Pads the back of the string up to a desired length.
Definition: string.hpp:416
std::deque< String > split_by_charset(const String &charset) const
Splits the string by a delimiter charset.
Definition: string.hpp:468
String trim(const String &charset) const
Trims the string.
Definition: string.hpp:328
@ success
solving successful (convergence criterion fulfilled)
FEAT namespace.
Definition: adjactor.hpp:12
String stringify(const T_ &item)
Converts an item into a String.
Definition: string.hpp:993
@ value
specifies whether the space should supply basis function values
std::uint64_t Index
Index data type.