diff --git a/docs/tutorial.md b/docs/tutorial.md index c72a325d..de4331e8 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -28,8 +28,9 @@ - [Value Actions - Functions that are called after parsing an argument's value.](#value-actions---functions-that-are-called-after-parsing-an-arguments-value) - [Default Values - A list of values which will be used if no values for an argument have been parsed](#default-values---a-list-of-values-which-will-be-used-if-no-values-for-an-argument-have-been-parsed) - [Parameters Specific for Optional Arguments](#parameters-specific-for-optional-arguments) - - [On-flag Actions - Functions that are called immediately after parsing an argument's flag.](#on-flag-actions---functions-that-are-called-immediately-after-parsing-an-arguments-flag) - - [Implicit Values - A list of values which will be set for an argument if only its flag but no values are parsed from the command-line.](#implicit-values---a-list-of-values-which-will-be-set-for-an-argument-if-only-its-flag-but-no-values-are-parsed-from-the-command-line) + - [Implicit Values](#implicit-values) + - [On-flag Actions](#on-flag-actions) + - [Negative Flags](#negative-flags) - [Predefined Parameter Values](#predefined-parameter-values) - [Actions](#actions) - [Default Arguments](#default-arguments) @@ -327,7 +328,7 @@ parser.add_flag("enable_some_option", "eso").help("enables option: some option") /* equivalent to: parser.add_optional_argument("enable_some_option", "eso") .default_values(false) - .implicit_values(true) + .actions(argon::action::reset_parsed, argon::action::store(true)) .nargs(0) .help("enables option: some option"); */ @@ -633,7 +634,7 @@ Actions are represented as functions, which take the argument's value as an argu } parser.add_optional_argument("user", "u") - .action(is_valid_user_tag); + .actions(is_valid_user_tag); ``` - `transform` actions | `value_type(const value_type&)` - applied to the parsed value. The returned value will be used to initialize the argument's value. @@ -646,7 +647,7 @@ Actions are represented as functions, which take the argument's value as an argu } parser.add_optional_argument("key", "k") - .action(to_lower); + .actions(to_lower); ``` - `modify` actions | `void(value_type&)` - applied to the initialized value of an argument. @@ -657,12 +658,19 @@ Actions are represented as functions, which take the argument's value as an argu } parser.add_optional_argument("name", "n") - .action(capitalize); + .actions(capitalize); ``` > [!TIP] > -> A single argument can have multiple value actions. Instead of writing complex logic in one action, consider composing several simple, focused actions for better readability and reusability. +> A single argument can have multiple value actions. Instead of writing complex logic in one action, consider composing several simple, focused actions for better readability and reusability. You can pass multiple actions into a single `.actions(...)` call, e.g.: +> ```cpp +> parser.add_optional_argument("email") +> .actions( +> validate_email_format, +> validate_active_user +> ) +> ```
@@ -729,27 +737,9 @@ Command Result Apart from the common parameters listed above, for optional arguments you can also specify the following parameters: -#### On-flag Actions - Functions that are called immediately after parsing an argument's flag. - -```cpp -void print_debug_info() noexcept { -#ifdef NDEBUG - std::cout << "Running in release mode.\n"; -#else - std::cout << "Running in debug mode.\n"; -#endif - std::exit(EXIT_SUCCESS); -}; - -parser.add_optional_argument("debug-info") - .action(print_debug_info); -``` - -Here the `print_debug_info` function will be called right after parsing the `--debug-info` flag and the program will exit, even if there are more arguments after this flag. +#### Implicit Values -
- -#### Implicit Values - A list of values which will be set for an argument if only its flag but no values are parsed from the command-line. +A set of values which will be set for an argument if only its flag but no values are parsed from the command-line. ```cpp // example @@ -783,6 +773,59 @@ Command Result > > The `implicit_values` parameter is extremely useful when combined with default value (e.g. in case of boolean flags - see [Adding Arguments](#adding-arguments)). +
+ +#### On-flag Actions + +Functions that are called immediately after parsing an argument's flag. + +```cpp +void print_debug_info() noexcept { +#ifdef NDEBUG + std::cout << "Running in release mode.\n"; +#else + std::cout << "Running in debug mode.\n"; +#endif + std::exit(EXIT_SUCCESS); +}; + +parser.add_optional_argument("debug-info") + .actions(print_debug_info); +``` + +Here the `print_debug_info` function will be called right after parsing the `--debug-info` flag and the program will exit, even if there are more arguments after this flag. + +
+ +#### Negative Flags + +You can define a negative prefix (e.g., `"no-"`, `"disable-"`) for optional arguments, which allows users to explicitly disable features or reset an argument's values. + +```cpp +parser.add_optional_argument("color", "c") + .default_values("blue") // if no value is specified, "blue" will be used + .negative("no-"); // Registers an additional `--no-color` flag +``` + +By default, when the negative flag is used: + +- For `bool` flags: It stores `false` (overriding default/true values). +- For other types: It clears all parsed, default, and implicit values (executing the `argon::action::reset_all` behavior). + +You can customize the negative flag's behavior by passing variadic state action tags or custom callables: + +```cpp +parser.add_optional_argument("numbers") + .negative("clear-", argon::action::reset_parsed); // Only clears the user's parsed values, keeping defaults + +parser.add_optional_argument("mode") + .negative("no-", argon::action::reset_parsed, argon::action::store("none")); // Clears values and injects "none" +``` + +> [!WARNING] +> +> Be careful with the actions specified for negative flags. While you can pass arbitrary state action callable (i.e. `void()`), the expected behavior of such flags is **negation** and/or **state resetting**. +


@@ -796,7 +839,7 @@ Command Result Prints the parser's help message to the output stream and optionally exits with the given code. ```cpp - typename argon::action_type::on_flag::type print_help( + typename argon::action::on_flag::type print_help( const argon::argument_parser& parser, const std::optional exit_code = std::nullopt, std::ostream& os = std::cout @@ -808,52 +851,52 @@ Command Result Throws if the provided file path does not exist. ```cpp - argon::action::util::callable_type check_file_exists() noexcept; + argon::action::util::callable_type check_file_exists() noexcept; ``` -- `gt` | observe (value type: [arithmetic](https://en.cppreference.com/w/cpp/types/is_arithmetic)) +- `gt` | observe (value type: [arithmetic](https://www.google.com/search?q=https%3A%2F%2Fen.cppreference.com%2Fw%2Fcpp%2Ftypes%2Fis_arithmetic)) Validates that the value is strictly greater than `lower_bound`. ```cpp template - argon::action::util::callable_type gt(const T lower_bound) noexcept; + argon::action::util::callable_type gt(const T lower_bound) noexcept; ``` -- `geq` | observe (value type: [arithmetic](https://en.cppreference.com/w/cpp/types/is_arithmetic)) +- `geq` | observe (value type: [arithmetic](https://www.google.com/search?q=https%3A%2F%2Fen.cppreference.com%2Fw%2Fcpp%2Ftypes%2Fis_arithmetic)) Validates that the value is greater than or equal to `lower_bound`. ```cpp template - argon::action::util::callable_type geq(const T lower_bound) noexcept; + argon::action::util::callable_type geq(const T lower_bound) noexcept; ``` -- `lt` | observe (value type: [arithmetic](https://en.cppreference.com/w/cpp/types/is_arithmetic)) +- `lt` | observe (value type: [arithmetic](https://www.google.com/search?q=https%3A%2F%2Fen.cppreference.com%2Fw%2Fcpp%2Ftypes%2Fis_arithmetic)) Validates that the value is strictly less than `upper_bound`. ```cpp template - argon::action::util::callable_type lt(const T upper_bound) noexcept; + argon::action::util::callable_type lt(const T upper_bound) noexcept; ``` -- `leq` | observe (value type: [arithmetic](https://en.cppreference.com/w/cpp/types/is_arithmetic)) +- `leq` | observe (value type: [arithmetic](https://www.google.com/search?q=https%3A%2F%2Fen.cppreference.com%2Fw%2Fcpp%2Ftypes%2Fis_arithmetic)) Validates that the value is less than or equal to `upper_bound`. ```cpp template - argon::action::util::callable_type leq(const T upper_bound) noexcept; + argon::action::util::callable_type leq(const T upper_bound) noexcept; ``` -- `within` | observe (value type: [arithmetic](https://en.cppreference.com/w/cpp/types/is_arithmetic)) +- `within` | observe (value type: [arithmetic](https://www.google.com/search?q=https%3A%2F%2Fen.cppreference.com%2Fw%2Fcpp%2Ftypes%2Fis_arithmetic)) Checks if the value is within the given interval. Bound inclusivity is customizable using template parameters. ```cpp template - argon::action::util::callable_type within( + argon::action::util::callable_type within( const T lower_bound, const T upper_bound ) noexcept; ``` @@ -881,7 +924,7 @@ parser.default_arguments(); ```cpp // equivalent to: parser.add_positional_argument("input") - .action(argon::action::check_file_exists()) + .actions(argon::action::check_file_exists()) .help("Input file path"); ``` @@ -897,7 +940,7 @@ parser.default_arguments(); ```cpp // equivalent to: parser.add_optional_argument("help", "h") - .action(argon::action::print_help(parser, EXIT_SUCCESS)) + .actions(argon::action::print_help(parser, EXIT_SUCCESS)) .help("Display the help message"); ``` @@ -905,8 +948,8 @@ parser.default_arguments(); ```cpp // equivalent to: - parser.add_optional_argument("version", "v") - .action([&parser]() { + parser.add_optional_argument("version", "v") + .actions([&parser]() { parser.print_version(); std::exit(EXIT_SUCCESS); }) @@ -920,14 +963,14 @@ parser.default_arguments(); parser.add_optional_argument("input", "i") .required() .nargs(1) - .action(argon::action::check_file_exists()) + .actions(argon::action::check_file_exists()) .help("Input file path"); // multi_input - equivalent to: parser.add_optional_argument("input", "i") .required() .nargs(argon::nargs::at_least(1)) - .action(argon::action::check_file_exists()) + .actions(argon::action::check_file_exists()) .help("Input files paths"); ``` diff --git a/include/argon/action/predefined.hpp b/include/argon/action/predefined.hpp index d284adb4..7c4bfca8 100644 --- a/include/argon/action/predefined.hpp +++ b/include/argon/action/predefined.hpp @@ -19,13 +19,52 @@ std::ostream& operator<<(std::ostream& os, const argument_parser&) noexcept; namespace action { -/** - * @brief Returns an *on-flag* action which prints the argument parser's help message. - * @param parser Argument parser instance the help message of which will be printed. - * @param exit_code The exit code with which `std::exit` will be called (if not `std::nullopt`). - * @param os The output stream to which the help message will be printed. - */ -inline typename argon::action_type::on_flag::type print_help( +/// @brief A predefined negative flag action tag that clears only the parsed values. +inline constexpr action::reset_parsed_t reset_parsed{}; + +/// @brief A predefined negative flag action tag that clears all parsed, default, and implicit values. +inline constexpr action::reset_all_t reset_all{}; + +/// @brief A factory function returning a negative action tag that injects specific values. +/// @param val The primary value to store. +/// @param vals Additional variadic values to store. +template +requires traits::c_argument_value_type> +inline action::store_t> store(V&& val, Vs&&... vals) noexcept { + using value_type = std::remove_cvref_t; + + // clang-format off + return {std::vector{ + static_cast(std::forward(val)), + static_cast(std::forward(vals))... + }}; + // clang-format on +} + +/// @brief A factory function returning a negative action tag that injects a range of values. +/// @param range A range of values to store. +template +requires(not traits::c_argument_value_type>) + and traits::c_argument_value_type>> +inline action::store_t>> store(R&& range +) noexcept { + using value_type = std::remove_cvref_t>; + std::vector vals; + + if constexpr (std::ranges::sized_range) + vals.reserve(std::ranges::size(range)); + + for (auto&& v : range) + vals.emplace_back(std::forward(v)); + + return {std::move(vals)}; +} + +/// @brief Returns an *on-flag* action which prints the argument parser's help message. +/// @param parser Argument parser instance the help message of which will be printed. +/// @param exit_code The exit code with which `std::exit` will be called (if not `std::nullopt`). +/// @param os The output stream to which the help message will be printed. +inline typename argon::action::on_flag::type print_help( const argument_parser& parser, const std::optional exit_code = std::nullopt, std::ostream& os = std::cout @@ -38,7 +77,7 @@ inline typename argon::action_type::on_flag::type print_help( } /// @brief Returns an *observe* action which checks whether lower_bound file with the given name exists. -inline util::callable_type check_file_exists() noexcept { +inline util::callable_type check_file_exists() noexcept { return [](const std::string& file_path) { if (not std::filesystem::exists(file_path)) throw std::filesystem::filesystem_error( @@ -49,13 +88,11 @@ inline util::callable_type check_file_ }; } -/** - * @brief Returns an *observe* action which checks if a parsed value is greater than the given bound. - * @tparam T The *arithmetic* value type. - * @param lower_bound The exclusive lower bound to validate against. - */ +/// @brief Returns an *observe* action which checks if a parsed value is greater than the given bound. +/// @tparam T The *arithmetic* value type. +/// @param lower_bound The exclusive lower bound to validate against. template -util::callable_type gt(const T lower_bound) noexcept { +util::callable_type gt(const T lower_bound) noexcept { return [lower_bound](const T& value) { if (not (value > lower_bound)) throw std::out_of_range( @@ -64,13 +101,11 @@ util::callable_type gt(const T lower_bound) noex }; } -/** - * @brief Returns an *observe* action which checks if a parsed value is greater than or equal to the given bound. - * @tparam T The *arithmetic* value type. - * @param lower_bound The inclusive lower bound to validate against. - */ +/// @brief Returns an *observe* action which checks if a parsed value is greater than or equal to the given bound. +/// @tparam T The *arithmetic* value type. +/// @param lower_bound The inclusive lower bound to validate against. template -util::callable_type geq(const T lower_bound) noexcept { +util::callable_type geq(const T lower_bound) noexcept { return [lower_bound](const T& value) { if (! (value >= lower_bound)) throw std::out_of_range( @@ -79,13 +114,11 @@ util::callable_type geq(const T lower_bound) noe }; } -/** - * @brief Returns an *observe* action which checks if a parsed value is less than the given bound. - * @tparam T The *arithmetic* value type. - * @param lower_bound The exclusive upper bound to validate against. - */ +/// @brief Returns an *observe* action which checks if a parsed value is less than the given bound. +/// @tparam T The *arithmetic* value type. +/// @param lower_bound The exclusive upper bound to validate against. template -util::callable_type lt(const T upper_bound) noexcept { +util::callable_type lt(const T upper_bound) noexcept { return [upper_bound](const T& value) { if (! (value < upper_bound)) throw std::out_of_range( @@ -94,13 +127,11 @@ util::callable_type lt(const T upper_bound) noex }; } -/** - * @brief Returns an *observe* action which checks if a parsed value is less than or equal to the given bound. - * @tparam T The *arithmetic* value type. - * @param lower_bound The inclusive upper bound to validate against. - */ +/// @brief Returns an *observe* action which checks if a parsed value is less than or equal to the given bound. +/// @tparam T The *arithmetic* value type. +/// @param lower_bound The inclusive upper bound to validate against. template -util::callable_type leq(const T upper_bound) noexcept { +util::callable_type leq(const T upper_bound) noexcept { return [upper_bound](const T& value) { if (! (value <= upper_bound)) throw std::out_of_range( @@ -109,19 +140,18 @@ util::callable_type leq(const T upper_bound) noe }; } -/** - * @brief Returns an *observe* action which checks if a parsed value falls within the specified interval. - * - * The interval is defined by the given lower and upper bounds, with inclusivity controlled by the template parameters. - * - * @tparam T The *arithmetic* value type. - * @tparam LeftInclusive Whether the lower bound is inclusive (`[`) or exclusive (`(`) - default: true. - * @tparam RightInclusive Whether the upper bound is inclusive (`]`) or exclusive (`)`) - default: true. - * @param lower_bound The lower bound of the interval. - * @param upper_bound The upper bound of the interval. - */ -template -util::callable_type within( +/// @brief Returns an *observe* action which checks if a parsed value falls within the specified interval. +/// +/// The interval is defined by the given lower and upper bounds, with inclusivity controlled by the template parameters. +/// +/// @tparam T The *arithmetic* value type. +/// @tparam LeftInclusive Whether the lower bound is inclusive (`[`) or exclusive (`(`) - default: true. +/// @tparam RightInclusive Whether the upper bound is inclusive (`]`) or exclusive (`)`) - default: true. +/// @param lower_bound The lower bound of the interval. +/// @param upper_bound The upper bound of the interval. +/// @todo Add explicit inclusive/exclusive constants (perhaps in argon::traits) +template +util::callable_type within( const T lower_bound, const T upper_bound ) noexcept { return [lower_bound, upper_bound](const T& value) { diff --git a/include/argon/action/traits.hpp b/include/argon/action/traits.hpp index bf58197b..9e0878f2 100644 --- a/include/argon/action/traits.hpp +++ b/include/argon/action/traits.hpp @@ -2,10 +2,8 @@ // This file is part of the CPP-ARGON project (https://github.com/SpectraL519/cpp-argon). // Licensed under the MIT License. See the LICENSE file in the project root for full license information. -/** - * @file argon/action/traits.hpp - * @brief Defines action-related traits and concepts. - */ +/// @file argon/action/traits.hpp +/// @brief Defines action-related traits and concepts. #pragma once @@ -16,29 +14,33 @@ namespace argon::traits { -/** - * @brief The concept is satisfied when `AS` is a valid *value* action action specifier. - * @tparam AS The action specifier type. - * @ingroup traits - */ +/// @brief The concept is satisfied when `AS` is a valid *value* action action specifier. +/// @tparam AS The action specifier type. +/// @ingroup traits template concept c_value_action_specifier = - argon::traits::c_one_of; + argon::traits::c_one_of; -/** - * @brief The concept is satisfied when `AS` is a valid *on-flag* action action specifier. - * @tparam AS The action specifier type. - * @ingroup traits - */ +/// @brief The concept is satisfied when `AS` is a valid *on-flag* action action specifier. +/// @tparam AS The action specifier type. +/// @ingroup traits template -concept c_flag_action_specifier = argon::traits::c_one_of; +concept c_flag_action_specifier = argon::traits::c_one_of; -/** - * @brief The concept is satisfied when `AS` is a valid action action specifier. - * @tparam AS The action specifier type. - * @ingroup traits - */ +/// @brief The concept is satisfied when `AS` is a valid action action specifier. +/// @tparam AS The action specifier type. +/// @ingroup traits template -concept c_action_specifier = c_value_action_specifier or std::same_as; +concept c_action_specifier = c_value_action_specifier or std::same_as; + +/// @brief Concept validating if a type is a predefined state action tag. +template +concept c_state_action_specifier = + c_one_of + or c_instantiation_of; + +/// @brief Concept validating if a type is a valid state action (a specifier tag or an invocable callable). +template +concept c_state_action = c_state_action_specifier> or std::invocable; } // namespace argon::traits diff --git a/include/argon/action/types.hpp b/include/argon/action/types.hpp index 71495fc2..36a0bc2a 100644 --- a/include/argon/action/types.hpp +++ b/include/argon/action/types.hpp @@ -2,10 +2,8 @@ // This file is part of the CPP-ARGON project (https://github.com/SpectraL519/cpp-argon). // Licensed under the MIT License. See the LICENSE file in the project root for full license information. -/** - * @file argon/action/types.hpp - * @brief Defies the action specifier types. - */ +/// @file argon/action/types.hpp +/// @brief Defies the action specifier types. #pragma once @@ -13,51 +11,55 @@ #include -namespace argon::action_type { +namespace argon::action { -/** - * @brief An observing *value* action specifier. - * - * Represents an argument action which observes the parsed value and - * performs some logic on it without modifying it. - */ +/// @brief Tag type used to reset an argument's parsed values. +struct reset_parsed_t {}; + +/// @brief Tag type used to clear an argument's parsed, default, and implicit values. +struct reset_all_t {}; + +/// @brief A type used to store/insert values for an argument by an argument action. +template +struct store_t { + std::vector values; +}; + +/// @brief An observing *value* action specifier. +/// +/// Represents an argument action which observes the parsed value and +/// performs some logic on it without modifying it. struct observe { - template + template using type = std::function; }; -/** - * @brief A transformating *value* action specifier. - * - * Represents an argument action which transforms the parsed value and - * returns a new value with which the argument will be initialized. - */ +/// @brief A transformating *value* action specifier. +/// +/// Represents an argument action which transforms the parsed value and +/// returns a new value with which the argument will be initialized. struct transform { - template + template using type = std::function; }; -/** - * @brief A modifying *value* action specifier. - * - * Represents an argument action which modifies the value of an - * already initialized argument. - */ +/// @brief A modifying *value* action specifier. +/// +/// Represents an argument action which modifies the value of an +/// already initialized argument. struct modify { - template + template using type = std::function; }; -/** - * @brief An on-flag action specifier. - * - * Represents an action associated with an argument that performs - * some logic, independently of the parsed value. - * - * @note An on-flag action is executed immediately after parsing the argument's flag and before parsing the following values. - */ +/// @brief An on-flag action specifier. +/// +/// Represents an action associated with an argument that performs +/// some logic, independently of the parsed value. +/// +/// @note An on-flag action is executed immediately after parsing the argument's flag and before parsing the following values. struct on_flag { using type = std::function; }; -} // namespace argon::action_type +} // namespace argon::action diff --git a/include/argon/action/util.hpp b/include/argon/action/util.hpp index 41bb7192..458f60d4 100644 --- a/include/argon/action/util.hpp +++ b/include/argon/action/util.hpp @@ -24,9 +24,9 @@ using callable_type = typename AS::template type; /// @brief Template argument action callabla variant type alias. template using value_action_variant_type = std::variant< - callable_type, - callable_type, - callable_type>; + callable_type, + callable_type, + callable_type>; /** * @brief A visitor structure used to apply *value* actions. @@ -41,7 +41,7 @@ struct apply_visitor { * @brief The call operator overload for the *observe* action type. * @param action The *observe* action callable. */ - void operator()(const callable_type& action) const { + void operator()(const callable_type& action) const { action(std::as_const(value)); } @@ -49,7 +49,7 @@ struct apply_visitor { * @brief The call operator overload for the *transform* action type. * @param action The *transform* action callable. */ - void operator()(const callable_type& action) const { + void operator()(const callable_type& action) const { value = action(std::as_const(value)); } @@ -57,7 +57,7 @@ struct apply_visitor { * @brief The call operator overload for the *modify* action type. * @param action The *modify* action callable. */ - void operator()(const callable_type& action) const { + void operator()(const callable_type& action) const { action(value); } diff --git a/include/argon/argument.hpp b/include/argon/argument.hpp index fcc6b702..bbf7623e 100644 --- a/include/argon/argument.hpp +++ b/include/argon/argument.hpp @@ -253,37 +253,79 @@ class argument : public typed_argument_base { } /** - * @brief Set the *value* action for the argument. - * @tparam AS The action specifier type (see @ref argon/action/type.hpp). - * @tparam F The type of the action function. - * @param action The action callable. + * @brief Set multiple *value* actions for the argument. + * @tparam AS The action specifier type (e.g., `argon::action::observe`, `argon::action::transform`, `argon::action::modify`). + * @tparam Fs The types of the action callables. + * @param value_actions A variadic list of callables to be executed sequentially after the argument's value is parsed. * @return Reference to the argument instance. - * @note The method is enabled only if: - * @note - `value_type` is not `none_type`. - * @note - `AS` is a valid value action specifier: `action_type::observe`, `action_type::transform`, `action_type::modify`. + * @note The method is enabled only if `value_type` is not `none_type`. */ - template - argument& action(F&& action) noexcept + template + argument& actions(Fs&&... value_actions) noexcept requires(not traits::c_is_none) { using callable_type = action::util::callable_type; - this->_value_actions.emplace_back(std::forward(action)); + // clang-format off + (this->_value_actions.emplace_back(static_cast(std::forward(value_actions))), ...); + // clang-format on return *this; } /** - * @brief Set the *on-flag* action for the argument. - * @tparam AS The action specifier type (see @ref argon/action/types.hpp). - * @tparam F The type of the action function. - * @param action The action callable. + * @brief Set multiple *on-flag* actions for the argument. + * @tparam AS The action specifier type (must be `argon::action::on_flag`). + * @tparam Fs The types of the state action callables or predefined action tags. + * @param state_actions A variadic list of predefined tags (e.g., `action::reset_parsed`, `action::store`) or generic invocable callables. * @return Reference to the argument instance. - * @note The method is enabled only for optional arguments and if `AS` is `action_type::on_flag`. + * @note The method is enabled only for optional arguments. + * @note On-flag actions are executed immediately after parsing the argument's flag, before parsing any subsequent values. */ - template - argument& action(F&& action) noexcept + template + argument& actions(Fs&&... state_actions) requires(type == argument_type::optional) { - this->_flag_actions.emplace_back(std::forward(action)); + // clang-format off + (this->_flag_actions.emplace_back(this->_compile_state_action(std::forward(state_actions))), ...); + // clang-format on + return *this; + } + + /** + * @brief Set the negative prefix and associated state actions for the argument. + * @tparam Actions The types of the state action callables or predefined action tags. + * @param prefix The negative prefix string (e.g., "no-", "disable-"). + * @param state_actions A variadic list of predefined tags (like `action::reset_parsed`) or generic invocable callables executed when the negative flag is used. + * If left empty, sensible defaults are automatically applied. + * @return Reference to the argument instance. + * @note If no actions are provided, the default behavior is storing `false` (via `action::reset_parsed` and `action::store(false)`) for booleans, and clearing all values (via `action::reset_all`) for others. + * @note The method is enabled only for optional arguments. + */ + template + argument& negative(std::string_view prefix, Actions&&... state_actions) + requires(type == argument_type::optional) + { + this->_name.negative_prefix(prefix); + + if constexpr (sizeof...(Actions) == 0) { + if constexpr (std::same_as) { + this->_negative_actions.emplace_back( + this->_compile_state_action(action::reset_parsed) + ); + this->_negative_actions.emplace_back(this->_compile_state_action(action::store(false + ))); + } + else { + this->_negative_actions.emplace_back(this->_compile_state_action(action::reset_all) + ); + } + } + else { + (this->_negative_actions.emplace_back( + this->_compile_state_action(std::forward(state_actions)) + ), + ...); + } + return *this; } @@ -501,8 +543,8 @@ class argument : public typed_argument_base { /// @brief The argument's value action type alias. using value_action_type = action::util::value_action_variant_type; - /// @brief The argument's flag action type alias. - using flag_action_type = typename action_type::on_flag::type; + /// @brief The argument's state action type alias. + using state_action_type = std::function; /// @brief The argument's value-argument-specific type alias. /// @tparam _T The actual type used if the argument's `value_type` is not `none_type`. @@ -559,6 +601,8 @@ class argument : public typed_argument_base { return bld; } + // --- parsing --- + /// @brief Mark the optional argument as used. /// @return `true` if the argument accepts further values, `false` otherwise. bool mark_used() override { @@ -571,6 +615,18 @@ class argument : public typed_argument_base { return this->_accepts_further_values(); } + /// @brief Mark the optional argument's negative flag as used. + /// @return `true` if the argument accepts further values, `false` otherwise. + bool mark_negative_used() override { + if constexpr (type == argument_type::optional) { + ++this->_count; + for (const auto& action : this->_negative_actions) + action(); + } + + return false; // Negative flags are terminal + } + /** * @brief Set the value for the optional argument. * @param str_value The string value to use. @@ -583,10 +639,10 @@ class argument : public typed_argument_base { /// @return The ordering relationship of the argument's values and its nargs range attribute. [[nodiscard]] std::weak_ordering nvalues_ordering() const noexcept override { - if (this->_values.empty() and this->_has_predefined_values_impl()) + if (this->_parsed_nvalues == 0ull and this->_has_predefined_values_impl()) return std::weak_ordering::equivalent; - return this->_values.size() <=> this->_nargs_range; + return this->_parsed_nvalues <=> this->_nargs_range; } /// @return Reference to the vector of parsed values for the argument. @@ -764,11 +820,51 @@ class argument : public typed_argument_base { std::visit(apply_visitor, action); this->_values.emplace_back(std::move(value)); + ++this->_parsed_nvalues; // Mark an explicitly parsed value + return this->_accepts_further_values(); } + // --- configuration --- + + template + state_action_type _compile_state_action(F&& action) { + using action_t = std::remove_cvref_t; + + if constexpr (traits::c_state_action_specifier) { + if constexpr (std::same_as) { + return [this]() { + this->_values.clear(); + this->_parsed_nvalues = 0ull; + }; + } + else if constexpr (std::same_as) { + return [this]() { + this->_values.clear(); + this->_parsed_nvalues = 0ull; + if constexpr (not traits::c_is_none) { + this->_default_values.clear(); + this->_implicit_values.clear(); + } + }; + } + else if constexpr (traits::c_instantiation_of) { + return [this, vals = action.values]() { + if constexpr (not traits::c_is_none) { + for (const auto& v : vals) { + this->_values.emplace_back(v); + } + } + }; + } + } + else { + return std::forward(action); // User provided a raw callable + } + } + // attributes - const argon::argument_name _name; ///< The argument's name. + argument_name _name; ///< The argument's name. std::string _help_msg; ///< The argument's help message. nargs::range _nargs_range; ///< The argument's nargs range attribute value. @@ -778,10 +874,12 @@ class argument : public typed_argument_base { _implicit_values; ///< The optional argument's implicit value list. [[no_unique_address]] value_arg_specific_type> _choices; ///< The argument's valid choices collection. - [[no_unique_address]] optional_specific_type> - _flag_actions; ///< The optional argument's flag actions collection. [[no_unique_address]] value_arg_specific_type> _value_actions; ///< The argument's value actions collection. + [[no_unique_address]] optional_specific_type> + _flag_actions; ///< The optional argument's flag actions collection. + [[no_unique_address]] optional_specific_type> + _negative_actions; ///< The action executed when the negative flag is used. bool _required : 1; ///< The argument's `required` attribute value. bool _suppress_arg_checks : 1 = @@ -794,6 +892,8 @@ class argument : public typed_argument_base { // parsing result [[no_unique_address]] optional_specific_type _count; ///< The argument's value count. + [[no_unique_address]] std::size_t _parsed_nvalues = + 0ull; ///< Tracks ONLY the values consumed from the command line. std::vector _values; ///< The argument's parsed values. // default attribute values diff --git a/include/argon/argument_base.hpp b/include/argon/argument_base.hpp index 50c797fe..d352f626 100644 --- a/include/argon/argument_base.hpp +++ b/include/argon/argument_base.hpp @@ -83,6 +83,10 @@ class argument_base { /// @return `true` if the argument accepts further values, `false` otherwise. virtual bool mark_used() = 0; + /// @brief Mark the argument's negative flag as used. + /// @return `true` if the argument accepts further values, `false` otherwise. + virtual bool mark_negative_used() = 0; + /// @brief Set the value for the argument. /// @param value The string representation of the value. /// @return `true` if the argument accepts further values, `false` otherwise. diff --git a/include/argon/argument_name.hpp b/include/argon/argument_name.hpp index 0a814ef7..b3f2a27d 100644 --- a/include/argon/argument_name.hpp +++ b/include/argon/argument_name.hpp @@ -20,9 +20,10 @@ class argument_name { public: /// @brief Specifies the type of argument name match. enum class match_type : std::uint8_t { - m_any, ///< Matches either the primary or the secondary name. + m_any, ///< Matches either the primary, secondary, or negative name. m_primary, ///< Matches only the primary name. - m_secondary ///< Matches only the secondary name. + m_secondary, ///< Matches only the secondary name. + m_negative ///< Matches only the negative primary name. }; using enum match_type; @@ -34,12 +35,10 @@ class argument_name { argument_name& operator=(const argument_name&) = default; argument_name& operator=(argument_name&&) = default; - /** - * @brief Primary and secondary name constructor. - * @param primary The primary name of the argument. - * @param secondary The secondary (short) name of the argument. - * @param flag_char The flag character (used for optional argument names). - */ + /// @brief Primary and secondary name constructor. + /// @param primary The primary name of the argument. + /// @param secondary The secondary (short) name of the argument. + /// @param flag_char The flag character (used for optional argument names). explicit argument_name( std::string primary, std::string secondary = "", char flag_char = flag_char_sentinel ) @@ -52,13 +51,12 @@ class argument_name { /// @brief Class destructor. ~argument_name() = default; - /** - * @brief Equality comparison operator. - * @param other The argument_name instance to compare with. - * @return Equality of argument names. - */ + /// @brief Equality comparison operator. + /// @param other The argument_name instance to compare with. + /// @return Equality of argument names. bool operator==(const argument_name& other) const noexcept { - return this->_primary == other._primary and this->_secondary == other._secondary; + return this->_primary == other._primary and this->_secondary == other._secondary + and this->_negative_prefix == other._negative_prefix; } /// @brief Checks if the argument name instance has a primary name. @@ -71,6 +69,11 @@ class argument_name { return not this->_secondary.empty(); } + /// @brief Checks if the argument name instance has a negative prefix. + [[nodiscard]] bool has_negative() const noexcept { + return not this->_negative_prefix.empty(); + } + /// @return The primary name of the argument. [[nodiscard]] const std::string& primary() const noexcept { return this->_primary; @@ -81,70 +84,93 @@ class argument_name { return this->_secondary; } + /// @return The negative prefix of the argument. + [[nodiscard]] const std::string& negative_prefix() const noexcept { + return this->_negative_prefix; + } + /// @return The flag character (used for optional argument names). [[nodiscard]] char flag_char() const noexcept { return this->_flag_char; } - /** - * @brief Matches the given string to the argument_name instance. - * @param arg_name The name string to match. - * @param m_type The match type used to find the argument. - * @return `true` if the given name matches the primary/secondary name (depending on the match type). - */ + /// @brief Sets the negative prefix for the argument name. + /// @param prefix The negative prefix string. + /// @return Reference to the argument name instance. + /// @throws std::logic_error if the argument does not have a primary name. + argument_name& negative_prefix(std::string_view prefix) { + if (not this->has_primary()) + throw std::logic_error("Cannot add a negative prefix to an argument without a primary " + "name!"); + this->_negative_prefix = prefix; + return *this; + } + + /// @brief Matches the given string to the argument_name instance. + /// @param arg_name The name string to match. + /// @param m_type The match type used to find the argument. + /// @return `true` if the given name matches the primary/secondary/negative name (depending on the match type). [[nodiscard]] bool match(std::string_view arg_name, const match_type m_type = m_any) const noexcept { switch (m_type) { case m_any: return (this->has_primary() and this->_primary == arg_name) + or (this->has_primary() and this->has_negative() + and (this->_negative_prefix + this->_primary) == arg_name) or (this->has_secondary() and this->_secondary == arg_name); case m_primary: return this->has_primary() and this->_primary == arg_name; case m_secondary: return this->has_secondary() and this->_secondary == arg_name; + case m_negative: + return this->has_primary() and this->has_negative() + and (this->_negative_prefix + this->_primary) == arg_name; } return false; } - /** - * @brief Matches the given argument name to the argument_name instance. - * @param arg_name The argument_name instance to match. - * @return True if arg_name's primary or secondary value matches the argument_name instance. - */ + /// @brief Matches the given argument name to the argument_name instance. + /// @param arg_name The argument_name instance to match. + /// @return True if arg_name's primary, secondary, or negative value matches the argument_name instance. [[nodiscard]] bool match(const argument_name& arg_name) const noexcept { if (arg_name.has_primary() and this->match(arg_name._primary)) return true; - if (arg_name.has_secondary()) - return this->match(arg_name._secondary); + if (arg_name.has_secondary() and this->match(arg_name._secondary)) + return true; + + if (arg_name.has_negative() and this->match(arg_name._negative_prefix + arg_name._primary)) + return true; return false; } - /** - * @brief Get a string representation of the argument_name. - */ + /// @brief Get a string representation of the argument_name. [[nodiscard]] std::string str() const noexcept { const std::string fc( static_cast(this->_flag_char != flag_char_sentinel), this->_flag_char ); std::string primary_str = - this->has_primary() ? std::format("{}{}{}", fc, fc, this->_primary) : ""; - std::string separator = this->has_primary() and this->has_secondary() ? ", " : ""; + this->has_primary() + ? (this->has_negative() + ? std::format("{}{}[{}]{}", fc, fc, this->_negative_prefix, this->_primary) + : std::format("{}{}{}", fc, fc, this->_primary)) + : ""; + + std::string separator = (this->has_primary() and this->has_secondary()) ? ", " : ""; + std::string secondary_str = this->has_secondary() ? std::format("{}{}", fc, this->_secondary) : ""; return std::format("{}{}{}", primary_str, separator, secondary_str); } - /** - * @brief Stream insertion operator for argument names. - * @param os The output stream. - * @param arg_name The argument name to be inserted into the stream. - * @return The modified output stream. - */ + /// @brief Stream insertion operator for argument names. + /// @param os The output stream. + /// @param arg_name The argument name to be inserted into the stream. + /// @return The modified output stream. friend std::ostream& operator<<(std::ostream& os, const argument_name& arg_name) noexcept { os << arg_name.str(); return os; @@ -156,14 +182,12 @@ class argument_name { private: std::string _primary; ///< The primary name of the argument. std::string _secondary; ///< The optional (short) name of the argument. + std::string _negative_prefix; ///< The optional negative prefix for the primary name. char _flag_char; ///< The flag character (used for optional argument names). }; -/** - * @brief Argument name member discriminator. - * - * This discriminator type is used in the argument initializing methods of the `argument_parser` class. - */ +/// @brief Argument name member discriminator. +/// This discriminator type is used in the argument initializing methods of the `argument_parser` class. enum class argument_name_discriminator : bool { n_primary, ///< Represents the primary name (used with a long flag prefix --). n_secondary ///< Represents the secondary name (used with a short flag prefix --). diff --git a/include/argon/argument_parser.hpp b/include/argon/argument_parser.hpp index 546b8e40..424d3802 100644 --- a/include/argon/argument_parser.hpp +++ b/include/argon/argument_parser.hpp @@ -39,7 +39,7 @@ enum class default_argument : std::uint8_t { * Equivalent to: * @code{.cpp} * parser.add_positional_argument("input") - * .action(argon::action::check_file_exists()) + * .actions(argon::action::check_file_exists()) * .help("Input file path"); * @endcode */ @@ -60,7 +60,7 @@ enum class default_argument : std::uint8_t { * Equivalent to: * @code{.cpp} * parser.add_optional_argument("help") - * .action(argon::action::print_help(parser, EXIT_SUCCESS)) + * .actions(argon::action::print_help(parser, EXIT_SUCCESS)) * .help("Display the help message"); * @endcode */ @@ -71,7 +71,7 @@ enum class default_argument : std::uint8_t { * Equivalent to: * @code{.cpp} * arg_parser.add_optional_argument("version", "v") - * .action([&arg_parser]() { + * .actions([&arg_parser]() { * arg_parser.print_version(); * std::exit(EXIT_SUCCESS); * }) @@ -86,7 +86,7 @@ enum class default_argument : std::uint8_t { * @code{.cpp} * parser.add_positional_argument("input", "i") * .nargs(1ull) - * .action(argon::action::check_file_exists()) + * .actions(argon::action::check_file_exists()) * .help("Input file path"); * @endcode */ @@ -109,7 +109,7 @@ enum class default_argument : std::uint8_t { * @code{.cpp} * parser.add_positional_argument("input", "i") * .nargs(argon::nargs::at_least(1ull)) - * .action(argon::action::check_file_exists()) + * .actions(argon::action::check_file_exists()) * .help("Input file path"); * @endcode */ @@ -515,8 +515,8 @@ class argument_parser { ) { return this->add_optional_argument(base_name, name_discr) .default_values(not StoreImplicitly) - .implicit_values(StoreImplicitly) - .nargs(0ull); + .nargs(0ull) + .actions(action::reset_parsed, action::store(StoreImplicitly)); } /** @@ -533,8 +533,8 @@ class argument_parser { ) { return this->add_optional_argument(base_primary_name, base_secondary_name) .default_values(not StoreImplicitly) - .implicit_values(StoreImplicitly) - .nargs(0ull); + .nargs(0ull) + .actions(action::reset_parsed, action::store(StoreImplicitly)); } /** @@ -554,8 +554,8 @@ class argument_parser { ) { return this->add_optional_argument(group, base_name, name_discr) .default_values(not StoreImplicitly) - .implicit_values(StoreImplicitly) - .nargs(0ull); + .nargs(0ull) + .actions(action::reset_parsed, action::store(StoreImplicitly)); } /** @@ -575,8 +575,8 @@ class argument_parser { ) { return this->add_optional_argument(group, base_primary_name, base_secondary_name) .default_values(not StoreImplicitly) - .implicit_values(StoreImplicitly) - .nargs(0ull); + .nargs(0ull) + .actions(action::reset_parsed, action::store(StoreImplicitly)); } /** @@ -1391,19 +1391,39 @@ class argument_parser { return false; } - [[nodiscard]] arg_ptr_vec_iter_t _find_opt_arg(const detail::argument_token& flag_tok - ) noexcept { + [[nodiscard]] arg_ptr_vec_iter_t _find_opt_arg(detail::argument_token& flag_tok) noexcept { if (not flag_tok.is_flag_token()) return this->_optional_args.end(); const auto actual_tok_value = this->_strip_flag_prefix(flag_tok); - const auto match_type = - flag_tok.type == detail::argument_token::t_flag_primary - ? argument_name::m_primary - : argument_name::m_secondary; + if (flag_tok.type == detail::argument_token::t_flag_primary) { + // Match by primary name + auto it = std::ranges::find_if( + this->_optional_args, + this->_name_match_predicate(actual_tok_value, argument_name::m_primary) + ); + if (it != this->_optional_args.end()) + return it; + + // Match by negative name if it can't be matched by primary + it = std::ranges::find_if( + this->_optional_args, + this->_name_match_predicate(actual_tok_value, argument_name::m_negative) + ); + if (it != this->_optional_args.end()) { + flag_tok.type = detail::argument_token::t_flag_negative; + return it; + } + + // Not found + return this->_optional_args.end(); + } + + // Secondary and compound flags cannot have a negative prefix return std::ranges::find_if( - this->_optional_args, this->_name_match_predicate(actual_tok_value, match_type) + this->_optional_args, + this->_name_match_predicate(actual_tok_value, argument_name::m_secondary) ); } @@ -1445,7 +1465,12 @@ class argument_parser { } for (const auto& arg : tok.args) { - if (arg->mark_used()) + const bool accepts_values = + (tok.type == detail::argument_token::t_flag_negative) + ? arg->mark_negative_used() + : arg->mark_used(); + + if (accepts_values) state.curr_arg = arg; else state.curr_arg.reset(); @@ -1732,7 +1757,7 @@ inline void add_default_argument( switch (arg_discriminator) { case default_argument::p_input: arg_parser.add_positional_argument("input") - .action(action::check_file_exists()) + .actions(action::check_file_exists()) .help("Input file path"); break; @@ -1742,13 +1767,13 @@ inline void add_default_argument( case default_argument::o_help: arg_parser.add_optional_argument("help", "h") - .action(action::print_help(arg_parser, EXIT_SUCCESS)) + .actions(action::print_help(arg_parser, EXIT_SUCCESS)) .help("Display the help message"); break; case default_argument::o_version: arg_parser.add_optional_argument("version", "v") - .action([&arg_parser]() { + .actions([&arg_parser]() { arg_parser.print_version(); std::exit(EXIT_SUCCESS); }) @@ -1758,7 +1783,7 @@ inline void add_default_argument( case default_argument::o_input: arg_parser.add_optional_argument("input", "i") .nargs(1ull) - .action(action::check_file_exists()) + .actions(action::check_file_exists()) .help("Input file path"); break; @@ -1769,7 +1794,7 @@ inline void add_default_argument( case default_argument::o_multi_input: arg_parser.add_optional_argument("input", "i") .nargs(argon::nargs::at_least(1ull)) - .action(action::check_file_exists()) + .actions(action::check_file_exists()) .help("Input files paths"); break; diff --git a/include/argon/detail/argument_token.hpp b/include/argon/detail/argument_token.hpp index 5894b450..5611626c 100644 --- a/include/argon/detail/argument_token.hpp +++ b/include/argon/detail/argument_token.hpp @@ -25,7 +25,8 @@ struct argument_token { t_value, ///< Represents a value argument. t_flag_primary, ///< Represents a primary (--) flag argument. t_flag_secondary, ///< Represents a secondary (-) flag argument. - t_flag_compound ///< Represents a compound flag argument (secondary flag matching multiple arguments). + t_flag_compound, ///< Represents a compound flag argument (secondary flag matching multiple arguments). + t_flag_negative ///< Represents a primary flag argument matching a negative prefix. }; using enum token_type; @@ -45,14 +46,14 @@ struct argument_token { * @note - t_flag_primary * @note - t_flag_secondary * @note - t_flag_compound + * @note - t_flag_negative */ [[nodiscard]] bool is_flag_token() const noexcept { switch (this->type) { case t_flag_primary: - [[fallthrough]]; case t_flag_secondary: - [[fallthrough]]; case t_flag_compound: + case t_flag_negative: return true; default: return false; diff --git a/include/argon/traits.hpp b/include/argon/traits.hpp index 9d14e11f..25d509dd 100644 --- a/include/argon/traits.hpp +++ b/include/argon/traits.hpp @@ -86,6 +86,33 @@ using argument_result_type = template concept c_one_of = std::disjunction_v...>; +/// @ingroup traits +/// @brief Type trait to check if a type is an instantiation of a specific class template. +/// @tparam T The type to check. +/// @tparam Template The class template to match against. +template typename Template> +struct is_instantiation_of : std::false_type {}; + +/// @ingroup traits +/// @brief Specialization of the @ref gl::traits::is_instantiation_of "is_instantiation_of" trait +/// for when the type is an instantiation of the provided class template. +template