FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
FEAT::ArgParser Class Reference

Argument parser base class. More...

#include <arg_parser.hpp>

Public Member Functions

 ArgParser (String env_prefix, String property_prefix, String flag_prefix)
 Prefix constructor. More...
 
void add_defaults_to_property_map (PropertyMap &pmap)
 Adds the default values of all property-parameters to the given PropertyMap. More...
 
void add_values_to_property_map (PropertyMap &pmap)
 Adds the values of all property-parameters to the given PropertyMap. More...
 
void allow_unknown_cli_flags (bool allow=true)
 Allow parser to ignore unknown CLI flags. More...
 
bool bootstrap (int argc, const char *const *argv, PropertyMap &pmap)
 Load PropertyMaps based on command line parameters or environment variables. More...
 
String display () const
 Produce formatted output of all values in this parser. More...
 
const std::deque< String > & errors () const
 Error accessor. More...
 
String help_text () const
 Generate help text for this parser. More...
 
bool parse (const PropertyMap &property_map)
 Populate this parser. More...
 
bool parse (const String &property_map_path)
 Populate this parser. More...
 
bool parse (int argc, const char *const *argv, const PropertyMap *property_map=nullptr)
 Populate this parser. More...
 
bool parse (int argc, const char *const *argv, const String &property_map_path)
 Populate this parser. More...
 
void set_description (String &&description)
 Set program description. More...
 

Protected Member Functions

template<typename T_ >
ParameterBuilder< T_ > parameter (T_ &&default_value=T_{})
 Add a Parameter to this parser. More...
 
template<typename Parser_ >
Parser_ parser (String env_prefix="", String property_path_prefix="", String flag_prefix="")
 Add a sub-parser to this parser. More...
 

Private Member Functions

bool _check_for_unique_parameters ()
 
void _collect_args (int argc, const char *const *argv)
 
void _collect_env ()
 
void _collect_property_map (const PropertyMap *property_map)
 
void _derive ()
 Derive parameters from other parameters. More...
 
void _hide ()
 Hide parameters if requested. More...
 
void _property_map (PropertyMap &pmap, const std::function< String(const Intern::ParameterCore &)> &extractor)
 Create a PropertyMap from all property-parameters using the given extractor. More...
 
void _validate ()
 Validate parameters after parsing. More...
 

Static Private Member Functions

static bool is_flag (const String &s)
 
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. More...
 

Private Attributes

bool _allow_unknown_cli_flags = false
 If true, unknown CLI flags do not produce errors. More...
 
String _description {""}
 Description of this parser. Displayed in help text. More...
 
String _env_prefix {""}
 Prefix for environment variables. Gets preprended to this parsers environment variables. More...
 
std::deque< String > _errors
 
String _flag_prefix {""}
 Prefix for long flags. Gets preprended to this parsers long flags. More...
 
std::deque< std::shared_ptr< Intern::ParameterCore > > _parameters
 
String _program {""}
 Path to program, i.e. argv[0]. More...
 
String _property_prefix {""}
 Prefix for property map paths. Gets preprended to this parsers property map paths. More...
 

Static Private Attributes

static constexpr int priority_cli = 3
 
static constexpr int priority_default = 0
 
static constexpr int priority_env = 1
 
static constexpr int priority_property = 2
 

Detailed Description

Argument parser base class.

This class aims to be a more convenient alternative to the SimpleArgParser. It allows defining fully integrated argument parsers that can:

  • parse arguments from the command line, property maps, and environment variables
  • store parsed arguments directly into a convenient struct
  • generate a help text
  • handle required and optional parameters
  • handle custom parsing
  • handle validation of arguments
  • model dependencies between parameters.

Example

