From 3ca421e7cdeb5c0306fa8e0bcbe2888ad3f46ca0 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 11:26:55 +0100 Subject: [PATCH] Report unknown long options by name under rfl::NoExtraFields in rfl::cli With rfl::NoExtraFields, `--nope=1` failed with "Value named 'nope' not used." and `--nope 1` with "Too many positional arguments: ...". The option table now lists every long option, through nested structs, maps and rfl::ExtraFields, so parse_argv rejects both with "Unknown option '--nope'.". Keys of maps and rfl::ExtraFields stay open; the fields of a struct inside a map are known (`--servers.eu.nope` is unknown). Without rfl::NoExtraFields, unknown long options are still ignored. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 12 ++ include/rfl/cli/options.hpp | 238 +++++++++++++++++++++++--- include/rfl/cli/parse_argv.hpp | 7 +- tests/cli/test_unknown_options.cpp | 135 +++++++++++++++ 4 files changed, 363 insertions(+), 29 deletions(-) create mode 100644 tests/cli/test_unknown_options.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index dcb3ed14..5a84037f 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -69,6 +69,18 @@ const auto result = rfl::cli::read(args); `rfl::cli::parse_argv` has the same overloads. +## Unknown options + +By default, long options that match no field are ignored. Pass +`rfl::NoExtraFields` to reject them: + +```cpp +const auto result = rfl::cli::read(argc, argv); +// ./app --nope=1 -> error: Unknown option '--nope'. +``` + +Unknown short options are always an error. + ## Positional arguments Wrap a field with `rfl::Positional` to accept it as a bare (non-flag) argument: diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 7dc338b8..62b3d358 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -10,6 +10,7 @@ #include #include +#include "../Box.hpp" #include "../Generic.hpp" #include "../Positional.hpp" #include "../Short.hpp" @@ -21,6 +22,7 @@ #include "../internal/is_named_tuple.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_short.hpp" +#include "../internal/no_extra_fields_v.hpp" #include "../internal/processed_t.hpp" #include "../parsing/is_string_map.hpp" #include "Parser.hpp" @@ -36,7 +38,7 @@ enum class OptionKind { /// A field that takes a value: `--key=value`, `-k value` or `-k=value`. value, /// A known path whose kind cannot be decided from the type (a nested - /// struct, a map, a variant or rfl::Generic). `--key` + /// struct, a variant, rfl::Generic, or a sub-key of a variant). `--key` /// never takes the next token, so alone it passes an empty value. A short /// alias `-k` takes the next token unless it looks like an option. other, @@ -51,11 +53,13 @@ struct Option { /// The options that a target struct accepts, built from its fields by /// make_options on every read. parse_argv uses it to decide whether a short -/// option takes the next token as its value, and resolve_args to map short -/// aliases and positional arguments to fields. Names are the field names -/// after processors (kebab-case, rfl::Rename) are applied. +/// option takes the next token as its value and whether a long option is +/// known, and resolve_args to map short aliases and positional arguments to +/// fields. Paths are dotted +/// (`database.host`) and use the field names after processors (kebab-case, +/// rfl::Rename) are applied. struct Options { - /// The options of the top-level fields, by name. + /// The long options, by path. std::map long_options; /// The short aliases given by rfl::Short (`p` for `-p`), mapped to the path @@ -66,6 +70,19 @@ struct Options { /// takes one positional argument. std::vector positionals; + /// Prefixes (ending in path_separator, or empty for the root) under which + /// the keys are not known in advance, such as maps and rfl::ExtraFields. + /// Maps to the option of a direct sub-key. + std::map open_prefixes; + + /// For the open prefixes whose sub-keys hold structs or maps: the options + /// inside one such value, with paths relative to it, so that + /// `--servers.eu.port` is looked up as `port`. + std::map> open_prefix_options; + + /// Whether options that match no field are an error (rfl::NoExtraFields). + bool reject_unknown = false; + /// Whether tokens such as `-5` and `-.5` are short options rather than /// negative numbers. They are when parse_argv is called without the /// struct. make_options clears it unless, as in argparse, a short option's @@ -80,7 +97,48 @@ struct Options { /// Returns the long option `--_name`. Option find_long(const std::string& _name) const { const auto it = long_options.find(_name); - return it == long_options.end() ? Option{} : it->second; + if (it != long_options.end()) { + return it->second; + } + + // A key below a leaf field (for example a variant of structs): the + // reader decides what it means. + for (auto pos = _name.find(path_separator); pos != std::string::npos; + pos = _name.find(path_separator, pos + 1)) { + if (long_options.count(_name.substr(0, pos))) { + return Option{OptionKind::other}; + } + } + + // A nested struct or map itself, such as `--database`. + const auto prefix = _name + path_separator; + if (has_prefix(long_options, prefix) || has_prefix(open_prefixes, prefix)) { + return Option{OptionKind::other}; + } + + // A key inside a map or a struct with rfl::ExtraFields. The longest + // matching prefix wins. + const std::pair* open = nullptr; + for (const auto& p : open_prefixes) { + if (_name.size() > p.first.size() && _name.starts_with(p.first) + && (!open || p.first.size() > open->first.size())) { + open = &p; + } + } + if (open) { + const auto rest = _name.substr(open->first.size()); + const auto sep = rest.find(path_separator); + if (sep == std::string::npos) { + return open->second; + } + const auto nested = open_prefix_options.find(open->first); + if (nested != open_prefix_options.end()) { + return nested->second->find_long(rest.substr(sep + 1)); + } + return Option{OptionKind::other}; + } + + return Option{}; } /// Returns the option that the short alias `-_name` stands for. @@ -88,6 +146,14 @@ struct Options { const auto it = short_options.find(_name); return it == short_options.end() ? Option{} : find_long(it->second); } + + private: + static bool has_prefix( + const std::map& _map, const std::string& _prefix + ) { + const auto it = _map.lower_bound(_prefix); + return it != _map.end() && it->first.starts_with(_prefix); + } }; /// Returns true if the token is one of the values that a bool flag given @@ -229,37 +295,121 @@ using option_fields_t = typename std::conditional_t< rfl::internal::is_named_tuple_v, std::type_identity, rfl::internal::Processed>::type; -/// Adds the option of the top-level field `_name` of type T. +template +struct type_list { + template + static constexpr bool contains = (std::is_same_v || ...); + + template + using add = type_list; +}; + +/// The option for a field, or a key of a map or of rfl::ExtraFields, with +/// values of type T. template -void add_option(const std::string& _name, Options* _options) { +Option option_for() { using U = unwrapped_option_t; if constexpr (std::is_same_v) { - _options->long_options[_name] = Option{OptionKind::flag}; + return Option{OptionKind::flag}; } - else if constexpr (is_open_option_v || parsing::is_string_map_v - || is_option_struct_v) { - _options->long_options[_name] = Option{OptionKind::other}; + else if constexpr (parsing::is_string_map_v || is_option_struct_v + || is_open_option_v) { + return Option{OptionKind::other}; } else { - _options->long_options[_name] = Option{OptionKind::value}; + return Option{OptionKind::value}; } } -template -void add_option_for_field(Options* _options) { +template +void collect_options(const std::string& _prefix, Options* _options); + +template +void collect_value_options(Options* _options); + +/// Adds the open prefix `_prefix` of a map or of rfl::ExtraFields with +/// values of type T. If the values are structs or maps, also adds the +/// options inside one of them. +template +void add_open_prefix(const std::string& _prefix, Options* _options) { + using U = unwrapped_option_t; + _options->open_prefixes[_prefix] = option_for(); + if constexpr (parsing::is_string_map_v + || (is_option_struct_v + && !VisitedType::template contains)) { + auto nested = rfl::Box::make(); + collect_value_options(nested.get()); + _options->open_prefix_options.insert_or_assign(_prefix, std::move(nested)); + } +} + +/// Adds the options inside one value of type T to `_options`, with paths +/// relative to it: the fields of a struct, or the keys of a map. +template +void collect_value_options(Options* _options) { + using U = unwrapped_option_t; + if constexpr (parsing::is_string_map_v) { + add_open_prefix( + "", _options); + } + else if constexpr (is_option_struct_v) { + collect_options("", _options); + } + else { + _options->open_prefixes[""] = Option{OptionKind::other}; + } +} + +template +void add_option(const std::string& _path, Options* _options) { + using U = unwrapped_option_t; + if constexpr (std::is_same_v) { + _options->long_options[_path] = Option{OptionKind::flag}; + } + else if constexpr (is_open_option_v) { + _options->long_options[_path] = Option{OptionKind::other}; + } + else if constexpr (parsing::is_string_map_v) { + add_open_prefix( + _path + path_separator, _options); + } + else if constexpr (is_option_struct_v) { + if constexpr (VisitedType::template contains) { + // A recursive type: stop here and let the reader handle deeper keys. + _options->open_prefixes[_path + path_separator] = + Option{OptionKind::other}; + } + else { + collect_options( + _path + path_separator, _options); + } + } + else { + _options->long_options[_path] = Option{OptionKind::value}; + } +} + +template +void add_option_for_field(const std::string& _prefix, Options* _options) { using T = std::remove_cvref_t; - if constexpr (!rfl::internal::is_extra_fields_v) { - add_option(std::string(FieldType::name()), _options); + if constexpr (rfl::internal::is_extra_fields_v) { + add_open_prefix( + _prefix, _options); + } + else { + add_option( + _prefix + std::string(FieldType::name()), _options); } } -/// Adds the options of the top-level fields of T. -template -void collect_options(Options* _options) { +template +void collect_options(const std::string& _prefix, Options* _options) { using NT = option_fields_t; + using NextVisitedType = typename VisitedType::template add; [&](std::index_sequence<_is...>) { - (add_option_for_field, - ProcessorsType>(_options), + (add_option_for_field< + rfl::tuple_element_t<_is, typename NT::Fields>, ProcessorsType, + NextVisitedType>(_prefix, _options), ...); }(std::make_index_sequence()); } @@ -292,18 +442,50 @@ void collect_short_and_positional(Options* _options) { }(std::make_index_sequence()); } -/// Derives the options that T accepts from its fields: the option of every -/// top-level field, with whether it is a flag or takes a value, and the -/// rfl::Short aliases and rfl::Positional fields. +template +void add_top_level_option(Options* _options) { + using T = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + _options->long_options[std::string(FieldType::name())] = + option_for(); + } +} + +/// Adds the options of the top-level fields of T, which is all that short +/// options need. +template +void collect_top_level_options(Options* _options) { + using NT = option_fields_t; + [&](std::index_sequence<_is...>) { + (add_top_level_option, + ProcessorsType>(_options), + ...); + }(std::make_index_sequence()); +} + +/// Derives the options that T accepts from its fields: the long options, +/// with whether each is a flag or takes a value, and the rfl::Short aliases +/// and rfl::Positional fields of the top-level struct. /// @tparam T The target struct type /// @tparam ProcessorsType The processors applied to the struct -/// @return The options -template +/// @tparam _all_paths Whether to list every long option through nested +/// structs, maps and rfl::ExtraFields, rather than only the top-level fields. +/// Only rfl::NoExtraFields needs them all, to reject unknown options. +/// @return The options, with reject_unknown set if ProcessorsType contains +/// rfl::NoExtraFields +template > Options make_options() { Options options; + options.reject_unknown = rfl::internal::no_extra_fields_v; using U = unwrapped_option_t; + if constexpr (_all_paths) { + collect_value_options>(&options); + } + else if constexpr (is_option_struct_v) { + collect_top_level_options(&options); + } if constexpr (is_option_struct_v) { - collect_options(&options); collect_short_and_positional(&options); } // As in argparse, -5 is a negative number unless a short option's name diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 76fce449..ba77cccd 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -46,7 +46,8 @@ namespace internal { /// fails if there is none. A bool flag consumes it only if it is "true", /// "false", "1" or "0". Short options missing from `_options` consume it /// unless it looks like an option, as they do without `_options`. Long -/// options never consume it. +/// options never consume it. With `_options.reject_unknown`, a long option +/// that matches no field is an error. /// A token that looks like a negative number (-5, -.5) is a positional /// argument unless `_options.negative_numbers_are_options` is set, as it is /// without `_options` and when the struct has a short option whose name @@ -135,6 +136,10 @@ inline rfl::Result parse_string_views( if (key.empty()) { return error("Empty key in argument: " + std::string(arg_raw)); } + const auto option = _options.find_long(key); + if (option.kind == OptionKind::unknown && _options.reject_unknown) { + return error("Unknown option '--" + key + "'."); + } if (!result.named.emplace(std::move(key), std::move(val)).second) { return error("Duplicate argument: " + std::string(arg_raw)); } diff --git a/tests/cli/test_unknown_options.cpp b/tests/cli/test_unknown_options.cpp new file mode 100644 index 00000000..08eb96b6 --- /dev/null +++ b/tests/cli/test_unknown_options.cpp @@ -0,0 +1,135 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_unknown_options { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +struct Database { + std::string host; + int port; + std::optional ssl; +}; + +struct Query { + std::string sql; + std::optional verbose; + rfl::Positional input_file; +}; + +TEST(cli, test_long_unknown_option_no_extra_fields) { + for (const auto& args : std::vector>{ + {"--sql=x", "--nope", "1", "in.txt"}, + {"--sql=x", "--nope=1", "in.txt"}, + {"--sql=x", "in.txt", "--nope"}, + {"--nope", "--sql=x", "in.txt"}}) { + const auto result = read(args); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), "Unknown option '--nope'."); + } +} + +struct WithDatabase { + std::string sql; + Database database; +}; + +TEST(cli, test_long_unknown_nested_option_no_extra_fields) { + const auto result = read( + {"--sql=x", "--database.host=h", "--database.port=1", "--database.nope", + "1"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Unknown option '--database.nope'."); +} + +struct Flags { + bool verbose; + std::optional dry_run; + rfl::Short<"q", std::optional> quiet; + rfl::Description<"Colorize output", std::optional> color; + Database database; + rfl::Positional input_file; +}; + +TEST(cli, test_long_known_options_no_extra_fields) { + const auto result = read( + {"--verbose", "in.txt", "--database.host=h", "--database.port=1", "-q"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().verbose); + EXPECT_EQ(result.value().quiet(), true); + EXPECT_EQ(result.value().database.host, "h"); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +struct Server { + std::string host; + int port; +}; + +struct WithMaps { + std::map labels; + std::map servers; + rfl::Positional input_file; +}; + +TEST(cli, test_unknown_option_map_keys) { + // Any key of a map is an option, but the fields of a struct in a map are + // known. + const auto result = read( + {"--labels.env=prod", "--servers.eu.host=h", "--servers.eu.port=1", + "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().labels.at("env"), "prod"); + EXPECT_EQ(result.value().servers.at("eu").port, 1); + + const auto unknown = read( + {"--servers.eu.nope=1", "in.txt"}); + ASSERT_FALSE(unknown); + EXPECT_EQ(std::string(unknown.error().what()), + "Unknown option '--servers.eu.nope'."); +} + +struct WithExtraFields { + std::string name; + rfl::ExtraFields extra; +}; + +TEST(cli, test_extra_fields_no_extra_fields) { + // rfl::ExtraFields takes every option that matches no other field. + const auto result = read( + {"--name=a", "--color=red"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().name, "a"); + EXPECT_EQ(result.value().extra.at("color"), "red"); +} + +struct Node { + std::string name; + std::optional> child; +}; + +TEST(cli, test_unknown_option_recursive_struct) { + const auto known = read( + {"--name=a", "--child.name=b"}); + ASSERT_TRUE(known) << known.error().what(); + EXPECT_EQ(known.value().child.value()->name, "b"); + + const auto unknown = + read({"--name=a", "--nope=1"}); + ASSERT_FALSE(unknown); + EXPECT_EQ(std::string(unknown.error().what()), "Unknown option '--nope'."); +} + +} // namespace test_unknown_options