diff --git a/README.md b/README.md
index b70e538..745a7d7 100644
--- a/README.md
+++ b/README.md
@@ -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)
diff --git a/docs/tutorial.md b/docs/tutorial.md
index ee086a3..5a285ed 100644
--- a/docs/tutorial.md
+++ b/docs/tutorial.md
@@ -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)
@@ -1901,6 +1902,34 @@ Resolved parser : init (argon-git submodule init)
+## 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.
+
+
+
+
+
## Examples
The library usage examples and demo projects are included in the `cpp-argon-demo` submodule.
diff --git a/include/argon/argument.hpp b/include/argon/argument.hpp
index ba759c0..f782732 100644
--- a/include/argon/argument.hpp
+++ b/include/argon/argument.hpp
@@ -68,18 +68,20 @@ class argument : public typed_argument_base {
* @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) {}
@@ -570,6 +572,16 @@ class argument : public typed_argument_base {
using optional_specific_type =
std::conditional_t;
+ /// @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.
@@ -610,6 +622,8 @@ class argument : public typed_argument_base {
/// @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)
@@ -622,6 +636,7 @@ class argument : public typed_argument_base {
/// @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)
@@ -699,7 +714,8 @@ class argument : public typed_argument_base {
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()
+ );
}
/**
@@ -718,7 +734,7 @@ class argument : public typed_argument_base {
));
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()
@@ -899,6 +915,8 @@ class argument : public typed_argument_base {
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).
diff --git a/include/argon/argument_base.hpp b/include/argon/argument_base.hpp
index d352f62..efea2a5 100644
--- a/include/argon/argument_base.hpp
+++ b/include/argon/argument_base.hpp
@@ -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;
diff --git a/include/argon/argument_parser.hpp b/include/argon/argument_parser.hpp
index 25f2db0..aceed01 100644
--- a/include/argon/argument_parser.hpp
+++ b/include/argon/argument_parser.hpp
@@ -711,7 +711,7 @@ class argument_parser {
*/
template 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");
@@ -808,7 +808,7 @@ class argument_parser {
*/
template ArgvRange>
std::vector 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");
@@ -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.
@@ -1063,6 +1088,12 @@ class argument_parser {
using arg_token_vec_t = std::vector;
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),
@@ -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("/\\");
@@ -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);
@@ -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 = {};
@@ -1703,7 +1735,6 @@ class argument_parser {
// --- cfg flags ---
- bool _is_name_resolved : 1 = false;
bool _verbose : 1 = false;
// --- parsing state flags ---
diff --git a/tests/include/argument_test_fixture.hpp b/tests/include/argument_test_fixture.hpp
index 5c5e0df..6f6e879 100644
--- a/tests/include/argument_test_fixture.hpp
+++ b/tests/include/argument_test_fixture.hpp
@@ -43,6 +43,11 @@ struct argument_test_fixture {
++arg._parsed_nvalues;
}
+ template
+ void reset(argument& arg) const {
+ arg.reset();
+ }
+
template
void reset_values(argument& arg) const {
arg._values.clear();
diff --git a/tests/source/test_argument_parser_parse_args.cpp b/tests/source/test_argument_parser_parse_args.cpp
index af87db6..8235ecd 100644
--- a/tests/source/test_argument_parser_parse_args.cpp
+++ b/tests/source/test_argument_parser_parse_args.cpp
@@ -12,7 +12,7 @@ using argon::unknown_policy;
TEST_SUITE_BEGIN("test_argument_parser_parse_args");
struct test_argument_parser_parse_args : public argument_parser_test_fixture {
- const std::string_view test_program_name = "test program name";
+ const std::string_view test_program_name = "test-program";
const std::size_t no_args = 0ull;
const std::size_t n_positional_args = 3ull;
@@ -2055,4 +2055,145 @@ TEST_CASE_FIXTURE(
free_argv(argc, argv);
}
+// reset
+
+TEST_CASE_FIXTURE(
+ test_argument_parser_parse_args,
+ "reset() should reset parser state to un-invoked and un-finalized"
+) {
+ sut.add_flag("flag");
+
+ std::vector argv_vec{"program", "--flag"};
+ const int argc = static_cast(argv_vec.size());
+ auto argv = to_char_2d_array(argv_vec);
+
+ sut.parse_args(argc, argv);
+
+ REQUIRE(sut.invoked());
+ REQUIRE(sut.finalized());
+
+ sut.reset();
+
+ CHECK_FALSE(sut.invoked());
+ CHECK_FALSE(sut.finalized());
+
+ free_argv(argc, argv);
+}
+
+TEST_CASE_FIXTURE(
+ test_argument_parser_parse_args,
+ "reset() should clear all parsed argument values and usage counts"
+) {
+ sut.add_positional_argument("pos");
+ sut.add_optional_argument("opt", "o").nargs(argon::nargs::any());
+ sut.add_flag("flag", "f");
+
+ std::vector argv_vec{"program", "pos-value", "-o", "10", "20", "--flag", "-f"};
+
+ const int argc = static_cast(argv_vec.size());
+ auto argv = to_char_2d_array(argv_vec);
+
+ sut.parse_args(argc, argv);
+
+ REQUIRE(sut.has_value("pos"));
+ REQUIRE_EQ(sut.values("opt").size(), 2ull);
+ REQUIRE_EQ(sut.count("flag"), 2ull);
+
+ sut.reset();
+
+ CHECK_FALSE(sut.has_value("pos"));
+ CHECK_FALSE(sut.has_value("opt"));
+ CHECK_EQ(sut.count("flag"), 0ull);
+ CHECK_FALSE(sut.is_used("flag"));
+
+ free_argv(argc, argv);
+}
+
+TEST_CASE_FIXTURE(
+ test_argument_parser_parse_args,
+ "reset() should clear the dynamic name resolution state and full names for dynamic parsers"
+) {
+ argon::argument_parser dynamic_parser(argon::dynamic_name);
+ auto& sub_cmd = dynamic_parser.add_subparser("commit");
+
+ std::vector argv_vec{"/usr/bin/git", "commit"};
+ const int argc = static_cast(argv_vec.size());
+ auto argv = to_char_2d_array(argv_vec);
+
+ dynamic_parser.parse_args(argc, argv);
+
+ REQUIRE_EQ(dynamic_parser.name(), "git");
+ REQUIRE_EQ(sub_cmd.full_name(), "git commit");
+
+ dynamic_parser.reset();
+
+ // The name should be un-resolved
+ CHECK(dynamic_parser.name().empty());
+ CHECK(dynamic_parser.full_name().empty());
+
+ // Attempting range-based parsing immediately after reset should throw again
+ std::vector empty_args;
+ CHECK_THROWS_WITH_AS(
+ dynamic_parser.parse_args(empty_args),
+ "Dynamic program name must be resolved before calling parsing the program's arguments",
+ std::logic_error
+ );
+
+ free_argv(argc, argv);
+}
+
+TEST_CASE_FIXTURE(
+ test_argument_parser_parse_args,
+ "reset() should NOT clear names for statically initialized parsers"
+) {
+ argon::argument_parser static_parser(test_program_name);
+ auto& sub_cmd = static_parser.add_subparser("testcmd");
+
+ std::vector argv_vec{"some_random_argv0", "testcmd"};
+ const int argc = static_cast(argv_vec.size());
+ auto argv = to_char_2d_array(argv_vec);
+
+ static_parser.parse_args(argc, argv);
+
+ REQUIRE_EQ(static_parser.name(), test_program_name);
+ REQUIRE_EQ(sub_cmd.full_name(), std::format("{} testcmd", test_program_name));
+
+ static_parser.reset();
+
+ CHECK_EQ(static_parser.name(), test_program_name);
+ CHECK_EQ(sub_cmd.full_name(), std::format("{} testcmd", test_program_name));
+
+ free_argv(argc, argv);
+}
+
+TEST_CASE_FIXTURE(
+ test_argument_parser_parse_args,
+ "reset() should recursively reset all subparsers and argument states"
+) {
+ auto& sub_cmd = sut.add_subparser("sub");
+ sub_cmd.add_flag("subflag");
+
+ std::vector argv_vec{"program", "sub", "--subflag"};
+ const int argc = static_cast(argv_vec.size());
+ auto argv = to_char_2d_array(argv_vec);
+
+ sut.parse_args(argc, argv);
+
+ REQUIRE(sut.invoked());
+ REQUIRE_FALSE(sut.finalized());
+
+ REQUIRE(sub_cmd.invoked());
+ REQUIRE(sub_cmd.finalized());
+ REQUIRE_EQ(sub_cmd.count("subflag"), 1ull);
+
+ sut.reset();
+
+ CHECK_FALSE(sut.invoked());
+ CHECK_FALSE(sub_cmd.invoked());
+ CHECK_FALSE(sub_cmd.finalized());
+ CHECK_EQ(sub_cmd.count("subflag"), 0ull);
+
+ free_argv(argc, argv);
+}
+
TEST_SUITE_END(); // test_argument_parser_parse_args;
diff --git a/tests/source/test_optional_argument.cpp b/tests/source/test_optional_argument.cpp
index 795f2b7..90f5c44 100644
--- a/tests/source/test_optional_argument.cpp
+++ b/tests/source/test_optional_argument.cpp
@@ -783,4 +783,102 @@ TEST_CASE_FIXTURE(
CHECK(std::is_gt(nvalues_ordering(sut)));
}
+TEST_CASE_FIXTURE(
+ argument_test_fixture,
+ "negative flag with discard_parsed should clear parsed values but preserve predefined values"
+) {
+ auto sut = sut_type(arg_name_primary);
+ sut.default_values(default_value);
+ sut.negative("no-", argon::action::discard_parsed);
+
+ set_value(sut, arbitrary_value);
+ REQUIRE(sut.has_parsed_values());
+ REQUIRE_EQ(sut.value(), arbitrary_value);
+
+ mark_negative_used(sut);
+
+ CHECK_FALSE(sut.has_parsed_values());
+ CHECK(sut.has_predefined_values()); // Predefined values are untouched
+ CHECK_EQ(sut.value(), default_value);
+}
+
+TEST_CASE_FIXTURE(
+ argument_test_fixture,
+ "negative flag with discard_all should clear parsed values and mask predefined values"
+) {
+ auto sut = sut_type(arg_name_primary);
+ sut.default_values(default_value);
+ sut.negative("no-", argon::action::discard_all);
+
+ set_value(sut, arbitrary_value);
+ REQUIRE(sut.has_parsed_values());
+ REQUIRE(sut.has_predefined_values());
+
+ mark_negative_used(sut);
+
+ CHECK_FALSE(sut.has_parsed_values());
+ CHECK_FALSE(sut.has_predefined_values()); // _ignore_predefined is now true
+ CHECK_THROWS_AS(discard(sut.value()), std::logic_error);
+}
+
+TEST_CASE_FIXTURE(
+ argument_test_fixture,
+ "reset() should clear parsed values, count, and restore masked predefined values"
+) {
+ auto sut = sut_type(arg_name_primary);
+ sut.default_values(default_value);
+ sut.negative("no-", argon::action::discard_all);
+
+ mark_used(sut);
+ set_value(sut, arbitrary_value);
+ mark_negative_used(sut);
+
+ REQUIRE_EQ(sut.count(), 2ull);
+ REQUIRE_FALSE(sut.has_predefined_values());
+
+ reset(sut); // This should flip _ignore_predefined back to false
+
+ CHECK_EQ(sut.count(), 0ull);
+ CHECK_FALSE(sut.has_parsed_values());
+ CHECK(sut.has_predefined_values()); // Mask is lifted
+ CHECK_EQ(sut.value(), default_value);
+}
+
+TEST_CASE_FIXTURE(
+ argument_test_fixture,
+ "negative boolean flags should automatically deduce and store the inverse of the default value"
+) {
+ SUBCASE("Default is true (e.g., add_flag)") {
+ argon::optional_argument sut(arg_name_primary);
+ sut.default_values(true);
+ sut.negative("no-"); // Automatically sets up discard_parsed + store(true)
+
+ mark_negative_used(sut);
+
+ REQUIRE(sut.has_parsed_values());
+ CHECK_EQ(sut.value(), true);
+ }
+
+ SUBCASE("Default is false (e.g., add_flag)") {
+ argon::optional_argument sut(arg_name_primary);
+ sut.default_values(false);
+ sut.negative("no-"); // Automatically sets up discard_parsed + store(true)
+
+ mark_negative_used(sut);
+
+ REQUIRE(sut.has_parsed_values());
+ CHECK_EQ(sut.value(), false);
+ }
+
+ SUBCASE("No default set (raw optional_argument)") {
+ argon::optional_argument sut(arg_name_primary);
+ sut.negative("no-"); // Fallback inverse is false
+
+ mark_negative_used(sut);
+
+ REQUIRE(sut.has_parsed_values());
+ CHECK_EQ(sut.value(), false);
+ }
+}
+
TEST_SUITE_END(); // test_optional_argument
diff --git a/tests/source/test_positional_argument.cpp b/tests/source/test_positional_argument.cpp
index b99cc04..8950bc7 100644
--- a/tests/source/test_positional_argument.cpp
+++ b/tests/source/test_positional_argument.cpp
@@ -552,4 +552,24 @@ TEST_CASE_FIXTURE(
CHECK(std::is_gt(nvalues_ordering(sut)));
}
+TEST_CASE_FIXTURE(
+ argument_test_fixture, "reset() should clear parsed values and reset the argument state"
+) {
+ auto sut = sut_type(arg_name);
+ sut.default_values(default_value);
+
+ set_value(sut, valid_value);
+
+ REQUIRE(sut.has_parsed_values());
+ REQUIRE_EQ(sut.value(), valid_value);
+ REQUIRE_EQ(sut.count(), 1ull);
+
+ reset(sut);
+
+ CHECK_FALSE(sut.has_parsed_values());
+ CHECK_EQ(sut.count(), 0ull);
+ CHECK(sut.has_predefined_values());
+ CHECK_EQ(sut.value(), default_value);
+}
+
TEST_SUITE_END(); // test_positional_argument