// Define parser
struct ExampleParser : public ArgParser
{
Parameter<String> mesh_path = parameter(String("mesh.xml")).short_flag("-m").long_flag("--mesh").required();
Parameter<bool> write_vtk = parameter(false).long_flag("--vtk");
Parameter<String> output_file = parameter(String("output.vtu")).long_flag("--output-file").needs(write_vtk);
Parameter<std::uint32_t> max_iters = parameter(std::uint32_t(0)).long_flag("--max-iters").property("max-iters");
Parameter<String> solver = parameter(String("Umfpack"))
.long_flag("--solver")
.property("solver")
.validator([](const auto& s) { return s == "Umfpack" || s == "CG"; })
.needs_if(max_iters, [](const auto& s) { return s == "CG"; });
}
// Use like this
ExampleParser args;
bool success = args.parse(argc, argv, property_map);
if(!success)
{
for(const String& error : parser.errors())
{
std::cout << error << "\n";
}
}
if(*args.write_vtk)
{
// Export VTK
}
Argument parser base class.
Parser_ parser(String env_prefix="", String property_path_prefix="", String flag_prefix="")
Add a sub-parser to this parser.
Parameter of an ArgParser.
Definition: arg_parser.hpp:429
static void abort(bool dump_call_stack=true)
FEAT abortion.
Definition: runtime.cpp:431
String class implementation.
Definition: string.hpp:47
@ success
solving successful (convergence criterion fulfilled)

Creating a parser

You create a parser by defining a class or struct that inherits from this base class. Inheriting from this class makes a protected method ArgParser::parameter available to you that allows you to define Parameters via a ParameterBuilder. See the various methods of the ParameterBuilder for details on the different settings you can use to define your parser.

Using a parser

After you have defined your parser, you can use it by simply creating an instance of it and calling the parse method. The parse method returns a boolean indicating whether the parameter parsing was successful. If parsing was unsuccessful the parser will contain a list of errors that occured during parsing. Note that for a better user experience the parser is optimistic and will try to produce as many errors as possible rather than quitting after the first warning.

After successfull parsing you can access the parsed values via the Parameter::value() method or the overloads of operator* and operator-> on the Parameter class.

The parser supports being reused. If you call parse again with different parameters, then the parsed result will be identical to calling parse on a fresh parser.

Parsing priority

The parser considers, if provided, command line arguments, property map entries, environment variables, and the supplied default values of parameters. During parsing the priority for sources is as follows:

Default Values < environment variables < property maps < command line arguments

Roughly, the more explicit and interactive the method, to higher the prioritiy. This means that setting a parameter via the command line will overide a value for that parameter set in a property map.

Allowed types

The ArgParser supports all types that can be parsed via the String::parse method. To add support for your own custom type, either supply an operator>> overload for your type, which will be used by String::parse or supply a custom parser in the parameter definition.

Boolean parameters are handled specially. Environment variables and properties are parsed as normal, but setting the command line flag sets the parameters value to the inverse of the default value. This allows you to define "--no-foo" flags that are on by default and get turned off by setting the flag.

If a type T can be parsed, then the Parser also supports Parameters of type std::deque<T>. These parameters are parsed by either splitting the value of a environment variable or property map index at whitespace and parsing each value individually, or by parsing all following command line arguments until the next flag occurs.

If types K and V can be parsed, then the parser also supports Parameters of type std::map<K, V>. These parameters are parsed similarly to std::deques, except that pairs of arguments are treated as key-value pairs for the std::map.

Help Text

You can create a help text with a list of all parameters with their flags, property map paths, and environment variables via the ArgParser::help method. The ParameterBuilder provides various settings to customize this help text for each parameter.

Display Text

You can create a table containing the values of all parameters and their respective sources via the ArgParser::display method.

Errors

In the interest of correctness the parser treats most unexpected things as errors. This includes:

  • unused command line arguments
  • failed calls to String::parse
  • unset required parameters
  • failed validators
  • unfulfilled dependencies between parameters

Composing parsers

You might have a parser A with several parameters and want to create a parser B with the same parameters as A, plus some additional ones. There are two mechanisms for composing parsers like that. Inheritance and sub-parsers.

Inheritance allows you to compose parser in a "flat" manner. You can have parser B inherit from A, then B will naturally have all the same parameters as A, plus any additional ones you define in the class definition of B. All these parameters will be available as members of B.

Sub-parsers allow you to compose parsers in a tree-like manner. You can add A as a sub-parser of B via the ArgParser::parser member function, similar to defining a parameter:

class B : public ArgParser
{
A a = parser<A>();
//... additional parameters
}

