Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
- [Parsing Arguments with Subparsers](/docs/tutorial.md#parsing-arguments-with-subparsers)
- [Tracking Parser State](/docs/tutorial.md#tracking-parser-state)
- [Suppressing Argument Group Checks](/docs/tutorial.md#suppressing-argument-group-checks)
- [Resetting Parser State](/docs/tutorial.md#resetting-parser-state)
- [Examples](/docs/tutorial.md#examples)
- [Common Utility](/docs/tutorial.md#common-utility)
- [Dev notes](/docs/dev_notes.md#dev-notes)
Expand Down
29 changes: 29 additions & 0 deletions docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
- [Parsing Arguments with Subparsers](#parsing-arguments-with-subparsers)
- [Tracking Parser State](#tracking-parser-state)
- [Example: Inspecting Parsing States](#example-inspecting-parsing-states)
- [Resetting Parser State](#resetting-parser-state)
- [Examples](#examples)
- [Common Utility](#common-utility)

Expand Down Expand Up @@ -1901,6 +1902,34 @@ Resolved parser : init (argon-git submodule init)
<br/>
<br/>

## Resetting Parser State

If you need to reuse an `argument_parser` instance multiple times within the same program execution (e.g., inside a REPL loop, a long-running service, or a test suite), you can clear its parsing state using the `reset()` method:

```cpp
parser.reset();
```

Calling `reset()` performs a deep clean of the runtime state while keeping your configuration entirely intact. Specifically, it will:

- Clear all explicitly parsed values and reset argument usage counts to zero.
- Lift any masks on default or implicit values that were suppressed by negative flags (e.g., flags utilizing `argon::action::discard_all`).
- Revert the parser's `invoked()` and `finalized()` state flags to `false`.
- Recursively reset the state of all attached subparsers.
- Revert dynamically deduced program names (`argon::dynamic_name`) back to an unresolved state, ensuring the parser safely re-deduces its name from `argv[0]` on the next run.

> [!IMPORTANT]
>
> `reset()` only clears the **runtime parsing state**. It does not alter, remove, or destroy your parser's structural configuration (defined arguments, groups, explicit default values, choices, or actions).

> [!NOTE]
>
> The parser does **not** call `reset()` automatically when you invoke `parse_args()`. This deliberate design choice preserves the parser's state across multiple calls, enabling advanced multi-pass parsing workflows (for example, parsing a string of base configurations first, and then parsing user CLI overrides to accumulate values). If your intent is to start a completely fresh parsing run, you must call `reset()` explicitly.

<br/>
<br/>
<br/>

## Examples

The library usage examples and demo projects are included in the `cpp-argon-demo` submodule.
Expand Down
30 changes: 24 additions & 6 deletions include/argon/argument.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,18 +68,20 @@ class argument : public typed_argument_base<T> {
* @param name The name of the positional argument.
* @note The constructor is enabled only if `type` is `argument_type::positional`.
*/
argument(const argument_name& name)
argument(argument_name name)
requires(type == argument_type::positional)
: _name(name), _nargs_range(_default_nargs_range_actual), _required(_default_required) {}
: _name(std::move(name)),
_nargs_range(_default_nargs_range_actual),
_required(_default_required) {}

/**
* @brief Optional argument constructor.
* @param name The name of the optional argument.
* @note The constructor is enabled only if `type` is `argument_type::optional`.
*/
argument(const argument_name& name)
argument(argument_name name)
requires(type == argument_type::optional)
: _name(name),
: _name(std::move(name)),
_nargs_range(_default_nargs_range_actual),
_required(_default_required),
_count(0ull) {}
Expand Down Expand Up @@ -570,6 +572,16 @@ class argument : public typed_argument_base<T> {
using optional_specific_type =
std::conditional_t<type == argument_type::optional, _T, none_type>;

/// @brief Reset the argument's state, clearing parsed values and resetting counters.
void reset() noexcept override {
this->_values.clear();
this->_parsed_nvalues = 0ull;
if constexpr (type == argument_type::optional)
this->_count = 0ull;
this->_ignore_predefined = false;
this->_last_flag_sign = true;
}

/**
* @brief Creates a help message builder object for the argument.
* @param verbose The verbosity mode value.
Expand Down Expand Up @@ -610,6 +622,8 @@ class argument : public typed_argument_base<T> {
/// @brief Mark the optional argument as used.
/// @return `true` if the argument accepts further values, `false` otherwise.
bool mark_used() override {
this->_last_flag_sign = true;
this->_ignore_predefined = false;
if constexpr (type == argument_type::optional) {
++this->_count;
for (const auto& action : this->_flag_actions)
Expand All @@ -622,6 +636,7 @@ class argument : public typed_argument_base<T> {
/// @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 {
this->_last_flag_sign = false;
if constexpr (type == argument_type::optional) {
++this->_count;
for (const auto& action : this->_negative_actions)
Expand Down Expand Up @@ -699,7 +714,8 @@ class argument : public typed_argument_base<T> {
return not this->_default_values.empty();
else
return not this->_default_values.empty()
or (this->is_used() and not this->_implicit_values.empty());
or (this->is_used() and this->_last_flag_sign and not this->_implicit_values.empty()
);
}

/**
Expand All @@ -718,7 +734,7 @@ class argument : public typed_argument_base<T> {
));

if constexpr (type == argument_type::optional) {
if (this->is_used()) {
if (this->is_used() and this->_last_flag_sign) {
if (this->_implicit_values.empty())
throw(std::logic_error(std::format(
"No implicit values specified for argument '{}'.", this->_name.str()
Expand Down Expand Up @@ -899,6 +915,8 @@ class argument : public typed_argument_base<T> {
bool _hidden : 1 = false; ///< The argument's `hidden` attribute value.

// parsing result
bool _last_flag_sign : 1 =
false; ///< Tracks the sign of the last flag used (true for positive, false for negative).
bool _ignore_predefined : 1 =
false; ///< Indicates whether the argument's predefined values should be masked during the current parsing run (typically set by the discard_all state action).

Expand Down
3 changes: 3 additions & 0 deletions include/argon/argument_base.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ class argument_base {
friend class ::argon::argument_parser;

protected:
/// @brief Reset the argument's state, clearing parsed values and resetting counters.
virtual void reset() noexcept = 0;

/// @param verbose The verbosity mode value. If `true` all non-default parameters will be included in the output.
/// @return A help message builder object for the argument.
virtual detail::help_builder help_builder(const bool verbose) const noexcept = 0;
Expand Down
59 changes: 45 additions & 14 deletions include/argon/argument_parser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ class argument_parser {
*/
template <traits::c_forward_range_of<std::string, traits::type_validator::convertible> ArgvRange>
void parse_args(const ArgvRange& argv_rng) {
if (not this->_is_name_resolved)
if (this->_name_res == name_resolution::unresolved)
throw std::logic_error("Dynamic program name must be resolved before calling parsing "
"the program's arguments");

Expand Down Expand Up @@ -808,7 +808,7 @@ class argument_parser {
*/
template <traits::c_forward_range_of<std::string, traits::type_validator::convertible> ArgvRange>
std::vector<std::string> parse_known_args(const ArgvRange& argv_rng) {
if (not this->_is_name_resolved)
if (this->_name_res == name_resolution::unresolved)
throw std::logic_error("Dynamic program name must be resolved before calling parsing "
"the program's arguments");

Expand Down Expand Up @@ -984,6 +984,31 @@ class argument_parser {
return typed_arg->values();
}

/// @brief Reset the state of the parser.
/// @note This function resets the state of the parser and all its arguments and subparsers, but does not reset the parser's configuration.
void reset() noexcept {
// reset own state
if (this->_name_res == name_resolution::dynamically_resolved) {
this->_name.clear();
this->_full_name.clear();
this->_name_res = name_resolution::unresolved;
for (const auto& subparser : this->_subparsers)
subparser->_update_program_name(this->_full_name);
}
this->_invoked = false;
this->_finalized = false;

// reset arguments
for (const auto& arg : this->_positional_args)
arg->reset();
for (const auto& arg : this->_optional_args)
arg->reset();

// recursively reset subparsers
for (const auto& subparser : this->_subparsers)
subparser->reset();
}

/**
* @brief Prints the argument parser's help message to an output stream.
* @param verbose The verbosity mode value.
Expand Down Expand Up @@ -1063,6 +1088,12 @@ class argument_parser {
using arg_token_vec_t = std::vector<detail::argument_token>;
using arg_token_vec_iter_t = typename arg_token_vec_t::const_iterator;

enum class name_resolution : std::uint8_t {
unresolved,
statically_resolved,
dynamically_resolved
};

struct parsing_state {
parsing_state(argument_parser& parser, const bool parse_known_only = false)
: curr_arg(nullptr),
Expand All @@ -1089,21 +1120,21 @@ class argument_parser {
? ""
: std::format("{}{}{}", parent_name, std::string(not parent_name.empty(), ' '), name)
),
_name_res(dynamic ? name_resolution::unresolved : name_resolution::statically_resolved),
_gr_positional_args(add_group("Positional Arguments")),
_gr_optional_args(add_group("Optional Arguments")),
_is_name_resolved(not dynamic) {
if (not this->_is_name_resolved)
return;
_gr_optional_args(add_group("Optional Arguments")) {
if (this->_name_res == name_resolution::statically_resolved) {
if (name.empty())
throw invalid_configuration("The program name cannot be empty!");

if (name.empty())
throw invalid_configuration("The program name cannot be empty!");

if (util::contains_whitespaces(name))
throw invalid_configuration("The program name cannot contain whitespace characters!");
if (util::contains_whitespaces(name))
throw invalid_configuration("The program name cannot contain whitespace characters!"
);
}
}

void _resolve_name(std::string_view path) {
if (this->_is_name_resolved)
if (this->_name_res != name_resolution::unresolved)
return;

const auto pos = path.find_last_of("/\\");
Expand All @@ -1113,7 +1144,7 @@ class argument_parser {
this->_name = "unknown";

this->_full_name = this->_name;
this->_is_name_resolved = true;
this->_name_res = name_resolution::dynamically_resolved;

for (auto& sub : this->_subparsers)
sub->_update_program_name(this->_full_name);
Expand Down Expand Up @@ -1694,6 +1725,7 @@ class argument_parser {

// --- parsing cfg & state ---

name_resolution _name_res = name_resolution::unresolved;
arg_ptr_vec_t _positional_args = {};
arg_ptr_vec_t _optional_args = {};
arg_group_ptr_vec_t _argument_groups = {};
Expand All @@ -1703,7 +1735,6 @@ class argument_parser {

// --- cfg flags ---

bool _is_name_resolved : 1 = false;
bool _verbose : 1 = false;

// --- parsing state flags ---
Expand Down
5 changes: 5 additions & 0 deletions tests/include/argument_test_fixture.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ struct argument_test_fixture {
++arg._parsed_nvalues;
}

template <argument_type ArgT, c_argument_value_type T>
void reset(argument<ArgT, T>& arg) const {
arg.reset();
}

template <argument_type ArgT, c_argument_value_type T>
void reset_values(argument<ArgT, T>& arg) const {
arg._values.clear();
Expand Down
Loading
Loading