A will automatically participate in the parsing of B, including tracking of required parameters, dependencies between parameters, etc. No further action by the user is required. You can access the parameters of A via the member a of parser B, just like you would expect.

The ArgParser::parser member function also allows you to set prefixes for a parsers environment variables, property maps paths, and flags. For example, assume that parser A has a parameter with a long flag of "--foo". If we define a parser C via:

class C : public ArgParser
{
A a = parser<A>("A", "a", "a");
//... additional parameters
}

The the parameter associated with the "--foo" flag of A will be treated as being defined with the flag "--a-foo". You can set separate prefixes for environment variables, property map paths, and long flags.

This prefix mechanism is especially useful when dealing with PropertyMaps. It allows you to define a parser for each expected subsection of the PropertyMap in isolation and then compose those parsers, setting the subsection name as prefix for each parser.

Definition at line 1228 of file arg_parser.hpp.

Constructor & Destructor Documentation

◆ ArgParser()

FEAT::ArgParser::ArgParser ( String  env_prefix,
String  property_prefix,
String  flag_prefix 
)
inline

Prefix constructor.

Definition at line 1258 of file arg_parser.hpp.

Member Function Documentation

◆ _check_for_unique_parameters()

bool FEAT::ArgParser::_check_for_unique_parameters ( )
private

Search for short flags, long flags, environment variables, or property paths that get used by multiple parameters

Definition at line 424 of file arg_parser.cpp.

Referenced by parse().

◆ _collect_args()

void FEAT::ArgParser::_collect_args ( int  argc,
const char *const *  argv 
)
private

Definition at line 487 of file arg_parser.cpp.

◆ _collect_env()

void FEAT::ArgParser::_collect_env ( )
private

Definition at line 462 of file arg_parser.cpp.

◆ _collect_property_map()

void FEAT::ArgParser::_collect_property_map ( const PropertyMap *  property_map)
private

Definition at line 475 of file arg_parser.cpp.

◆ _derive()

void FEAT::ArgParser::_derive ( )
inlineprivate

Derive parameters from other parameters.

Definition at line 1516 of file arg_parser.hpp.

Referenced by parse().

◆ _hide()

void FEAT::ArgParser::_hide ( )
inlineprivate

Hide parameters if requested.

Definition at line 1525 of file arg_parser.hpp.

Referenced by parse().

◆ _property_map()

void FEAT::ArgParser::_property_map ( PropertyMap &  pmap,
const std::function< String(const Intern::ParameterCore &)> &  extractor 
)
private

Create a PropertyMap from all property-parameters using the given extractor.

Definition at line 566 of file arg_parser.cpp.

References FEAT::PropertyMap::add_entry(), FEAT::PropertyMap::add_section(), and FEAT::PropertyMap::get_sub_section().

Referenced by add_defaults_to_property_map(), and add_values_to_property_map().

◆ _validate()

void FEAT::ArgParser::_validate ( )
inlineprivate

Validate parameters after parsing.

Definition at line 1507 of file arg_parser.hpp.

Referenced by parse().

◆ add_defaults_to_property_map()

void FEAT::ArgParser::add_defaults_to_property_map ( PropertyMap &  pmap)

Adds the default values of all property-parameters to the given PropertyMap.

Parameters
[in,out]pmapPropertyMap to fill

This functions adds an entry to the given PropertyMap for each parameter with an associated PropertyMap path. Each added entry contains that parameters default value.

Definition at line 400 of file arg_parser.cpp.

References _property_map().

◆ add_values_to_property_map()

void FEAT::ArgParser::add_values_to_property_map ( PropertyMap &  pmap)

Adds the values of all property-parameters to the given PropertyMap.

Parameters
[in,out]pmapPropertyMap to fill

This functions adds an entry to the given PropertyMap for each parameter with an associated PropertyMap path. Each added entry contains that parameters parsed value.

Definition at line 412 of file arg_parser.cpp.

References _property_map().

◆ allow_unknown_cli_flags()

void FEAT::ArgParser::allow_unknown_cli_flags ( bool  allow = true)
inline

Allow parser to ignore unknown CLI flags.

The default behavior is to generate an error upon encountering a CLI flag for which no parameter exists and declare the parse as failed. If this option is set, then unknown flags will instead be silently ignored.

Warning
Erroring upon encountering an unknown flag is mean to protect the user from errors due to misspelling a flag. Use this option with care.

Definition at line 1276 of file arg_parser.hpp.

References _allow_unknown_cli_flags.

◆ bootstrap()

bool FEAT::ArgParser::bootstrap ( int  argc,
const char *const *  argv,
PropertyMap &  pmap 
)

Load PropertyMaps based on command line parameters or environment variables.

Parameters
[in,out]pmapProperty map to merge additional property maps into.

This method parses parameters marked as bootstrap parameters to load an initial set of PropertyMaps for a full parse. Loaded property maps are merged into the given PropertyMap. Entries are replaced by later maps.

Errors that occur during the scanning of command line arguments and during the parsing of bootstrap parameters are recorded. No further validation is done.

Note
No parsing results are recorded into any parameters, including the bootstrap parameters. Run ArgParser::parse() after bootstrapping your PropertyMap to do the actual parsing.

Definition at line 305 of file arg_parser.cpp.

References FEAT::PropertyMap::merge(), and FEAT::PropertyMap::read().

◆ display()

String FEAT::ArgParser::display ( ) const

Produce formatted output of all values in this parser.

Returns
A string containing the values of all parameters
Note
This function shows the arguments given by the user. Parser might change these values however they like.

Definition at line 244 of file arg_parser.cpp.

References FEAT::String::pad_back(), and XASSERT.

◆ errors()

const std::deque< String > & FEAT::ArgParser::errors ( ) const
inline

Error accessor.

Definition at line 1282 of file arg_parser.hpp.

◆ help_text()

String FEAT::ArgParser::help_text ( ) const

Generate help text for this parser.

Returns
A string containing the help text for this parser

The help text gives information about all parameters supported by this parser

Definition at line 225 of file arg_parser.cpp.

References _description, _program, and parameter_help().

◆ is_flag()

static bool FEAT::ArgParser::is_flag ( const String &  s)
inlinestaticprivate

Definition at line 1539 of file arg_parser.hpp.

◆ parameter()

template<typename T_ >
ParameterBuilder< T_ > FEAT::ArgParser::parameter ( T_ &&  default_value = T_{})
inlineprotected

Add a Parameter to this parser.

Parameters
[in]default_valueDefault value for this parameter
Returns
A ParameterBuilder for the new Parameter

Definition at line 1423 of file arg_parser.hpp.

◆ parameter_help()

void FEAT::ArgParser::parameter_help ( const Intern::ParameterCore &  core,
std::stringstream &  s 
)
staticprivate

Write flags, property path, environment variable and help text for given parameter to stringstream.

Definition at line 597 of file arg_parser.cpp.

References FEAT::String::split_by_charset(), and FEAT::value.

Referenced by help_text().

◆ parse() [1/4]

bool FEAT::ArgParser::parse ( const PropertyMap &  property_map)
inline

Populate this parser.

Parameters
[in]property_mapReference to property map root

Collect all parameters from the environment and given property map.

Definition at line 1357 of file arg_parser.hpp.

References parse().

◆ parse() [2/4]

bool FEAT::ArgParser::parse ( const String &  property_map_path)
inline

Populate this parser.

Parameters
[in]property_map_pathPath to file containing property map

Collect all parameters from the environment and given property map.

Definition at line 1387 of file arg_parser.hpp.

References parse(), and FEAT::PropertyMap::read().

◆ parse() [3/4]

bool FEAT::ArgParser::parse ( int  argc,
const char *const *  argv,
const PropertyMap *  property_map = nullptr 
)

Populate this parser.

Parameters
[in]argcNumber of command line arguments, as passed to main
[in]argvCommand line arguments
[in]property_mapPointer to property map root

Collect all parameters from the given sources, parse values, validate parser. Note that the parser expects the first command line parameter to be the path to the program binary, as is usual.

Definition at line 348 of file arg_parser.cpp.

References _check_for_unique_parameters(), _derive(), _hide(), and _validate().

Referenced by parse().

◆ parse() [4/4]

bool FEAT::ArgParser::parse ( int  argc,
const char *const *  argv,
const String &  property_map_path 
)
inline

Populate this parser.

Parameters
[in]argcNumber of command line arguments, as passed to main
[in]argvCommand line arguments
[in]property_map_pathPath to file containing property map

Collect all parameters from the given sources, parse values, validate parser. Note that the parser expects the first command line parameter to be the path to the program binary, as is usual.

Definition at line 1373 of file arg_parser.hpp.

References parse(), and FEAT::PropertyMap::read().

◆ parser()

template<typename Parser_ >
Parser_ FEAT::ArgParser::parser ( String  env_prefix = "",
String  property_path_prefix = "",
String  flag_prefix = "" 
)
inlineprotected

Add a sub-parser to this parser.

Parameters
[in]env_prefixAll environment variables of the sub-parser will be prefixed with this string, separated by an underscore.
[in]property_path_prefixAll PropertyMap paths of the sub-parser will be prefixed with this string, separated by a slash.
[in]flag_prefixAll flags of the sub-parser will be prefixed with this string, separated by a dash.

Prefixes are recursive. If B is a sub-parser of A with a flag prefix "b", and C is a sub-parser of B with a flag prefix "b", then a flag "--foo" of parser C will be treated as "--b-c-foo". Analogously for environment variables and PropertyMap paths.

The sub-parsers automatically take part in the parsing of the root parser. No extra action by the user is required.

Definition at line 1459 of file arg_parser.hpp.

References _env_prefix, _flag_prefix, _property_prefix, and parser().

Referenced by parser().

◆ set_description()

void FEAT::ArgParser::set_description ( String &&  description)
inline

Set program description.

Parameters
[in]descriptionDescription

This text will be shown before the usage information in the help text.

Definition at line 1294 of file arg_parser.hpp.

References _description.

Member Data Documentation

◆ _allow_unknown_cli_flags

bool FEAT::ArgParser::_allow_unknown_cli_flags = false
private

If true, unknown CLI flags do not produce errors.

Definition at line 1247 of file arg_parser.hpp.

Referenced by allow_unknown_cli_flags().

◆ _description

String FEAT::ArgParser::_description {""}
private

Description of this parser. Displayed in help text.

Definition at line 1237 of file arg_parser.hpp.

Referenced by help_text(), and set_description().

◆ _env_prefix

String FEAT::ArgParser::_env_prefix {""}
private

Prefix for environment variables. Gets preprended to this parsers environment variables.

Definition at line 1240 of file arg_parser.hpp.

Referenced by parser().

◆ _errors

std::deque<String> FEAT::ArgParser::_errors
private

Definition at line 1232 of file arg_parser.hpp.

◆ _flag_prefix

String FEAT::ArgParser::_flag_prefix {""}
private

Prefix for long flags. Gets preprended to this parsers long flags.

Definition at line 1244 of file arg_parser.hpp.

Referenced by parser().

◆ _parameters

std::deque<std::shared_ptr<Intern::ParameterCore> > FEAT::ArgParser::_parameters
private

Definition at line 1231 of file arg_parser.hpp.

◆ _program

String FEAT::ArgParser::_program {""}
private

Path to program, i.e. argv[0].

Definition at line 1235 of file arg_parser.hpp.

Referenced by help_text().

◆ _property_prefix

String FEAT::ArgParser::_property_prefix {""}
private

Prefix for property map paths. Gets preprended to this parsers property map paths.

Definition at line 1242 of file arg_parser.hpp.

Referenced by parser().

◆ priority_cli

constexpr int FEAT::ArgParser::priority_cli = 3
staticconstexprprivate

Definition at line 1252 of file arg_parser.hpp.

◆ priority_default

constexpr int FEAT::ArgParser::priority_default = 0
staticconstexprprivate

Definition at line 1249 of file arg_parser.hpp.

◆ priority_env

constexpr int FEAT::ArgParser::priority_env = 1
staticconstexprprivate

Definition at line 1250 of file arg_parser.hpp.

◆ priority_property

constexpr int FEAT::ArgParser::priority_property = 2
staticconstexprprivate

Definition at line 1251 of file arg_parser.hpp.


The documentation for this class was generated from the following files: