From 603a9b5c5fa4dbc9a6df19448c0e300f0d181cd6 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 09:52:12 +0100 Subject: [PATCH 1/3] Accept `--key value` for long options that take a value parse_argv did not know the target struct, so a long option only took a value after '='. `--sql "SELECT 1"` set sql to an empty string and passed "SELECT 1" on as a positional argument, which usually failed with "Too many positional arguments". rfl::cli::read now derives a LongOptions table from the struct (make_long_options) and passes it to parse_argv. The table lists the dotted paths of the boolean fields and of the fields that take a value, named as after the processors, through nested structs and rfl::NamedTuples, the struct values of maps, rfl::Flatten and the rfl wrappers. A long option that takes a value consumes the next token unless that token looks like an option, and fails with "Missing value for option '--sql'." if there is none. A boolean flag never consumes the next token, as before, so `--verbose input.txt` and `--force 0` still pass input.txt and 0 as positional arguments. Neither does a variant or rfl::Generic, which may hold a bool, so `--mode` alone still parses. With rfl::NoExtraFields, a long option that matches no field now fails with "Unknown option '--nope'.". Before, `--nope 1` reported "Too many positional arguments" instead. Without NoExtraFields, unknown options are still ignored and do not consume the next token. parse_argv called without a LongOptions table behaves as before. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 51 ++- include/rfl/cli.hpp | 1 + include/rfl/cli/long_options.hpp | 365 +++++++++++++++++ include/rfl/cli/parse_argv.hpp | 108 +++-- include/rfl/cli/read.hpp | 36 +- tests/cli/test_long_option_values.cpp | 552 ++++++++++++++++++++++++++ 6 files changed, 1074 insertions(+), 39 deletions(-) create mode 100644 include/rfl/cli/long_options.hpp create mode 100644 tests/cli/test_long_option_values.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 93a1084b8..542df703e 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -79,6 +79,47 @@ first positional value. `rfl::cli::parse_argv` has the same overloads. +## Long options + +A long option takes its value either after `=` or as the next token: + +``` +./app --host-name=localhost --port=8080 --verbose --tags=a,b,c +./app --host-name localhost --port 8080 --verbose --tags a,b,c --rate -0.5 +``` + +This works for every field that takes a value: nested fields +(`--database.host db.local`, also inside an `rfl::NamedTuple`), vectors, +enums, numbers, optionals, map entries (`--labels.env prod`, or +`--servers.eu.port 8080` for a map of structs), fields inlined by +`rfl::Flatten`, and fields wrapped in `rfl::Short`, `rfl::Positional`, +`rfl::Rename`, `rfl::Description`, `rfl::Validator` or `rfl::DefaultVal`. +A `std::variant`, `rfl::Variant`, `rfl::TaggedUnion` or `rfl::Generic` +may hold a bool, so its option never takes the next token: pass its value +with `=`. Alone, `--key` passes an empty value (`true` for a bool). + +The next token is the value unless it looks like an option (`-` followed by +a letter), so negative numbers such as `--offset -5` work. If the value is +missing, parsing fails with `Missing value for option '--sql'.` Use `=` to +pass an empty value or one that starts with `-`: `--sql=`, `--pattern=-x`. + +Boolean fields (`bool`, `std::optional` and wrapped bools) are flags +and never consume the next token: `--verbose input.txt` sets `verbose` and +passes `input.txt` as a positional argument, and so does `--verbose 0` with +`0`. To set a flag to `false`, write `--verbose=false`. + +## Unknown options + +By default, long options that match no field are ignored, and they do not +consume the next token. 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: @@ -176,9 +217,12 @@ leaving out `-o` gives `"out"`. Parsing proceeds in three stages: 1. **`parse_argv`** — categorizes raw tokens into `named`, `short_args`, - and `positional` buckets (`ParsedArgs` struct). No type information - needed, except that `rfl::cli::read` tells it whether a short option's - name looks like a number. On its own, it reads `-5` as a short option. + and `positional` buckets (`ParsedArgs` struct). It is given a + `LongOptions` table derived from the target struct + (`make_long_options()`), which says which long options + are flags and which take a value, so that `--key value` works, and + whether a short option's name looks like a number. Without the table, it + reads `-5` as a short option. 2. **`resolve_args`** — uses compile-time metadata from the target struct to map short aliases to long names, reclaim values from bool short flags, and merge positional arguments. Produces a flat `map`. @@ -192,6 +236,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/Reader.hpp` — Reader + `parse_value` overloads - `include/rfl/cli/Parser.hpp` — Parser type alias - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` +- `include/rfl/cli/long_options.hpp` — `LongOptions`: which long options take a value - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 763f335b0..b6e8f63a7 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -4,6 +4,7 @@ #include "../rfl.hpp" #include "cli/Parser.hpp" #include "cli/Reader.hpp" +#include "cli/long_options.hpp" #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" diff --git a/include/rfl/cli/long_options.hpp b/include/rfl/cli/long_options.hpp new file mode 100644 index 000000000..af69d99a7 --- /dev/null +++ b/include/rfl/cli/long_options.hpp @@ -0,0 +1,365 @@ +#ifndef RFL_CLI_LONG_OPTIONS_HPP_ +#define RFL_CLI_LONG_OPTIONS_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Tuple.hpp" +#include "../internal/has_reflection_type_v.hpp" +#include "../internal/has_reflector.hpp" +#include "../internal/is_extra_fields.hpp" +#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" +#include "Reader.hpp" + +namespace rfl::cli { + +/// What a long option does with the token that follows it. +enum class LongOptionKind { + /// A boolean field: `--flag`. Never consumes the next token. + flag, + /// A field that takes a value: `--key value` or `--key=value`. + value, + /// A known path whose kind cannot be decided from the type (a nested + /// struct, a variant, rfl::Generic, or a sub-key of a variant). Never + /// consumes the next token, so `--key` alone passes an empty value. + other, + /// No field matches this option. + unknown +}; + +/// The long options that a target struct accepts, derived from its fields at +/// compile time. Lets parse_argv decide whether `--key` takes the next token +/// as its value. Paths are dotted (`database.host`) and use the field names +/// after processors (kebab-case, rfl::Rename) are applied. +struct LongOptions { + /// Paths of boolean fields. + std::set flags; + + /// Paths of fields that take a value. + std::set values; + + /// Paths of fields that may or may not need a value, depending on what + /// they hold (variants, rfl::Generic). + std::set others; + + /// 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 kind of a direct sub-key. + std::map open_prefixes; + + /// For the open prefixes whose sub-keys hold structs or maps: the long + /// 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; + + /// Returns the kind of the long option `--_key`. + LongOptionKind kind_of(const std::string& _key) const { + if (flags.count(_key)) { + return LongOptionKind::flag; + } + if (values.count(_key)) { + return LongOptionKind::value; + } + if (others.count(_key)) { + return LongOptionKind::other; + } + + // A key below a leaf field (for example a variant of structs): the + // reader decides what it means. + for (auto pos = _key.find(path_separator); pos != std::string::npos; + pos = _key.find(path_separator, pos + 1)) { + const auto parent = _key.substr(0, pos); + if (flags.count(parent) || values.count(parent) + || others.count(parent)) { + return LongOptionKind::other; + } + } + + // A nested struct or map itself, such as `--database`. + const auto prefix = _key + path_separator; + if (has_prefix(flags, prefix) || has_prefix(values, prefix) + || has_prefix(others, prefix) || has_prefix(open_prefixes, prefix)) { + return LongOptionKind::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 (_key.size() > p.first.size() && _key.starts_with(p.first) + && (!open || p.first.size() > open->first.size())) { + open = &p; + } + } + if (open) { + const auto rest = _key.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->kind_of(rest.substr(sep + 1)); + } + return LongOptionKind::other; + } + + return LongOptionKind::unknown; + } + + private: + template + static bool has_prefix( + const ContainerType& _container, const std::string& _prefix + ) { + const auto it = _container.lower_bound(_prefix); + if (it == _container.end()) { + return false; + } + if constexpr (std::is_same_v>) { + return it->starts_with(_prefix); + } + else { + return it->first.starts_with(_prefix); + } + } +}; + +namespace internal { + +template +struct type_list { + template + static constexpr bool contains = (std::is_same_v || ...); + + template + using add = type_list; +}; + +/// Strips everything that does not change how a field is written on the +/// command line: optionals, pointers, rfl::Short, rfl::Positional, +/// rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a ReflectionType +/// (rfl::Validator, rfl::Description, rfl::Literal, ...), reflectors and +/// custom parsers. +template +auto unwrap_option_type() { + using U = std::remove_cvref_t; + if constexpr (std::is_pointer_v) { + return unwrap_option_type, ProcessorsType>(); + } + else if constexpr (parsing::is_optional_v) { + return unwrap_option_type(); + } + else if constexpr (parsing::is_unique_ptr_v + || parsing::is_shared_ptr_v) { + return unwrap_option_type(); + } + else if constexpr (parsing::is_box_v) { + return unwrap_option_type< + typename parsing::is_box::element_type, ProcessorsType>(); + } + else if constexpr (parsing::is_ref_v) { + return unwrap_option_type< + typename parsing::is_ref::element_type, ProcessorsType>(); + } + else if constexpr (rfl::internal::is_short_v + || rfl::internal::is_positional_v + || parsing::is_rename_v + || parsing::is_default_val_v + || parsing::is_skip_v) { + return unwrap_option_type(); + } + else if constexpr (rfl::internal::has_reflection_type_v) { + return unwrap_option_type(); + } + else if constexpr (rfl::internal::has_read_reflector) { + return unwrap_option_type< + typename Reflector::ReflType, ProcessorsType>(); + } + else if constexpr (requires { + typename Parser:: + CustomParserHelperStruct; + }) { + return unwrap_option_type< + typename Parser::CustomParserHelperStruct, + ProcessorsType>(); + } + else { + return std::type_identity{}; + } +} + +template +using unwrapped_option_t = + typename decltype(unwrap_option_type())::type; + +/// Whether the reader treats T as a struct whose fields are addressed as +/// `--field.sub-field`. +template +constexpr bool is_option_struct_v = + (std::is_class_v && std::is_aggregate_v && !parsing::is_array_v + && !parsing::is_rfl_array_v) + || rfl::internal::is_named_tuple_v; + +/// Whether an option for T may or may not need a value, depending on what +/// it holds: a variant or rfl::Generic can be a bool or a struct. Such an +/// option never takes the next token. +template +constexpr bool is_open_option_v = + parsing::is_variant_v || parsing::is_rfl_variant_v + || parsing::is_tagged_union_v || std::is_same_v; + +/// The NamedTuple whose fields are the options of the struct T: T itself if +/// it is an rfl::NamedTuple (whose names the processors leave alone), or T +/// with the processors applied. +template +using option_fields_t = typename std::conditional_t< + rfl::internal::is_named_tuple_v, std::type_identity, + rfl::internal::Processed>::type; + +template +constexpr LongOptionKind sub_key_kind() { + using U = unwrapped_option_t; + if constexpr (std::is_same_v) { + return LongOptionKind::flag; + } + else if constexpr (parsing::is_string_map_v || is_option_struct_v + || is_open_option_v) { + return LongOptionKind::other; + } + else { + return LongOptionKind::value; + } +} + +template +void collect_long_options(const std::string& _prefix, LongOptions* _options); + +template +void collect_value_long_options(LongOptions* _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 long +/// options inside one of them. +template +void add_open_prefix(const std::string& _prefix, LongOptions* _options) { + using U = unwrapped_option_t; + _options->open_prefixes[_prefix] = sub_key_kind(); + if constexpr (parsing::is_string_map_v + || (is_option_struct_v + && !VisitedType::template contains)) { + auto nested = std::make_shared(); + collect_value_long_options(nested.get()); + _options->open_prefix_options[_prefix] = std::move(nested); + } +} + +template +void add_long_option(const std::string& _path, LongOptions* _options) { + using U = unwrapped_option_t; + if constexpr (std::is_same_v) { + _options->flags.insert(_path); + } + else if constexpr (is_open_option_v) { + _options->others.insert(_path); + } + 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] = LongOptionKind::other; + } + else { + collect_long_options( + _path + path_separator, _options); + } + } + else { + _options->values.insert(_path); + } +} + +template +void add_long_option_for_field( + const std::string& _prefix, LongOptions* _options +) { + using T = std::remove_cvref_t; + if constexpr (rfl::internal::is_extra_fields_v) { + add_open_prefix( + _prefix, _options); + } + else { + add_long_option( + _prefix + std::string(FieldType::name()), _options); + } +} + +template +void collect_long_options(const std::string& _prefix, LongOptions* _options) { + using NT = option_fields_t; + using NextVisitedType = typename VisitedType::template add; + [&](std::index_sequence<_is...>) { + (add_long_option_for_field< + rfl::tuple_element_t<_is, typename NT::Fields>, ProcessorsType, + NextVisitedType>(_prefix, _options), + ...); + }(std::make_index_sequence()); +} + +/// Adds the long 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_long_options(LongOptions* _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_long_options("", _options); + } + else { + _options->open_prefixes[""] = LongOptionKind::other; + } +} + +} // namespace internal + +/// Derives the long options that T accepts from its fields. +/// @tparam T The target struct type +/// @tparam ProcessorsType The processors applied to the struct +/// @return The long options, with reject_unknown set if ProcessorsType +/// contains rfl::NoExtraFields +template +LongOptions make_long_options() { + LongOptions options; + options.reject_unknown = + rfl::internal::no_extra_fields_v; + internal::collect_value_long_options>(&options); + return options; +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 6991abe52..aeeafe61d 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -15,6 +15,7 @@ #include "../Result.hpp" #include "../internal/strings/utf8_conversions.hpp" +#include "long_options.hpp" #include "resolve_args.hpp" namespace rfl::cli { @@ -35,23 +36,27 @@ namespace internal { /// Parses command-line arguments into categorized buckets. /// Handles three types of arguments: -/// - Long options: --key=value or --flag (stored in `named`) +/// - Long options: --key=value, --key value or --flag (stored in `named`) /// - Short options: -x value, -x=value, or -x (stored in `short_args`) /// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`) /// The special argument "--" forces all subsequent arguments to be treated as positional. +/// `_long_options` says which long options take a value. A long option that +/// takes a value consumes the next token when it is given without '='. +/// Others, boolean flags among them, never consume it. /// Every element of `_args` is parsed; nothing is skipped as the program name. /// A token that looks like a negative number (-5, -.5) is a positional /// argument unless `_negative_numbers_are_options` is true, as it is when the /// target struct has a short option whose name looks like a number /// (rfl::Short<"1", ...>). Then such tokens are short options, as in argparse. /// @param _args The command-line arguments to parse +/// @param _long_options The long options of the target struct /// @return A Result containing ParsedArgs with categorized arguments or an error -/// --key=value / --flag → named +/// --key=value / --key value / --flag → named /// -x value / -x=value / -x → short_args /// bare arguments → positional /// -- → everything after goes to positional inline rfl::Result parse_string_views( - std::span _args, + std::span _args, const LongOptions& _long_options, bool _negative_numbers_are_options) { ParsedArgs result; @@ -79,17 +84,30 @@ inline rfl::Result parse_string_views( continue; } - // Long argument: --key=value or --flag. + // Long argument: --key=value, --key value or --flag. if (arg_raw.starts_with("--")) { const auto arg = arg_raw.substr(2); const auto eq = arg.find('='); auto key = std::string( eq == std::string_view::npos ? arg : arg.substr(0, eq)); - auto val = std::string( - eq == std::string_view::npos ? "" : arg.substr(eq + 1)); if (key.empty()) { return error("Empty key in argument: " + std::string(arg_raw)); } + const auto kind = _long_options.kind_of(key); + if (kind == LongOptionKind::unknown && _long_options.reject_unknown) { + return error("Unknown option '--" + key + "'."); + } + auto val = std::string(); + if (eq != std::string_view::npos) { + val = std::string(arg.substr(eq + 1)); + } + else if (kind == LongOptionKind::value) { + // --key value + if (i + 1 >= _args.size() || looks_like_option(_args[i + 1])) { + return error("Missing value for option '--" + key + "'."); + } + val = std::string(_args[++i]); + } if (!result.named.emplace(std::move(key), std::move(val)).second) { return error("Duplicate argument: " + std::string(arg_raw)); } @@ -172,6 +190,7 @@ bool is_null(const S& _str) noexcept { /// `_first_index` is the index of the first element in error messages. template rfl::Result parse_strings(R&& _args, size_t _first_index, + const LongOptions& _long_options, bool _negative_numbers_are_options) { std::vector views; auto i = _first_index; @@ -183,14 +202,16 @@ rfl::Result parse_strings(R&& _args, size_t _first_index, views.push_back(view); ++i; } - return parse_string_views(views, _negative_numbers_are_options); + return parse_string_views(views, _long_options, + _negative_numbers_are_options); } /// Converts every element of `_args` to UTF-8 and parses it. /// `_first_index` is the index of the first element in error messages. template -rfl::Result parse_wide_strings( - R&& _args, size_t _first_index, bool _negative_numbers_are_options) { +rfl::Result parse_wide_strings(R&& _args, size_t _first_index, + const LongOptions& _long_options, + bool _negative_numbers_are_options) { std::vector narrow; auto i = _first_index; for (auto&& arg : _args) { @@ -206,7 +227,8 @@ rfl::Result parse_wide_strings( narrow.emplace_back(std::move(*str)); ++i; } - return parse_strings(narrow, _first_index, _negative_numbers_are_options); + return parse_strings(narrow, _first_index, _long_options, + _negative_numbers_are_options); } /// Validates argc/argv and returns the arguments after argv[0], the program @@ -223,31 +245,35 @@ rfl::Result> skip_program_name( return std::span(argv + 1, static_cast(argc - 1)); } -/// Parses every element of `_args`, as parse_argv(_args) does. +/// Parses every element of `_args`, as parse_argv(_args, _long_options) does. /// `_negative_numbers_are_options` is as for parse_string_views. template requires StringRange || WideStringRange -rfl::Result parse_args(R&& _args, +rfl::Result parse_args(R&& _args, const LongOptions& _long_options, bool _negative_numbers_are_options) { if constexpr (StringRange) { - return parse_strings(std::forward(_args), 0, + return parse_strings(std::forward(_args), 0, _long_options, _negative_numbers_are_options); } else { - return parse_wide_strings(std::forward(_args), 0, + return parse_wide_strings(std::forward(_args), 0, _long_options, _negative_numbers_are_options); } } -/// Parses argc/argv, skipping argv[0], as parse_argv(argc, argv) does. +/// Parses argc/argv, skipping argv[0], as parse_argv(argc, argv, +/// _long_options) does. /// `_negative_numbers_are_options` is as for parse_string_views. template rfl::Result parse_args(int argc, const CharT* const argv[], + const LongOptions& _long_options, bool _negative_numbers_are_options) { return skip_program_name(argc, argv).and_then([&](auto _args) { if constexpr (std::is_same_v) { - return parse_strings(_args, 1, _negative_numbers_are_options); + return parse_strings(_args, 1, _long_options, + _negative_numbers_are_options); } else { - return parse_wide_strings(_args, 1, _negative_numbers_are_options); + return parse_wide_strings(_args, 1, _long_options, + _negative_numbers_are_options); } }); } @@ -260,24 +286,49 @@ rfl::Result parse_args(int argc, const CharT* const argv[], /// must be multi-pass and must not yield temporary `std::string`s, as for /// rfl::cli::read. Every element is parsed: unlike the argc/argv overloads, /// the first one is NOT skipped as the program name. -/// Without the target struct, a token such as -5 or -.5 is a short option. -/// rfl::cli::read, which knows the struct, reads it as a negative number -/// unless the struct has a short option like rfl::Short<"1", ...>. +/// A token such as -5 or -.5 is a negative number, so a positional argument. +/// @param _args The command-line arguments to parse +/// @param _long_options The long options of the target struct +/// @return A Result containing ParsedArgs with categorized arguments or an error +template > + requires internal::StringRange || internal::WideStringRange +rfl::Result parse_argv(R&& _args, + const LongOptions& _long_options) { + return internal::parse_args(std::forward(_args), _long_options, false); +} + +/// Parses a sequence of command-line arguments without knowing the target +/// struct. Long options never consume the next token, so values must be +/// passed as --key=value. A token such as -5 or -.5 is a short option, as it +/// always was in parse_argv(argc, argv). /// @param _args The command-line arguments to parse /// @return A Result containing ParsedArgs with categorized arguments or an error template > requires internal::StringRange || internal::WideStringRange rfl::Result parse_argv(R&& _args) { - return internal::parse_args(std::forward(_args), true); + return internal::parse_args(std::forward(_args), LongOptions{}, true); } /// Parses command-line arguments into categorized buckets, skipping argv[0] /// (the program name). /// @param argc Number of command-line arguments /// @param argv Array of command-line argument strings +/// @param _long_options The long options of the target struct +/// @return A Result containing ParsedArgs with categorized arguments or an error +inline rfl::Result parse_argv(int argc, const char* const argv[], + const LongOptions& _long_options) { + return internal::parse_args(argc, argv, _long_options, false); +} + +/// Parses command-line arguments without knowing the target struct, +/// skipping argv[0] (the program name). Long options never consume the next +/// token, so values must be passed as --key=value. A token such as -5 or -.5 +/// is a short option. +/// @param argc Number of command-line arguments +/// @param argv Array of command-line argument strings /// @return A Result containing ParsedArgs with categorized arguments or an error inline rfl::Result parse_argv(int argc, const char* const argv[]) { - return internal::parse_args(argc, argv, true); + return internal::parse_args(argc, argv, LongOptions{}, true); } inline rfl::Result parse_argv(int argc, char* argv[]) { @@ -288,10 +339,21 @@ inline rfl::Result parse_argv(int argc, char* argv[]) { /// skipping argv[0] (the program name). Converts each wide string to UTF-8. /// @param argc Number of wide-character command-line arguments /// @param argv Array of wide-character command-line argument strings +/// @param _long_options The long options of the target struct +/// @return A Result containing ParsedArgs with UTF-8 encoded arguments +inline rfl::Result parse_argv(int argc, const wchar_t* const argv[], + const LongOptions& _long_options) { + return internal::parse_args(argc, argv, _long_options, false); +} + +/// Parses wide-character command-line arguments without knowing the target +/// struct. See the narrow overload. +/// @param argc Number of wide-character command-line arguments +/// @param argv Array of wide-character command-line argument strings /// @return A Result containing ParsedArgs with UTF-8 encoded arguments inline rfl::Result parse_argv(int argc, const wchar_t* const argv[]) { - return internal::parse_args(argc, argv, true); + return internal::parse_args(argc, argv, LongOptions{}, true); } inline rfl::Result parse_argv(int argc, wchar_t* argv[]) { diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index d9883f07e..786bd2fcb 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -9,6 +9,7 @@ #include "../SnakeCaseToKebabCase.hpp" #include "Parser.hpp" #include "Reader.hpp" +#include "long_options.hpp" #include "parse_argv.hpp" #include "resolve_args.hpp" @@ -26,11 +27,14 @@ constexpr bool negative_numbers_are_options() { return has_numeric_short_name(std::make_index_sequence{}); } -/// Turns categorized arguments into a struct. -template -rfl::Result read_parsed(ParsedArgs _parsed) { +/// Categorizes the arguments with `_parse`, which takes the long options of +/// T (see make_long_options) and returns ParsedArgs, and turns them into a +/// struct. +template +rfl::Result parse_and_read(const ParseFn& _parse) { using ProcessorsType = Processors; - return resolve_args(std::move(_parsed)) + return _parse(make_long_options()) + .and_then(resolve_args) .and_then([](auto _args) -> rfl::Result { const auto r = Reader(); const auto var = CliVarType{&_args, "", std::nullopt}; @@ -67,9 +71,11 @@ template > requires internal::StringRange || internal::WideStringRange rfl::Result read(R&& _args) { - return internal::parse_args(std::forward(_args), - internal::negative_numbers_are_options()) - .and_then(internal::read_parsed); + return internal::parse_and_read([&](const auto& _options) { + return internal::parse_args( + std::forward(_args), _options, + internal::negative_numbers_are_options()); + }); } /// Parses command-line arguments into a struct using reflection. @@ -82,9 +88,11 @@ rfl::Result read(R&& _args) { /// @return A Result containing the parsed struct or an error template rfl::Result read(int argc, const char* const argv[]) { - return internal::parse_args(argc, argv, - internal::negative_numbers_are_options()) - .and_then(internal::read_parsed); + return internal::parse_and_read([&](const auto& _options) { + return internal::parse_args( + argc, argv, _options, + internal::negative_numbers_are_options()); + }); } template @@ -102,9 +110,11 @@ rfl::Result read(int argc, char* argv[]) { /// @return A Result containing the parsed struct or an error template rfl::Result read(int argc, const wchar_t* const argv[]) { - return internal::parse_args(argc, argv, - internal::negative_numbers_are_options()) - .and_then(internal::read_parsed); + return internal::parse_and_read([&](const auto& _options) { + return internal::parse_args( + argc, argv, _options, + internal::negative_numbers_are_options()); + }); } template diff --git a/tests/cli/test_long_option_values.cpp b/tests/cli/test_long_option_values.cpp new file mode 100644 index 000000000..742e37c64 --- /dev/null +++ b/tests/cli/test_long_option_values.cpp @@ -0,0 +1,552 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_long_option_values { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +enum class Color { red, green, blue }; + +struct Database { + std::string host; + int port; + std::optional ssl; +}; + +struct Config { + std::string sql; + int offset; + double rate; + std::vector tags; + Color color; + std::optional label; + Database database; +}; + +TEST(cli, test_long_space_basic_types) { + const auto result = read( + {"--sql", "SELECT 1", "--offset", "-5", "--rate", "-.5", "--tags", "a,b", + "--color", "green", "--label", "x", "--database.host", "localhost", + "--database.port", "5432", "--database.ssl"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& c = result.value(); + EXPECT_EQ(c.sql, "SELECT 1"); + EXPECT_EQ(c.offset, -5); + EXPECT_DOUBLE_EQ(c.rate, -0.5); + EXPECT_EQ(c.tags, (std::vector{"a", "b"})); + EXPECT_EQ(c.color, Color::green); + EXPECT_EQ(c.label, "x"); + EXPECT_EQ(c.database.host, "localhost"); + EXPECT_EQ(c.database.port, 5432); + EXPECT_EQ(c.database.ssl, true); +} + +TEST(cli, test_long_space_mixed_with_equals) { + const auto result = read( + {"--sql=SELECT 1", "--offset", "3", "--rate=2.5", "--tags=x", + "--color", "red", "--database.host=h", "--database.port", "1", + "--database.ssl=false"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& c = result.value(); + EXPECT_EQ(c.sql, "SELECT 1"); + EXPECT_EQ(c.offset, 3); + EXPECT_DOUBLE_EQ(c.rate, 2.5); + EXPECT_EQ(c.tags, (std::vector{"x"})); + EXPECT_FALSE(c.label); + EXPECT_EQ(c.database.ssl, false); +} + +TEST(cli, test_long_space_value_may_look_like_a_key) { + // The value is taken verbatim, even if it contains '=' or matches a + // field name. + const auto result = read( + {"--sql", "a=b", "--label", "sql", "--offset", "0", "--rate", "0", + "--tags", "", "--color", "blue", "--database.host", "h", + "--database.port", "1"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "a=b"); + EXPECT_EQ(result.value().label, "sql"); + EXPECT_TRUE(result.value().tags.empty()); +} + +struct Wrapped { + rfl::Description<"The query to run", std::string> sql; + rfl::Validator> limit; + rfl::Rename<"outFile", std::string> out_file; + rfl::Short<"p", int> port; + rfl::Positional input_file; + std::optional>> retries; + std::unique_ptr owner; +}; + +TEST(cli, test_long_space_wrappers) { + const auto result = read( + {"--sql", "SELECT 1", "--limit", "10", "--outFile", "out.csv", + "--port", "8080", "--input-file", "in.csv", "--retries", "3", "--owner", "me"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& w = result.value(); + EXPECT_EQ(w.sql(), "SELECT 1"); + EXPECT_EQ(w.limit(), 10); + EXPECT_EQ(w.out_file(), "out.csv"); + EXPECT_EQ(w.port(), 8080); + EXPECT_EQ(w.input_file(), "in.csv"); + ASSERT_TRUE(w.retries); + EXPECT_EQ((*w.retries)(), 3); + ASSERT_TRUE(w.owner); + EXPECT_EQ(*w.owner, "me"); +} + +struct WithDefaults { + rfl::DefaultVal mode; + rfl::DefaultVal level = 3; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_default_val) { + const auto result = read({"--mode", "fast", "in.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().mode(), "fast"); + EXPECT_EQ(result.value().level(), 3); + EXPECT_EQ(result.value().input_file(), "in.csv"); +} + +TEST(cli, test_long_space_validator_error_reported) { + const auto result = read( + {"--sql", "x", "--limit", "0", "--outFile", "o", "-p", "1", "in"}); + ASSERT_FALSE(result); + EXPECT_NE(std::string(result.error().what()).find("limit"), + std::string::npos) + << result.error().what(); +} + +struct Address { + std::string city; + rfl::Short<"z", int> zip; + bool verified; +}; + +struct Person { + std::string name; + rfl::Flatten
address; + rfl::Positional note; +}; + +TEST(cli, test_long_space_flatten) { + const auto result = read({"--name", "Alice", "--city", "Springfield", + "--zip", "12345", "--verified", "hello"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& p = result.value(); + EXPECT_EQ(p.name, "Alice"); + EXPECT_EQ(p.address().city, "Springfield"); + EXPECT_EQ(p.address().zip(), 12345); + EXPECT_TRUE(p.address().verified); + EXPECT_EQ(p.note(), "hello"); +} + +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_bool_does_not_consume_positional) { + for (const char* flag : + {"--verbose", "--dry-run", "--quiet", "--color", "--database.ssl"}) { + std::vector args = {"--database.host=h", "--database.port=1", + flag, "input.txt"}; + if (std::string(flag) != "--verbose") { + args.push_back("--verbose=false"); + } + const auto result = read(args); + ASSERT_TRUE(result) << flag << ": " << result.error().what(); + EXPECT_EQ(result.value().input_file(), "input.txt") << flag; + } +} + +TEST(cli, test_long_bool_values) { + const auto result = read( + {"--verbose", "--dry-run", "input.txt", "--quiet", "--color", + "--database.host", "h", "--database.port", "1", "--database.ssl"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& f = result.value(); + EXPECT_TRUE(f.verbose); + EXPECT_EQ(f.dry_run, true); + EXPECT_EQ(f.quiet(), true); + EXPECT_EQ(f.color(), true); + EXPECT_EQ(f.database.ssl, true); + EXPECT_EQ(f.input_file(), "input.txt"); +} + +struct Force { + bool force; + rfl::Positional level; +}; + +TEST(cli, test_long_bool_does_not_take_bool_literal) { + // Unlike `-f 0`, a long flag never takes the next token, even if it is a + // boolean literal. + for (const char* literal : {"0", "1"}) { + const auto result = read({"--force", literal}); + ASSERT_TRUE(result) << literal << ": " << result.error().what(); + EXPECT_TRUE(result.value().force) << literal; + EXPECT_EQ(result.value().level(), std::stoi(literal)); + } + + const auto with_equals = read({"--force=false", "0"}); + ASSERT_TRUE(with_equals) << with_equals.error().what(); + EXPECT_FALSE(with_equals.value().force); + EXPECT_EQ(with_equals.value().level(), 0); + + const auto literal = read( + {"--database.host=h", "--database.port=1", "--verbose", "false"}); + ASSERT_TRUE(literal) << literal.error().what(); + EXPECT_TRUE(literal.value().verbose); + EXPECT_EQ(literal.value().input_file(), "false"); +} + +TEST(cli, test_long_bool_literal_positional_after_separator) { + const auto result = read( + {"--database.host=h", "--database.port=1", "--verbose", "--", "false"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().verbose); + EXPECT_EQ(result.value().input_file(), "false"); +} + +struct Query { + std::string sql; + std::optional verbose; + rfl::Positional input_file; +}; + +TEST(cli, test_long_missing_value_at_end) { + const auto result = read({"in.txt", "--sql"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Missing value for option '--sql'."); +} + +TEST(cli, test_long_missing_value_before_option) { + const auto result = read({"--sql", "--verbose", "in.txt"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Missing value for option '--sql'."); +} + +TEST(cli, test_long_missing_value_before_separator) { + const auto result = read({"--sql", "--", "in.txt"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Missing value for option '--sql'."); +} + +TEST(cli, test_long_empty_value_with_equals) { + const auto result = read({"--sql=", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, ""); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +TEST(cli, test_long_space_separator) { + const auto result = + read({"--sql", "SELECT 1", "--", "--not-a-flag.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "SELECT 1"); + EXPECT_FALSE(result.value().verbose); + EXPECT_EQ(result.value().input_file(), "--not-a-flag.txt"); +} + +TEST(cli, test_long_space_duplicate) { + const auto result = read({"--sql", "a", "--sql", "b", "in.txt"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), "Duplicate argument: --sql"); +} + +TEST(cli, test_long_space_conflicts_with_positional) { + const auto result = read({"--sql=x", "--input-file", "a", "b"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Conflict: positional argument and '--input-file' both provided."); +} + +TEST(cli, test_long_unknown_option_lenient) { + // Without rfl::NoExtraFields, unknown options are ignored and do not + // consume the next token. + const auto result = + read({"--nope", "in.txt", "--sql", "x", "--other=1"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "x"); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +TEST(cli, test_long_unknown_option_lenient_too_many_positional) { + const auto result = read({"--nope", "1"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Too many positional arguments: expected at most 0, got 1."); +} + +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'."); + } +} + +TEST(cli, test_long_unknown_nested_option_no_extra_fields) { + const auto result = read( + {"--sql=x", "--offset=1", "--rate=1", "--tags=a", "--color=red", + "--database.host=h", "--database.port=1", "--database.nope", "1"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Unknown option '--database.nope'."); +} + +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 WithMap { + std::map labels; + std::map features; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_map) { + const auto result = read( + {"--labels.env", "prod", "--labels.team=data", "--features.fast", + "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& m = result.value(); + EXPECT_EQ(m.labels, (std::map{ + {"env", "prod"}, {"team", "data"}})); + EXPECT_EQ(m.features, (std::map{{"fast", true}})); + EXPECT_EQ(m.input_file(), "in.txt"); +} + +struct Server { + std::string host; + int port; +}; + +struct WithMapOfStructs { + std::map servers; + std::map> limits; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_map_of_structs) { + const auto result = read( + {"--servers.eu.host", "h", "--servers.eu.port", "1", + "--servers.us.host=u", "--servers.us.port", "2", "--limits.a.b", "3", + "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& m = result.value(); + EXPECT_EQ(m.servers.at("eu").host, "h"); + EXPECT_EQ(m.servers.at("eu").port, 1); + EXPECT_EQ(m.servers.at("us").host, "u"); + EXPECT_EQ(m.servers.at("us").port, 2); + EXPECT_EQ(m.limits.at("a").at("b"), 3); + EXPECT_EQ(m.input_file(), "in.txt"); + + 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'."); +} + +using DatabaseTuple = rfl::NamedTuple, + rfl::Field<"port", int>, + rfl::Field<"ssl", std::optional>>; + +struct WithNamedTuple { + DatabaseTuple database; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_named_tuple) { + const auto result = read( + {"--database.host", "h", "--database.port", "1", "--database.ssl", + "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& db = result.value().database; + EXPECT_EQ(db.get<"host">(), "h"); + EXPECT_EQ(db.get<"port">(), 1); + EXPECT_EQ(db.get<"ssl">(), true); + EXPECT_EQ(result.value().input_file(), "in.txt"); + + const auto root = read({"--host", "h", "--port", "1"}); + ASSERT_TRUE(root) << root.error().what(); + EXPECT_EQ(root.value().get<"host">(), "h"); + EXPECT_EQ(root.value().get<"port">(), 1); +} + +struct WithVariants { + std::optional> mode; + rfl::Generic extra; + rfl::Positional> input_file; +}; + +TEST(cli, test_long_variant_and_generic_without_value) { + // A variant or rfl::Generic may hold a bool, so `--mode` alone is valid + // and the next token is never its value. + const auto bare = read({"--mode", "--extra", "in.txt"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().mode, (std::variant(true))); + EXPECT_EQ(bare.value().input_file(), "in.txt"); + + const auto at_end = read({"--extra=1", "--mode"}); + ASSERT_TRUE(at_end) << at_end.error().what(); + EXPECT_EQ(at_end.value().mode, (std::variant(true))); + + const auto with_equals = read({"--mode=fast", "--extra=x"}); + ASSERT_TRUE(with_equals) << with_equals.error().what(); + EXPECT_EQ(with_equals.value().mode, + (std::variant(std::string("fast")))); +} + +TEST(cli, test_long_space_range_overload) { + // The range overload of rfl::cli::read uses the option table too. + const std::vector args = {"--sql", "SELECT 1", "--verbose", + "in.txt"}; + const auto result = rfl::cli::read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "SELECT 1"); + EXPECT_EQ(result.value().verbose, true); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +// The `Config` of docs/content/supported_formats/cli.md. +struct DocsConfig { + std::string host_name; + int port; + bool verbose; + std::optional rate; + std::vector tags; +}; + +TEST(cli, test_long_space_docs_examples) { + for (const auto& args : std::vector>{ + {"--host-name=localhost", "--port=8080", "--verbose", + "--tags=a,b,c"}, + {"--host-name", "localhost", "--port", "8080", "--verbose", + "--tags", "a,b,c", "--rate", "-0.5"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().host_name, "localhost"); + EXPECT_EQ(result.value().port, 8080); + EXPECT_TRUE(result.value().verbose); + EXPECT_EQ(result.value().tags, + (std::vector{"a", "b", "c"})); + } +} + +struct Node { + int value; + std::unique_ptr next; +}; + +TEST(cli, test_long_space_recursive_struct) { + const auto result = read({"--value", "1", "--next.value=2"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().value, 1); + ASSERT_TRUE(result.value().next); + EXPECT_EQ(result.value().next->value, 2); +} + +struct KebabConfig { + std::string host_name; + bool dry_run; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_kebab_case) { + const auto result = + read({"--host-name", "localhost", "--dry-run", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().host_name, "localhost"); + EXPECT_TRUE(result.value().dry_run); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +TEST(cli, test_long_space_wide_char) { + const wchar_t* args[] = {L"program", L"--sql", L"SELECT 1", L"--verbose", + L"in.txt"}; + const auto result = + rfl::cli::read(5, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "SELECT 1"); + EXPECT_EQ(result.value().verbose, true); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +TEST(cli, test_parse_argv_without_long_options) { + // Without the target struct's long options, parse_argv cannot tell + // whether --sql takes a value, so the next token stays positional. + const char* args[] = {"program", "--sql", "SELECT 1"}; + const auto parsed = rfl::cli::parse_argv(3, const_cast(args)); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().named.at("sql"), ""); + EXPECT_EQ(parsed.value().positional, (std::vector{"SELECT 1"})); + + const wchar_t* wargs[] = {L"program", L"--sql", L"SELECT 1"}; + const auto wparsed = rfl::cli::parse_argv(3, const_cast(wargs)); + ASSERT_TRUE(wparsed) << wparsed.error().what(); + EXPECT_EQ(wparsed.value().named.at("sql"), ""); + EXPECT_EQ(wparsed.value().positional, + (std::vector{"SELECT 1"})); +} + +TEST(cli, test_parse_argv_with_long_options) { + const auto options = + rfl::cli::make_long_options>(); + EXPECT_EQ(options.kind_of("sql"), rfl::cli::LongOptionKind::value); + EXPECT_EQ(options.kind_of("verbose"), rfl::cli::LongOptionKind::flag); + EXPECT_EQ(options.kind_of("input_file"), rfl::cli::LongOptionKind::value); + EXPECT_EQ(options.kind_of("nope"), rfl::cli::LongOptionKind::unknown); + + const wchar_t* args[] = {L"program", L"--sql", L"SELECT 1"}; + const auto parsed = + rfl::cli::parse_argv(3, const_cast(args), options); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().named.at("sql"), "SELECT 1"); + EXPECT_TRUE(parsed.value().positional.empty()); +} + +TEST(cli, test_short_options) { + const auto result = read( + {"--sql=x", "--limit=1", "--outFile=o", "-p", "-1", "in.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().port(), -1); + EXPECT_EQ(result.value().input_file(), "in.csv"); +} + +} // namespace test_long_option_values From a04eb1463f01292f2b1901227bc1161caf1b49eb Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 12:21:48 +0100 Subject: [PATCH 2/3] Add rfl::ImplicitValue, transparent like rfl::Short A CLI option such as `--help[=]` may be given with or without a value. Since `--key value` became the way to pass a value, a bare `--help` fails with "Missing value for option '--help'." and `--help input.txt` takes input.txt as the tag. rfl::ImplicitValue marks such a field, like Boost.Program_options' implicit_value: rfl::ImplicitValue> help; rfl::ImplicitValue, "all"> help_reports; rfl::ImplicitValue, "2"> verbosity = 0; The second template argument is the CLI text a bare option stands for, and defaults to "". This commit adds the wrapper and makes it transparent like rfl::Short and rfl::Positional: every reader and writer and the schema treat it as its inner type. is_required, is_empty and is_default_val_v look through it, so rfl::ImplicitValue> is omitted when empty and rfl::ImplicitValue> is filled in when missing, with its default in the schema. As with every other wrapper, an rfl::Rename renames the field only as the outermost wrapper, as in rfl::Rename<"x", rfl::ImplicitValue>. As for rfl::Short, csv and parquet do not support it. Its constructors and move assignment are noexcept only if the wrapped type's are, as for rfl::DefaultVal since #778, so `rfl::ImplicitValue, "5"> n = 0;` throws instead of calling std::terminate. The command line support follows in the next commit. Co-Authored-By: Claude Opus 5.5 --- include/rfl.hpp | 1 + include/rfl/ImplicitValue.hpp | 229 ++++++++++++++++++++ include/rfl/internal/is_default_val_v.hpp | 16 ++ include/rfl/internal/is_implicit_value.hpp | 27 +++ include/rfl/parsing/NamedTupleParser.hpp | 6 +- include/rfl/parsing/ParserImplicitValue.hpp | 71 ++++++ include/rfl/parsing/Parser_default.hpp | 16 ++ include/rfl/parsing/is_empty.hpp | 4 +- include/rfl/parsing/is_required.hpp | 4 + tests/json/test_implicit_value.cpp | 151 +++++++++++++ 10 files changed, 521 insertions(+), 4 deletions(-) create mode 100644 include/rfl/ImplicitValue.hpp create mode 100644 include/rfl/internal/is_implicit_value.hpp create mode 100644 include/rfl/parsing/ParserImplicitValue.hpp create mode 100644 tests/json/test_implicit_value.cpp diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..dc5ace36a 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -30,6 +30,7 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/ImplicitValue.hpp" #include "rfl/Literal.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" diff --git a/include/rfl/ImplicitValue.hpp b/include/rfl/ImplicitValue.hpp new file mode 100644 index 000000000..b42b0e91c --- /dev/null +++ b/include/rfl/ImplicitValue.hpp @@ -0,0 +1,229 @@ +#ifndef RFL_IMPLICITVALUE_HPP_ +#define RFL_IMPLICITVALUE_HPP_ + +#include +#include + +#include "default.hpp" +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Lets a CLI option be given without a value, like Boost.Program_options' +/// implicit_value: `--help` stands for `--help=<_implicit>`, and `--help=x` +/// sets `x`. `--help x` never takes `x` as the value, so `x` stays a +/// positional argument. If the option is absent, the field is read as usual +/// (std::optional gives std::nullopt, rfl::DefaultVal gives its default). +/// For non-CLI formats (JSON, YAML, etc.), this is transparent. +/// @tparam T The type of the field +/// @tparam _implicit The CLI text that a bare option stands for. It is parsed +/// like any other value, so `rfl::ImplicitValue` is 1. +template +struct ImplicitValue { + /// The underlying type. + using Type = T; + + /// The value that a bare option stands for. + static constexpr auto implicit_value_ = _implicit; + + /// @brief Default constructor. + /// @details Constructs the underlying value using its default constructor. + /// @requires Type must be default constructible. + ImplicitValue() + requires std::is_default_constructible_v + : value_(Type()) {} + + /// @brief Constructs the ImplicitValue wrapper from a const reference to + /// the underlying value. + /// @param _value The value to assign to the underlying field. + ImplicitValue(const Type& _value) : value_(_value) {} + + /// @brief Constructs the ImplicitValue wrapper by moving the underlying + /// value. + /// @param _value The value to move into the underlying field. + ImplicitValue(Type&& _value) noexcept( + std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + /// @brief Move constructor. + /// @param _field The ImplicitValue field to move from. + ImplicitValue(ImplicitValue&& _field) = default; + + /// @brief Copy constructor. + /// @param _field The ImplicitValue field to copy from. + ImplicitValue(const ImplicitValue& _field) = default; + + /// @brief Constructs from another ImplicitValue with a convertible + /// underlying type. + /// @tparam U The type of the other ImplicitValue's underlying value. + /// @param _field The other ImplicitValue field to copy from. + template + ImplicitValue(const ImplicitValue& _field) + : value_(_field.get()) {} + + /// @brief Move constructs from another ImplicitValue with a convertible + /// underlying type. + /// @tparam U The type of the other ImplicitValue's underlying value. + /// @param _field The other ImplicitValue field to move from. + template + ImplicitValue(ImplicitValue&& _field) noexcept( + std::is_nothrow_constructible_v) + : value_(std::move(_field.value_)) {} + + /// @brief Constructs from a value convertible to the underlying type. + /// @tparam U The type of the value. + /// @param _value The value to assign. + template + requires std::is_convertible_v + ImplicitValue(const U& _value) : value_(_value) {} + + /// @brief Move constructs from a value convertible to the underlying type. + /// @tparam U The type of the value. + /// @param _value The value to move. + template + requires std::is_convertible_v + ImplicitValue(U&& _value) noexcept( + std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + /// @brief Constructs the underlying object to its default value using + /// Default tag. + /// @tparam U The type to default construct (defaults to Type). + /// @param unused Default tag. + template + requires std::is_default_constructible_v + ImplicitValue(const Default&) : value_(Type()) {} + + /// @brief Destructor. + /// @details Defaulted destructor for ImplicitValue. + ~ImplicitValue() = default; + + /// @brief Returns a const reference to the underlying object. + /// @return Const reference to the underlying value. + const Type& get() const noexcept { return value_; } + + /// @brief Returns a reference to the underlying object. + /// @return Reference to the underlying value. + Type& get() noexcept { return value_; } + + /// @brief Dereference operator. + /// @return Reference to the underlying value. + Type& operator*() noexcept { return value_; } + + /// @brief Dereference operator (const). + /// @return Const reference to the underlying value. + const Type& operator*() const noexcept { return value_; } + + /// @brief Function call operator. + /// @return Reference to the underlying value. + Type& operator()() noexcept { return value_; } + + /// @brief Function call operator (const). + /// @return Const reference to the underlying value. + const Type& operator()() const noexcept { return value_; } + + /// @brief Pointer to the underlying value. + /// @return Pointer to the underlying value. + Type* operator->() noexcept { return &value_; } + + /// @brief Pointer to the underlying value (const). + /// @return Const pointer to the underlying value. + const Type* operator->() const noexcept { return &value_; } + + /// @brief Assigns a new value to the underlying object. + /// @param _value The value to assign. + /// @return Reference to this ImplicitValue. + auto& operator=(const Type& _value) { + value_ = _value; + return *this; + } + + /// @brief Move-assigns a new value to the underlying object. + /// @param _value The value to move. + /// @return Reference to this ImplicitValue. + auto& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return *this; + } + + /// @brief Assigns a value convertible to the underlying type. + /// @tparam U The type of the value. + /// @param _value The value to assign. + /// @return Reference to this ImplicitValue. + template + requires std::is_convertible_v + auto& operator=(const U& _value) { + value_ = _value; + return *this; + } + + /// @brief Assigns the underlying object to its default value using Default + /// tag. + /// @tparam U The type to default construct (defaults to Type). + /// @param unused Default tag. + /// @return Reference to this ImplicitValue. + template + requires std::is_default_constructible_v + auto& operator=(const Default&) { + value_ = Type(); + return *this; + } + + /// @brief Copy assignment operator. + /// @param _field The ImplicitValue field to copy from. + /// @return Reference to this ImplicitValue. + ImplicitValue& operator=( + const ImplicitValue& _field) = default; + + /// @brief Move assignment operator. + /// @param _field The ImplicitValue field to move from. + /// @return Reference to this ImplicitValue. + ImplicitValue& operator=( + ImplicitValue&& _field) = default; + + /// @brief Assigns from another ImplicitValue with a convertible underlying + /// type. + /// @tparam U The type of the other ImplicitValue's underlying value. + /// @param _field The other ImplicitValue field to copy from. + /// @return Reference to this ImplicitValue. + template + auto& operator=(const ImplicitValue& _field) { + value_ = _field.get(); + return *this; + } + + /// @brief Move-assigns from another ImplicitValue with a convertible + /// underlying type. + /// @tparam U The type of the other ImplicitValue's underlying value. + /// @param _field The other ImplicitValue field to move from. + /// @return Reference to this ImplicitValue. + template + auto& operator=(ImplicitValue&& _field) { + value_ = std::move(_field.value_); + return *this; + } + + /// @brief Sets the underlying object to a new value. + /// @param _value The value to assign. + void set(const Type& _value) { value_ = _value; } + + /// @brief Sets the underlying object to a new value by moving. + /// @param _value The value to move. + void set(Type&& _value) { value_ = std::move(_value); } + + /// @brief Returns a reference to the underlying value. + /// @return Reference to the underlying value. + Type& value() noexcept { return value_; } + + /// @brief Returns a const reference to the underlying value. + /// @return Const reference to the underlying value. + const Type& value() const noexcept { return value_; } + + /// The underlying value. + Type value_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 789206907..3ac5314c7 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -7,6 +7,7 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" @@ -44,6 +45,10 @@ template > : public is_default_val {}; +template +class is_default_val> : public is_default_val { +}; + template constexpr bool is_default_val_v = is_default_val>>::value; @@ -60,6 +65,17 @@ template class is_unwrapped_default_val>> : public std::true_type {}; +// rfl::ImplicitValue is transparent to every format but the command line, so +// a DefaultVal in it counts as unwrapped. +template +class is_unwrapped_default_val> + : public is_unwrapped_default_val {}; + +template +class is_unwrapped_default_val>> + : public is_unwrapped_default_val {}; + template constexpr bool is_unwrapped_default_val_v = is_unwrapped_default_val< std::remove_cvref_t>>::value; diff --git a/include/rfl/internal/is_implicit_value.hpp b/include/rfl/internal/is_implicit_value.hpp new file mode 100644 index 000000000..efcb9b518 --- /dev/null +++ b/include/rfl/internal/is_implicit_value.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_ISIMPLICITVALUE_HPP_ +#define RFL_INTERNAL_ISIMPLICITVALUE_HPP_ + +#include + +#include "../ImplicitValue.hpp" +#include "StringLiteral.hpp" + +namespace rfl::internal { + +template +class is_implicit_value; + +template +class is_implicit_value : public std::false_type {}; + +template +class is_implicit_value> + : public std::true_type {}; + +template +constexpr bool is_implicit_value_v = + is_implicit_value>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 7763fb46b..d7dc65f9b 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -309,9 +309,9 @@ struct NamedTupleParser { } }; - /// Sets the default value of the DefaultVal node in `_schema`. Rename, Short - /// and Positional leave no node in the schema, but Description and - /// Deprecated wrap the DefaultVal node in one of their own. + /// Sets the default value of the DefaultVal node in `_schema`. Rename, + /// Short, Positional and ImplicitValue leave no node in the schema, but + /// Description and Deprecated wrap the DefaultVal node in one of their own. static void set_default_value(Generic _default, schema::Type* _schema) { _schema->variant_.visit([&](auto& _s) { using S = std::remove_cvref_t; diff --git a/include/rfl/parsing/ParserImplicitValue.hpp b/include/rfl/parsing/ParserImplicitValue.hpp new file mode 100644 index 000000000..2893283de --- /dev/null +++ b/include/rfl/parsing/ParserImplicitValue.hpp @@ -0,0 +1,71 @@ +#ifndef RFL_PARSING_PARSER_IMPLICITVALUE_HPP_ +#define RFL_PARSING_PARSER_IMPLICITVALUE_HPP_ + +#include +#include + +#include "../ImplicitValue.hpp" +#include "../Result.hpp" +#include "../internal/StringLiteral.hpp" +#include "Parser_base.hpp" +#include "schema/Type.hpp" + +namespace rfl::parsing { + +template +struct ParserImplicitValue; + +template +struct ParserImplicitValue, ProcessorsType> { + using InputVarType = typename R::InputVarType; + + /** + * @brief Reads an ImplicitValue from the input. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @return A Result containing the parsed value or an error. + */ + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_implicit_value = [](auto&& _t) { + return ImplicitValue(std::move(_t)); + }; + return Parser, ProcessorsType>::read(_r, _var) + .transform(to_implicit_value); + } + + /** + * @brief Writes an ImplicitValue to the output. + * + * @tparam P The type of the parent. + * @param _w The writer to use. + * @param _implicit_value The ImplicitValue to write. + * @param _parent The parent object. + */ + template + static void write(const W& _w, + const ImplicitValue& _implicit_value, + const P& _parent) { + Parser, ProcessorsType>::write( + _w, _implicit_value.value(), _parent); + } + + /** + * @brief Generates the schema for the ImplicitValue, which is the schema of + * the underlying type. + * + * @param _definitions The map of definitions to add to. + * @return The schema type. + */ + static schema::Type to_schema( + std::map* _definitions) { + return Parser, ProcessorsType>::to_schema( + _definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 60677032b..ea9b7d0a1 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -20,6 +20,7 @@ #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" +#include "../internal/is_implicit_value.hpp" #include "../internal/is_literal.hpp" #include "../internal/is_validator.hpp" #include "../internal/processed_t.hpp" @@ -42,6 +43,7 @@ #include "ParserEnum.hpp" #include "ParserExpected.hpp" #include "ParserFilepath.hpp" +#include "ParserImplicitValue.hpp" #include "ParserOptional.hpp" #include "ParserPair.hpp" #include "ParserPositional.hpp" @@ -181,6 +183,11 @@ struct Parser { return ParserPositional::Type, ProcessorsType>::read(_r, _var); + } else if constexpr (rfl::internal::is_implicit_value< + std::remove_cvref_t>::value) { + return ParserImplicitValue, + ProcessorsType>::read(_r, _var); + } else if constexpr (is_reference_wrapper_v) { return ParserReferenceWrapper::type, ProcessorsType>::read(_r, _var); @@ -377,6 +384,11 @@ struct Parser { ParserPositional::Type, ProcessorsType>::write(_w, _var, _parent); + } else if constexpr (rfl::internal::is_implicit_value< + std::remove_cvref_t>::value) { + ParserImplicitValue, + ProcessorsType>::write(_w, _var, _parent); + } else if constexpr (is_reference_wrapper_v) { ParserReferenceWrapper::type, ProcessorsType>::write(_w, _var, _parent); @@ -549,6 +561,10 @@ struct Parser { return ParserPositional::to_schema(_definitions); + } else if constexpr (rfl::internal::is_implicit_value::value) { + return ParserImplicitValue::to_schema( + _definitions); + } else if constexpr (is_reference_wrapper_v) { return ParserReferenceWrapper::to_schema(_definitions); diff --git a/include/rfl/parsing/is_empty.hpp b/include/rfl/parsing/is_empty.hpp index 7f77a7c78..851cc6992 100644 --- a/include/rfl/parsing/is_empty.hpp +++ b/include/rfl/parsing/is_empty.hpp @@ -5,6 +5,7 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_implicit_value.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_rename.hpp" #include "../internal/is_short.hpp" @@ -38,7 +39,8 @@ static bool is_empty(const T& _var) { } } else if constexpr (internal::is_rename_v || internal::is_short_v || - internal::is_positional_v) { + internal::is_positional_v || + internal::is_implicit_value_v) { return is_empty(_var.value()); } else if constexpr (is_map_like_v || is_vector_like_v) { return _var.begin() == _var.end(); diff --git a/include/rfl/parsing/is_required.hpp b/include/rfl/parsing/is_required.hpp index 30fe10f6a..497594929 100644 --- a/include/rfl/parsing/is_required.hpp +++ b/include/rfl/parsing/is_required.hpp @@ -6,11 +6,13 @@ #include #include "../Generic.hpp" +#include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_implicit_value.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_rename.hpp" #include "../internal/is_short.hpp" @@ -63,6 +65,8 @@ consteval bool is_required() { return is_required(); } else if constexpr (internal::is_short_v) { return is_required(); + } else if constexpr (internal::is_implicit_value_v) { + return is_required(); } else { return !(is_never_required_v || (_ignore_empty_containers && diff --git a/tests/json/test_implicit_value.cpp b/tests/json/test_implicit_value.cpp new file mode 100644 index 000000000..cef1857e7 --- /dev/null +++ b/tests/json/test_implicit_value.cpp @@ -0,0 +1,151 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +// rfl::ImplicitValue only changes how a CLI option is given, so for JSON a +// field wrapped in it must behave exactly like the field without it. +namespace test_implicit_value { + +struct Plain { + std::optional help; + rfl::Short<"l", rfl::DefaultVal> level = 3; + rfl::Description<"Report to print", rfl::DefaultVal> report = + std::string("summary"); + std::string tag; +}; + +struct Implicit { + rfl::ImplicitValue> help; + rfl::Short<"l", rfl::ImplicitValue, "1">> level = 3; + rfl::Description<"Report to print", + rfl::DefaultVal>> + report = std::string("summary"); + rfl::ImplicitValue tag; +}; + +TEST(json, test_implicit_value) { + write_and_read(Implicit{.tag = std::string("t")}, + R"({"level":3,"report":"summary","tag":"t"})"); + write_and_read( + Implicit{.help = std::string("h"), + .level = 5, + .report = std::string("all"), + .tag = std::string("t")}, + R"({"help":"h","level":5,"report":"all","tag":"t"})"); + + const auto defaults = rfl::json::read(R"({"tag":"t"})"); + ASSERT_TRUE(defaults) << defaults.error().what(); + EXPECT_FALSE(defaults.value().help().has_value()); + EXPECT_EQ(defaults.value().level().value().value(), 3); + EXPECT_EQ(defaults.value().report().value().value(), "summary"); + + const auto missing = rfl::json::read(R"({})"); + ASSERT_FALSE(missing); + EXPECT_EQ(std::string(missing.error().what()), + "Field named 'tag' not found."); + + auto schema = rfl::json::to_schema(); + for (auto pos = schema.find("Implicit"); pos != std::string::npos; + pos = schema.find("Implicit", pos)) { + schema.replace(pos, 8, "Plain"); + } + EXPECT_EQ(schema, rfl::json::to_schema()); + EXPECT_NE(schema.find(R"("default":"summary")"), std::string::npos) + << schema; +} + +using Positive = rfl::Validator>; + +static_assert(!std::is_nothrow_constructible_v< + rfl::ImplicitValue, "5">, int>, + "Converting to a Validator can throw."); +static_assert(!std::is_nothrow_constructible_v< + rfl::ImplicitValue, int>); +static_assert( + std::is_nothrow_constructible_v, short>); +static_assert( + std::is_nothrow_move_constructible_v>); + +struct InvalidInitializer { + rfl::ImplicitValue, "5"> retries = 0; +}; + +TEST(json, test_implicit_value_throwing_initializer) { + EXPECT_THROW((void)InvalidInitializer{}, std::exception); + const auto res = rfl::json::read(R"({"retries":3})"); + ASSERT_FALSE(res); + EXPECT_NE(std::string(res.error().what()) + .find("Value expected to be greater than or equal to 1, but " + "got 0."), + std::string::npos) + << res.error().what(); +} + +// As for every other wrapper, an rfl::Rename renames the field if it is the +// outermost wrapper. +struct RenamedOutermost { + rfl::Rename<"outer", rfl::ImplicitValue> field_one; + rfl::Rename<"shortRenamed", + rfl::Short<"s", rfl::ImplicitValue, + "x">>> + field_two; + rfl::Rename<"withDefault", + rfl::ImplicitValue, "2">> + field_three = 5; +}; + +TEST(json, test_implicit_value_rename_outermost) { + write_and_read( + RenamedOutermost{.field_one = 2, + .field_two = std::optional("v"), + .field_three = 7}, + R"({"outer":2,"shortRenamed":"v","withDefault":7})"); + EXPECT_EQ(rfl::json::write( + RenamedOutermost{.field_one = 2, .field_three = 7}), + R"({"outer":2,"withDefault":7})"); + const auto missing = rfl::json::read(R"({"outer":1})"); + ASSERT_TRUE(missing) << missing.error().what(); + EXPECT_EQ(missing.value().field_three().value().value(), 5); + const auto required = rfl::json::read(R"({})"); + ASSERT_FALSE(required); + EXPECT_EQ(std::string(required.error().what()), + "Field named 'outer' not found."); + EXPECT_EQ( + rfl::json::to_schema(), + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_implicit_value__RenamedOutermost","$defs":{"test_implicit_value__RenamedOutermost":{"type":"object","properties":{"outer":{"type":"integer"},"shortRenamed":{"anyOf":[{"type":"string"},{"type":"null"}]},"withDefault":{"type":"integer","default":5}},"required":["outer"]}}})"); +} + +// Inside another wrapper, an rfl::Rename is ignored, as everywhere in +// reflect-cpp: the field keeps its own name. +struct RenamedInside { + rfl::ImplicitValue>, "x"> + field_one; + rfl::Short<"s", rfl::Rename<"short_renamed", std::string>> field_two; + rfl::Positional> field_three; +}; + +TEST(json, test_rename_inside_other_wrappers_is_ignored) { + write_and_read( + RenamedInside{ + .field_one = rfl::Rename<"renamed", std::optional>( + std::string("v")), + .field_two = rfl::Rename<"short_renamed", std::string>("w"), + .field_three = rfl::Rename<"positional_renamed", int>(2)}, + R"({"field_one":"v","field_two":"w","field_three":2})"); + EXPECT_EQ(rfl::json::write(RenamedInside{ + .field_one = + rfl::Rename<"renamed", std::optional>( + std::string("v")), + .field_two = rfl::Rename<"short_renamed", std::string>("w"), + .field_three = rfl::Rename<"positional_renamed", int>(2)}), + R"({"fieldOne":"v","fieldTwo":"w","fieldThree":2})"); +} + +} // namespace test_implicit_value From 7fa3a02b94e99a417693fb0056ec5820f649f4f1 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 13 Nov 2026 09:28:25 +0100 Subject: [PATCH 3/3] Support rfl::ImplicitValue and nested Short and Positional in rfl::cli rfl::cli only recognized rfl::Short and rfl::Positional as the outermost wrapper of a field, and treated a short option as a bool flag only if Short's inner type was exactly bool: - rfl::Description<"...", rfl::Short<"o", T>> and rfl::DefaultVal> failed with "Unknown short argument: -o". - rfl::DefaultVal> failed with "Too many positional arguments: expected at most 0, got 1.". - rfl::Short<"q", rfl::DefaultVal> and rfl::Short<"q", std::optional> took the next token, so `-q in.txt` failed with "Could not cast 'in.txt' to boolean". LongOptions becomes internal::Options (options.hpp, make_options): one table of the long options, short aliases and positional fields of the target struct. The table and the overloads of parse_argv and resolve_args that take it are in rfl::cli::internal. rfl::Short, rfl::Positional and rfl::ImplicitValue are found through each other and through rfl::DefaultVal, std::optional, rfl::Description, rfl::Rename and rfl::Deprecated, in any order. parse_argv looks short options up in the table as well, so a short option is a flag, takes a value or has an implicit value as its long name does: - A short bool flag takes the next token only if it is true, false, 1 or 0, as before (a long one never does). `-q in.txt` leaves in.txt positional, in argv order, and `-q=x` sets x, which fails for a non-bool x like `--quiet=x` does. - `-o` without a value fails with "Missing value for option '-o'." instead of passing an empty string. - An rfl::ImplicitValue option never takes the next token. `--help` and `-h` get the implicit value, `--help=x` and `-h=x` set x, and `--help in.txt` leaves in.txt positional. - A short alias of a variant, rfl::Generic or nested struct takes the next token unless it looks like an option, as before. Of several Short and Positional wrappers on one field, the outermost counts, as when only the outermost wrapper was looked at. Short directly around Positional, or the reverse, still does not compile, and neither does Positional with ImplicitValue. A Short found through other wrappers counts only if no other field has its name, so an outermost Short keeps its name. Two fields with the same outermost Short still make every read fail with "Duplicate short name '-o' in struct definition." Bare arguments go first to the fields whose outermost wrapper is Positional, then to those where it is found through other wrappers, each in declaration order, so a struct that mixes them reads as before. Options::negative_numbers_are_options replaces the flag that rfl::cli::read passed to the parser. It is true without a table, so parse_argv without one still reads -5 as a short option. An rfl::Rename renames the option only as the outermost wrapper, as in rfl::Rename<"out", rfl::Short<"o", T>>; inside Short, Positional or ImplicitValue it is ignored, as elsewhere in reflect-cpp. resolve_args(ParsedArgs) still returns the tokens that short bool flags took to the positional arguments, for callers that run parse_argv without the table. It also applies rfl::ImplicitValue there: `--help` and `-h` given without a value get the implicit value, and a token that `-h` took goes back to the positional arguments. ParsedArgs records which options were given without '=' for this. rfl::cli::read uses internal::resolve_args(ParsedArgs, const Options&) instead. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 102 ++++- include/rfl/cli.hpp | 2 +- include/rfl/cli/long_options.hpp | 365 --------------- include/rfl/cli/options.hpp | 624 ++++++++++++++++++++++++++ include/rfl/cli/parse_argv.hpp | 232 +++++----- include/rfl/cli/read.hpp | 47 +- include/rfl/cli/resolve_args.hpp | 284 ++++-------- tests/cli/test_implicit_value.cpp | 297 ++++++++++++ tests/cli/test_long_option_values.cpp | 35 +- tests/cli/test_wrapper_order.cpp | 327 ++++++++++++++ 10 files changed, 1599 insertions(+), 716 deletions(-) delete mode 100644 include/rfl/cli/long_options.hpp create mode 100644 include/rfl/cli/options.hpp create mode 100644 tests/cli/test_implicit_value.cpp create mode 100644 tests/cli/test_wrapper_order.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 542df703e..9532d5514 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -90,24 +90,58 @@ A long option takes its value either after `=` or as the next token: This works for every field that takes a value: nested fields (`--database.host db.local`, also inside an `rfl::NamedTuple`), vectors, -enums, numbers, optionals, map entries (`--labels.env prod`, or -`--servers.eu.port 8080` for a map of structs), fields inlined by +enums, numbers, optionals, entries of maps with string keys +(`--labels.env prod`, or `--servers.eu.port 8080` for a map of structs; +other maps need `=`), fields inlined by `rfl::Flatten`, and fields wrapped in `rfl::Short`, `rfl::Positional`, `rfl::Rename`, `rfl::Description`, `rfl::Validator` or `rfl::DefaultVal`. A `std::variant`, `rfl::Variant`, `rfl::TaggedUnion` or `rfl::Generic` -may hold a bool, so its option never takes the next token: pass its value -with `=`. Alone, `--key` passes an empty value (`true` for a bool). +may hold a bool, so its long option never takes the next token: pass its +value with `=`. Alone, `--key` passes an empty value (`true` for a bool). +Its short alias takes the next token unless it looks like an option: +`-m fast`. The next token is the value unless it looks like an option (`-` followed by -a letter), so negative numbers such as `--offset -5` work. If the value is +anything except a digit or `.`), so negative numbers such as `--offset -5` +work. If the value is missing, parsing fails with `Missing value for option '--sql'.` Use `=` to pass an empty value or one that starts with `-`: `--sql=`, `--pattern=-x`. +Short aliases follow the same rules: `-o out.csv`, `-o=out.csv`, and +`Missing value for option '-o'.` For an option whose value may be left out, +use `rfl::ImplicitValue` (below). Boolean fields (`bool`, `std::optional` and wrapped bools) are flags and never consume the next token: `--verbose input.txt` sets `verbose` and passes `input.txt` as a positional argument, and so does `--verbose 0` with `0`. To set a flag to `false`, write `--verbose=false`. +## Implicit values + +Wrap a field with `rfl::ImplicitValue` to let its option be given +without a value, like Boost's `implicit_value`: + +```cpp +struct Config { + rfl::Short<"h", rfl::ImplicitValue>> help; + rfl::ImplicitValue, "all"> help_reports; + rfl::ImplicitValue, "2"> verbosity = 0; + rfl::Positional> input; +}; + +// ./app --help-reports -> help_reports = "all" +// ./app --help-reports=memory -> help_reports = "memory" +// ./app --help-reports in.txt -> help_reports = "all", input = "in.txt" +// ./app -h / -h=tag -> help = "" / "tag" +// ./app --verbosity -> verbosity = 2 +``` + +A bare option stands for the text, which is parsed like any other value +(the default text is empty). A value can only be given after `=`: the next +token is never taken. If the option is absent, the field is read as usual: +`std::optional` gives `std::nullopt`, `rfl::DefaultVal` its default, and any +other field is required. Other formats read and write `rfl::ImplicitValue` +as its inner type, as they do `rfl::Short`. + ## Unknown options By default, long options that match no field are ignored, and they do not @@ -170,14 +204,34 @@ struct Config { // ./app --port=8080 --verbose --host=localhost (long names still work) ``` -Short bool flags do not consume the next token as a value — `-v somefile` -treats `somefile` as a positional argument, not as the value of `-v`. -To explicitly set a bool short flag, use `=` syntax: `-v=true`, `-v=false`. - -## Combining Positional and Short - -`Positional` and `Short` can be used together in the same struct, but -**cannot be nested** (`Positional>` is a compile-time error): +Short bool flags (`bool`, `std::optional` and wrapped bools) do not +consume the next token as a value — `-v somefile` treats `somefile` as a +positional argument, not as the value of `-v`. Unlike long flags, they take +the next token if it is `true`, `false`, `1` or `0`: `-v false` sets the +flag to `false`. Write `-v -- 1` to pass such a token as a positional +argument. To explicitly set a bool short flag, use `=` syntax: `-v=true`, +`-v=false`. + +## Combining wrappers + +`Short`, `Positional` and `ImplicitValue` can be nested with each other and +with `DefaultVal`, `std::optional`, `Description`, `Rename` and `Deprecated` +in any order: `rfl::Description<"...", rfl::Short<"o", T>>` is `-o`, and +`rfl::DefaultVal>` is positional. Put `rfl::Rename` +outermost, as in `rfl::Rename<"out", rfl::Short<"o", T>>`; inside other +wrappers it is ignored, as elsewhere in reflect-cpp. + +If a field has several `Short` or `Positional` wrappers, the outermost one +counts: `rfl::Short<"o", rfl::Description<"...", rfl::Positional>>` is +`-o`. A `Short` found through other wrappers counts only if no other field +has its name, so another field `rfl::Short<"o", U>` keeps `-o`. Two fields +whose outermost wrapper is the same `Short` make every read fail with +`Duplicate short name '-o' in struct definition.` + +Bare arguments go first to the fields whose outermost wrapper is +`Positional`, then to those where it is found through other wrappers, each in +declaration order. `Short` directly around `Positional` (or the reverse), and +a `Positional` field with an `ImplicitValue`, are compile-time errors: ```cpp struct Config { @@ -211,21 +265,22 @@ leaving out `-o` gives `"out"`. | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | | `rfl::Positional` | bare token | Matched in declaration order | | `rfl::Short<"x", T>` | `-x value` or `-x=value` | Single-character alias | +| `rfl::ImplicitValue` | `--key` or `--key=value` | Bare means `x` | ## Architecture Parsing proceeds in three stages: 1. **`parse_argv`** — categorizes raw tokens into `named`, `short_args`, - and `positional` buckets (`ParsedArgs` struct). It is given a - `LongOptions` table derived from the target struct - (`make_long_options()`), which says which long options - are flags and which take a value, so that `--key value` works, and - whether a short option's name looks like a number. Without the table, it - reads `-5` as a short option. -2. **`resolve_args`** — uses compile-time metadata from the target struct to - map short aliases to long names, reclaim values from bool short flags, - and merge positional arguments. Produces a flat `map`. + and `positional` buckets (`ParsedArgs` struct). `rfl::cli::read` gives + it an internal option table derived from the target struct, which says + which long and short options are flags, take a value or have an implicit + value, so that `--key value` works, and whether a short option's name + looks like a number. The public `parse_argv`, which has no table, reads + `-5` as a short option. +2. **`resolve_args`** — uses the same table to map short aliases to long + names and to merge positional arguments. Produces a flat + `map`. 3. **`Reader`** — implements reflect-cpp's `IsReader` concept by presenting virtual tree nodes over the flat map. Each node is a `{map*, path}` pair — no data copying, just prefix-based lookup via `lower_bound`. @@ -236,9 +291,10 @@ Parsing proceeds in three stages: - `include/rfl/cli/Reader.hpp` — Reader + `parse_value` overloads - `include/rfl/cli/Parser.hpp` — Parser type alias - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` -- `include/rfl/cli/long_options.hpp` — `LongOptions`: which long options take a value +- `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper - `include/rfl/Short.hpp` — `Short<"x", T>` wrapper +- `include/rfl/ImplicitValue.hpp` — `ImplicitValue` wrapper diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index b6e8f63a7..85881e7b9 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -4,7 +4,7 @@ #include "../rfl.hpp" #include "cli/Parser.hpp" #include "cli/Reader.hpp" -#include "cli/long_options.hpp" +#include "cli/options.hpp" #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" diff --git a/include/rfl/cli/long_options.hpp b/include/rfl/cli/long_options.hpp deleted file mode 100644 index af69d99a7..000000000 --- a/include/rfl/cli/long_options.hpp +++ /dev/null @@ -1,365 +0,0 @@ -#ifndef RFL_CLI_LONG_OPTIONS_HPP_ -#define RFL_CLI_LONG_OPTIONS_HPP_ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../Generic.hpp" -#include "../Tuple.hpp" -#include "../internal/has_reflection_type_v.hpp" -#include "../internal/has_reflector.hpp" -#include "../internal/is_extra_fields.hpp" -#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" -#include "Reader.hpp" - -namespace rfl::cli { - -/// What a long option does with the token that follows it. -enum class LongOptionKind { - /// A boolean field: `--flag`. Never consumes the next token. - flag, - /// A field that takes a value: `--key value` or `--key=value`. - value, - /// A known path whose kind cannot be decided from the type (a nested - /// struct, a variant, rfl::Generic, or a sub-key of a variant). Never - /// consumes the next token, so `--key` alone passes an empty value. - other, - /// No field matches this option. - unknown -}; - -/// The long options that a target struct accepts, derived from its fields at -/// compile time. Lets parse_argv decide whether `--key` takes the next token -/// as its value. Paths are dotted (`database.host`) and use the field names -/// after processors (kebab-case, rfl::Rename) are applied. -struct LongOptions { - /// Paths of boolean fields. - std::set flags; - - /// Paths of fields that take a value. - std::set values; - - /// Paths of fields that may or may not need a value, depending on what - /// they hold (variants, rfl::Generic). - std::set others; - - /// 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 kind of a direct sub-key. - std::map open_prefixes; - - /// For the open prefixes whose sub-keys hold structs or maps: the long - /// 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; - - /// Returns the kind of the long option `--_key`. - LongOptionKind kind_of(const std::string& _key) const { - if (flags.count(_key)) { - return LongOptionKind::flag; - } - if (values.count(_key)) { - return LongOptionKind::value; - } - if (others.count(_key)) { - return LongOptionKind::other; - } - - // A key below a leaf field (for example a variant of structs): the - // reader decides what it means. - for (auto pos = _key.find(path_separator); pos != std::string::npos; - pos = _key.find(path_separator, pos + 1)) { - const auto parent = _key.substr(0, pos); - if (flags.count(parent) || values.count(parent) - || others.count(parent)) { - return LongOptionKind::other; - } - } - - // A nested struct or map itself, such as `--database`. - const auto prefix = _key + path_separator; - if (has_prefix(flags, prefix) || has_prefix(values, prefix) - || has_prefix(others, prefix) || has_prefix(open_prefixes, prefix)) { - return LongOptionKind::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 (_key.size() > p.first.size() && _key.starts_with(p.first) - && (!open || p.first.size() > open->first.size())) { - open = &p; - } - } - if (open) { - const auto rest = _key.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->kind_of(rest.substr(sep + 1)); - } - return LongOptionKind::other; - } - - return LongOptionKind::unknown; - } - - private: - template - static bool has_prefix( - const ContainerType& _container, const std::string& _prefix - ) { - const auto it = _container.lower_bound(_prefix); - if (it == _container.end()) { - return false; - } - if constexpr (std::is_same_v>) { - return it->starts_with(_prefix); - } - else { - return it->first.starts_with(_prefix); - } - } -}; - -namespace internal { - -template -struct type_list { - template - static constexpr bool contains = (std::is_same_v || ...); - - template - using add = type_list; -}; - -/// Strips everything that does not change how a field is written on the -/// command line: optionals, pointers, rfl::Short, rfl::Positional, -/// rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a ReflectionType -/// (rfl::Validator, rfl::Description, rfl::Literal, ...), reflectors and -/// custom parsers. -template -auto unwrap_option_type() { - using U = std::remove_cvref_t; - if constexpr (std::is_pointer_v) { - return unwrap_option_type, ProcessorsType>(); - } - else if constexpr (parsing::is_optional_v) { - return unwrap_option_type(); - } - else if constexpr (parsing::is_unique_ptr_v - || parsing::is_shared_ptr_v) { - return unwrap_option_type(); - } - else if constexpr (parsing::is_box_v) { - return unwrap_option_type< - typename parsing::is_box::element_type, ProcessorsType>(); - } - else if constexpr (parsing::is_ref_v) { - return unwrap_option_type< - typename parsing::is_ref::element_type, ProcessorsType>(); - } - else if constexpr (rfl::internal::is_short_v - || rfl::internal::is_positional_v - || parsing::is_rename_v - || parsing::is_default_val_v - || parsing::is_skip_v) { - return unwrap_option_type(); - } - else if constexpr (rfl::internal::has_reflection_type_v) { - return unwrap_option_type(); - } - else if constexpr (rfl::internal::has_read_reflector) { - return unwrap_option_type< - typename Reflector::ReflType, ProcessorsType>(); - } - else if constexpr (requires { - typename Parser:: - CustomParserHelperStruct; - }) { - return unwrap_option_type< - typename Parser::CustomParserHelperStruct, - ProcessorsType>(); - } - else { - return std::type_identity{}; - } -} - -template -using unwrapped_option_t = - typename decltype(unwrap_option_type())::type; - -/// Whether the reader treats T as a struct whose fields are addressed as -/// `--field.sub-field`. -template -constexpr bool is_option_struct_v = - (std::is_class_v && std::is_aggregate_v && !parsing::is_array_v - && !parsing::is_rfl_array_v) - || rfl::internal::is_named_tuple_v; - -/// Whether an option for T may or may not need a value, depending on what -/// it holds: a variant or rfl::Generic can be a bool or a struct. Such an -/// option never takes the next token. -template -constexpr bool is_open_option_v = - parsing::is_variant_v || parsing::is_rfl_variant_v - || parsing::is_tagged_union_v || std::is_same_v; - -/// The NamedTuple whose fields are the options of the struct T: T itself if -/// it is an rfl::NamedTuple (whose names the processors leave alone), or T -/// with the processors applied. -template -using option_fields_t = typename std::conditional_t< - rfl::internal::is_named_tuple_v, std::type_identity, - rfl::internal::Processed>::type; - -template -constexpr LongOptionKind sub_key_kind() { - using U = unwrapped_option_t; - if constexpr (std::is_same_v) { - return LongOptionKind::flag; - } - else if constexpr (parsing::is_string_map_v || is_option_struct_v - || is_open_option_v) { - return LongOptionKind::other; - } - else { - return LongOptionKind::value; - } -} - -template -void collect_long_options(const std::string& _prefix, LongOptions* _options); - -template -void collect_value_long_options(LongOptions* _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 long -/// options inside one of them. -template -void add_open_prefix(const std::string& _prefix, LongOptions* _options) { - using U = unwrapped_option_t; - _options->open_prefixes[_prefix] = sub_key_kind(); - if constexpr (parsing::is_string_map_v - || (is_option_struct_v - && !VisitedType::template contains)) { - auto nested = std::make_shared(); - collect_value_long_options(nested.get()); - _options->open_prefix_options[_prefix] = std::move(nested); - } -} - -template -void add_long_option(const std::string& _path, LongOptions* _options) { - using U = unwrapped_option_t; - if constexpr (std::is_same_v) { - _options->flags.insert(_path); - } - else if constexpr (is_open_option_v) { - _options->others.insert(_path); - } - 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] = LongOptionKind::other; - } - else { - collect_long_options( - _path + path_separator, _options); - } - } - else { - _options->values.insert(_path); - } -} - -template -void add_long_option_for_field( - const std::string& _prefix, LongOptions* _options -) { - using T = std::remove_cvref_t; - if constexpr (rfl::internal::is_extra_fields_v) { - add_open_prefix( - _prefix, _options); - } - else { - add_long_option( - _prefix + std::string(FieldType::name()), _options); - } -} - -template -void collect_long_options(const std::string& _prefix, LongOptions* _options) { - using NT = option_fields_t; - using NextVisitedType = typename VisitedType::template add; - [&](std::index_sequence<_is...>) { - (add_long_option_for_field< - rfl::tuple_element_t<_is, typename NT::Fields>, ProcessorsType, - NextVisitedType>(_prefix, _options), - ...); - }(std::make_index_sequence()); -} - -/// Adds the long 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_long_options(LongOptions* _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_long_options("", _options); - } - else { - _options->open_prefixes[""] = LongOptionKind::other; - } -} - -} // namespace internal - -/// Derives the long options that T accepts from its fields. -/// @tparam T The target struct type -/// @tparam ProcessorsType The processors applied to the struct -/// @return The long options, with reject_unknown set if ProcessorsType -/// contains rfl::NoExtraFields -template -LongOptions make_long_options() { - LongOptions options; - options.reject_unknown = - rfl::internal::no_extra_fields_v; - internal::collect_value_long_options>(&options); - return options; -} - -} // namespace rfl::cli - -#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp new file mode 100644 index 000000000..aa8221565 --- /dev/null +++ b/include/rfl/cli/options.hpp @@ -0,0 +1,624 @@ +#ifndef RFL_CLI_OPTIONS_HPP_ +#define RFL_CLI_OPTIONS_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.hpp" +#include "../Generic.hpp" +#include "../ImplicitValue.hpp" +#include "../Positional.hpp" +#include "../Rename.hpp" +#include "../Short.hpp" +#include "../Tuple.hpp" +#include "../internal/StringLiteral.hpp" +#include "../internal/has_reflection_type_v.hpp" +#include "../internal/has_reflector.hpp" +#include "../internal/is_extra_fields.hpp" +#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" +#include "Reader.hpp" + +namespace rfl::cli::internal { + +/// What an option does with the token that follows it. +enum class OptionKind { + /// A boolean field: `--flag` or `-f`. `--flag` never takes the next + /// token; `-f` takes it only if it is `true`, `false`, `1` or `0`. + flag, + /// A field that takes a value: `--key value`, `--key=value`, `-k value` or + /// `-k=value`. + value, + /// A field wrapped in rfl::ImplicitValue: `--key` and `-k` stand for its + /// implicit value. A value can only be given after '=', never as the next + /// token. + implicit_value, + /// A known path whose kind cannot be decided from the type (a nested + /// 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, + /// No field matches this option. + unknown +}; + +/// How an option is given on the command line. +struct Option { + OptionKind kind = OptionKind::unknown; + + /// For OptionKind::implicit_value: the value that the option stands for + /// when it is given without one. + std::string implicit_value = {}; +}; + +/// The options that a target struct accepts, built from its fields by +/// make_options on every read. parse_argv uses it to decide whether an +/// option takes the next token as its value, 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 long options, by path. + std::map long_options; + + /// The short aliases given by rfl::Short (`p` for `-p`), mapped to the path + /// of their field. + std::map short_options; + + /// The paths of the rfl::Positional fields: first those whose outermost + /// wrapper is rfl::Positional, then those where it is found through other + /// wrappers, each in declaration order. + 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 + /// name looks like a number (`-1`). + bool negative_numbers_are_options = true; + + /// A short name that two fields give with an outermost rfl::Short, such as + /// `rfl::Short<"o", A> a; rfl::Short<"o", B> b;`, or empty. Reading such a + /// struct fails. + std::string duplicate_short_name; + + /// Returns the long option `--_name`. + Option find_long(const std::string& _name) const { + const auto it = long_options.find(_name); + 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. + Option find_short(const std::string& _name) const { + 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 +/// without '=' takes from the next token: "true", "false", "1" or "0". +/// @param _token The command-line token to check +/// @return true if it is a boolean literal, false otherwise +inline bool is_bool_literal(std::string_view _token) noexcept { + return _token == "true" || _token == "false" || _token == "1" + || _token == "0"; +} + +template +struct type_list { + template + static constexpr bool contains = (std::is_same_v || ...); + + template + using add = type_list; +}; + +/// What rfl::Short, rfl::Positional and rfl::ImplicitValue say about a field +/// of type T. They are found through each other and through rfl::DefaultVal, +/// std::optional, rfl::Description, rfl::Deprecated and rfl::Rename, in any +/// order. Of several rfl::Short and rfl::Positional, the outermost counts. +template +struct cli_annotations { + static constexpr bool is_short = false; + static constexpr bool is_positional = false; + static constexpr size_t num_implicit_value = 0; + static constexpr rfl::internal::StringLiteral<1> short_name = ""; + static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; +}; + +template +using cli_annotations_t = cli_annotations>; + +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> + : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t {}; + +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool is_short = false; + static constexpr bool is_positional = true; +}; + +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool is_short = true; + static constexpr bool is_positional = false; + static constexpr auto short_name = _name; +}; + +template +struct cli_annotations> : cli_annotations_t { + static constexpr size_t num_implicit_value = + cli_annotations_t::num_implicit_value + 1; + static constexpr auto implicit_value = _implicit; +}; + +/// Whether T is rfl::Short directly around rfl::Positional, or the other way +/// round, which is a compile-time error. +template +consteval bool is_short_around_positional() { + if constexpr (rfl::internal::is_short_v) { + return rfl::internal::is_positional_v; + } + else if constexpr (rfl::internal::is_positional_v) { + return rfl::internal::is_short_v; + } + else { + return false; + } +} + +/// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the +/// declared type of the field, whichever wrappers it consists of. +template +struct field_info { + using FieldType = rfl::tuple_element_t<_i, typename NamedTupleType::Fields>; + using InnerType = typename FieldType::Type; + using OuterType = std::remove_pointer_t>; + using Annotations = cli_annotations_t; + + static constexpr bool is_positional = Annotations::is_positional; + static constexpr bool is_short = Annotations::is_short; + /// Whether rfl::Short is the outermost wrapper of the field, not found + /// through others. + static constexpr bool is_direct_short = rfl::internal::is_short_v; + /// The same for rfl::Positional. + static constexpr bool is_direct_positional = + rfl::internal::is_positional_v; + static constexpr bool has_implicit_value = + Annotations::num_implicit_value > 0; + + static_assert( + !is_short_around_positional(), + "Nested wrappers (Positional> or Short<..., Positional<...>>) " + "are not allowed."); + static_assert(Annotations::num_implicit_value <= 1, + "A field can have at most one rfl::ImplicitValue."); + static_assert(!is_positional || !has_implicit_value, + "A field cannot be both rfl::Positional and " + "rfl::ImplicitValue."); + + static constexpr std::string_view name() { return FieldType::name(); } +}; + +/// The short name of the _i-th field, or an empty string if it has none. +template +constexpr auto get_short_name() { + using Info = field_info; + if constexpr (Info::is_short) { + return Info::Annotations::short_name; + } + else { + return rfl::internal::StringLiteral<1>(""); + } +} + +/// Strips everything that does not change how a field is written on the +/// command line: optionals, pointers, rfl::Short, rfl::Positional, +/// rfl::ImplicitValue, rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a +/// ReflectionType (rfl::Validator, rfl::Description, rfl::Literal, ...), +/// reflectors and custom parsers. +template +auto unwrap_option_type() { + using U = std::remove_cvref_t; + if constexpr (std::is_pointer_v) { + return unwrap_option_type, ProcessorsType>(); + } + else if constexpr (parsing::is_optional_v) { + return unwrap_option_type(); + } + else if constexpr (parsing::is_unique_ptr_v + || parsing::is_shared_ptr_v) { + return unwrap_option_type(); + } + else if constexpr (parsing::is_box_v) { + return unwrap_option_type< + typename parsing::is_box::element_type, ProcessorsType>(); + } + else if constexpr (parsing::is_ref_v) { + return unwrap_option_type< + typename parsing::is_ref::element_type, ProcessorsType>(); + } + else if constexpr (rfl::internal::is_short_v + || rfl::internal::is_positional_v + || rfl::internal::is_implicit_value_v + || parsing::is_rename_v + || parsing::is_default_val_v + || parsing::is_skip_v) { + return unwrap_option_type(); + } + else if constexpr (rfl::internal::has_reflection_type_v) { + return unwrap_option_type(); + } + else if constexpr (rfl::internal::has_read_reflector) { + return unwrap_option_type< + typename Reflector::ReflType, ProcessorsType>(); + } + else if constexpr (requires { + typename Parser:: + CustomParserHelperStruct; + }) { + return unwrap_option_type< + typename Parser::CustomParserHelperStruct, + ProcessorsType>(); + } + else { + return std::type_identity{}; + } +} + +template +using unwrapped_option_t = + typename decltype(unwrap_option_type())::type; + +/// Whether the reader treats T as a struct whose fields are addressed as +/// `--field.sub-field`. +template +constexpr bool is_option_struct_v = + (std::is_class_v && std::is_aggregate_v && !parsing::is_array_v + && !parsing::is_rfl_array_v) + || rfl::internal::is_named_tuple_v; + +/// Whether an option for T may or may not need a value, depending on what +/// it holds: a variant or rfl::Generic can be a bool or a struct. Such an +/// option never takes the next token. +template +constexpr bool is_open_option_v = + parsing::is_variant_v || parsing::is_rfl_variant_v + || parsing::is_tagged_union_v || std::is_same_v; + +/// The NamedTuple whose fields are the options of the struct T: T itself if +/// it is an rfl::NamedTuple (whose names the processors leave alone), or T +/// with the processors applied. +template +using option_fields_t = typename std::conditional_t< + rfl::internal::is_named_tuple_v, std::type_identity, + rfl::internal::Processed>::type; + +/// The option for a field of type T wrapped in rfl::ImplicitValue. +template +Option implicit_value_option() { + using U = unwrapped_option_t; + using Annotations = cli_annotations_t; + static_assert(Annotations::num_implicit_value <= 1, + "A field can have at most one rfl::ImplicitValue."); + static_assert(!parsing::is_string_map_v && !is_option_struct_v, + "rfl::ImplicitValue must wrap a field that takes a value, not " + "a struct or a map."); + static_assert(!std::is_arithmetic_v || std::is_same_v + || Annotations::implicit_value.length > 0, + "rfl::ImplicitValue on a number needs an implicit value, such " + "as rfl::ImplicitValue."); + return Option{OptionKind::implicit_value, + std::string(Annotations::implicit_value.string_view())}; +} + +/// The option for a key of a map or of rfl::ExtraFields with values of +/// type T. +template +Option sub_key_option() { + using U = unwrapped_option_t; + if constexpr (cli_annotations_t::num_implicit_value > 0) { + return implicit_value_option(); + } + else if constexpr (std::is_same_v) { + return Option{OptionKind::flag}; + } + else if constexpr (parsing::is_string_map_v || is_option_struct_v + || is_open_option_v) { + return Option{OptionKind::other}; + } + else { + return Option{OptionKind::value}; + } +} + +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] = sub_key_option(); + if constexpr (cli_annotations_t::num_implicit_value == 0 + && (parsing::is_string_map_v + || (is_option_struct_v + && !VisitedType::template contains))) { + auto nested = std::make_shared(); + collect_value_options(nested.get()); + _options->open_prefix_options[_prefix] = std::move(nested); + } +} + +template +void add_option(const std::string& _path, Options* _options) { + using U = unwrapped_option_t; + if constexpr (cli_annotations_t::num_implicit_value > 0) { + _options->long_options[_path] = + implicit_value_option(); + } + else 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_open_prefix( + _prefix, _options); + } + else { + add_option( + _prefix + std::string(FieldType::name()), _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< + rfl::tuple_element_t<_is, typename NT::Fields>, ProcessorsType, + NextVisitedType>(_prefix, _options), + ...); + }(std::make_index_sequence()); +} + +/// 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}; + } +} + +/// The rfl::Short of a top-level field. +struct ShortAlias { + std::string name; + std::string path; + /// Whether rfl::Short is the outermost wrapper of the field. + bool is_direct = false; +}; + +/// Adds the short alias and the positional slot of the _i-th top-level +/// field, if it has them. +template +void add_short_and_positional(std::vector* _aliases, + std::vector* _wrapped_positionals, + Options* _options) { + using Info = field_info; + if constexpr (Info::is_short) { + _aliases->push_back(ShortAlias{ + std::string(get_short_name().string_view()), + std::string(Info::name()), Info::is_direct_short}); + } + if constexpr (Info::is_direct_positional) { + _options->positionals.emplace_back(Info::name()); + } + else if constexpr (Info::is_positional) { + _wrapped_positionals->emplace_back(Info::name()); + } +} + +/// An outermost rfl::Short always counts; two with the same name are kept +/// as an error (Options::duplicate_short_name). An +/// rfl::Short found through other wrappers counts only if no other field +/// has its name. +inline void add_short_aliases(const std::vector& _aliases, + Options* _options) { + for (const auto& alias : _aliases) { + if (alias.is_direct + && !_options->short_options.emplace(alias.name, alias.path).second + && _options->duplicate_short_name.empty()) { + _options->duplicate_short_name = alias.name; + } + } + for (const auto& alias : _aliases) { + const auto has_name = [&](const ShortAlias& _other) { + return _other.name == alias.name; + }; + if (!alias.is_direct + && std::count_if(_aliases.begin(), _aliases.end(), has_name) == 1) { + _options->short_options.emplace(alias.name, alias.path); + } + } +} + +template +void collect_short_and_positional(Options* _options) { + using NT = option_fields_t; + std::vector aliases; + std::vector wrapped_positionals; + [&](std::index_sequence<_is...>) { + (add_short_and_positional(&aliases, &wrapped_positionals, + _options), + ...); + }(std::make_index_sequence()); + add_short_aliases(aliases, _options); + // Outermost rfl::Positional fields take the first positional arguments, + // and those found through other wrappers the ones after them. + _options->positionals.insert(_options->positionals.end(), + wrapped_positionals.begin(), + wrapped_positionals.end()); +} + +/// Derives the options that T accepts from its fields: every long option, +/// with whether it is a flag, takes a value or has an implicit 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, 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; + collect_value_options>(&options); + if constexpr (is_option_struct_v) { + collect_short_and_positional(&options); + } + // As in argparse, -5 is a negative number unless a short option's name + // looks like a number (-1). + options.negative_numbers_are_options = false; + for (const auto& [name, path] : options.short_options) { + if (!name.empty() + && ((name[0] >= '0' && name[0] <= '9') || name[0] == '.')) { + options.negative_numbers_are_options = true; + } + } + return options; +} + +} // namespace rfl::cli::internal + +#endif diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index aeeafe61d..b26f54117 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -15,13 +15,14 @@ #include "../Result.hpp" #include "../internal/strings/utf8_conversions.hpp" -#include "long_options.hpp" +#include "options.hpp" #include "resolve_args.hpp" namespace rfl::cli { -/// Returns true if the token looks like a CLI option (starts with '-' -/// followed by a letter), as opposed to a negative number like "-42". +/// Returns true if the token looks like a CLI option ('-' followed by +/// anything except a digit or '.'), as opposed to a negative number like +/// "-42". /// This helps distinguish option flags from negative numeric values. /// @param _token The command-line token to check /// @return true if it looks like an option, false otherwise @@ -40,25 +41,31 @@ namespace internal { /// - Short options: -x value, -x=value, or -x (stored in `short_args`) /// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`) /// The special argument "--" forces all subsequent arguments to be treated as positional. -/// `_long_options` says which long options take a value. A long option that -/// takes a value consumes the next token when it is given without '='. -/// Others, boolean flags among them, never consume it. +/// `_options` says what each option does with the token that follows it +/// when it is given without '='. An option that takes a value consumes it, +/// and fails if there is none. A long boolean flag never consumes it; a +/// short one consumes it only if it is "true", "false", "1" or "0". An +/// option wrapped in rfl::ImplicitValue never consumes it and gets its +/// implicit value. Other long options never consume it. Short options +/// missing from `_options` consume it unless it looks like an option, as +/// they do without `_options`. /// Every element of `_args` is parsed; nothing is skipped as the program name. /// A token that looks like a negative number (-5, -.5) is a positional -/// argument unless `_negative_numbers_are_options` is true, as it is when the -/// target struct has a short option whose name looks like a number -/// (rfl::Short<"1", ...>). Then such tokens are short options, as in argparse. +/// argument unless `_options` has a short option whose name looks like a +/// number (rfl::Short<"1", ...>). Then such tokens are short options, as in +/// argparse. /// @param _args The command-line arguments to parse -/// @param _long_options The long options of the target struct +/// @param _options The options of the target struct (see make_options) /// @return A Result containing ParsedArgs with categorized arguments or an error /// --key=value / --key value / --flag → named /// -x value / -x=value / -x → short_args /// bare arguments → positional /// -- → everything after goes to positional inline rfl::Result parse_string_views( - std::span _args, const LongOptions& _long_options, - bool _negative_numbers_are_options) { + std::span _args, const Options& _options) { ParsedArgs result; + const bool negative_numbers_are_options = + _options.negative_numbers_are_options; const auto add_short = [&](std::string _key, std::string _val, std::string_view _raw) -> rfl::Result { @@ -69,6 +76,49 @@ inline rfl::Result parse_string_views( return true; }; + // The value of the option _args[*_i], given without '=', taking the next + // token if the option says so. + const auto take_value = [&](const Option& _option, std::string_view _raw, + bool _is_short, + size_t* _i) -> rfl::Result { + const bool has_next = *_i + 1 < _args.size(); + switch (_option.kind) { + case OptionKind::value: + // --key value, -k value + if (!has_next || looks_like_option(_args[*_i + 1])) { + return error( + "Missing value for option '" + std::string(_raw) + "'."); + } + return std::string(_args[++*_i]); + + case OptionKind::flag: + // -f false: a short flag takes a bool literal. A long flag never takes + // the next token: `--verbose 0` leaves "0" positional. Any other + // token stays where it is, so `-v input.txt` leaves "input.txt" + // positional. + if (_is_short && has_next && is_bool_literal(_args[*_i + 1])) { + return std::string(_args[++*_i]); + } + return std::string(); + + case OptionKind::implicit_value: + // Never takes the next token: `--help input.txt` leaves + // "input.txt" positional. + return _option.implicit_value; + + case OptionKind::other: + // A variant, rfl::Generic or nested struct. `--mode` never takes the + // next token; `-m fast` takes it unless it looks like an option. + if (_is_short && has_next && !looks_like_option(_args[*_i + 1])) { + return std::string(_args[++*_i]); + } + return std::string(); + + default: + return std::string(); + } + }; + bool force_positional = false; for (size_t i = 0; i < _args.size(); ++i) { const std::string_view arg_raw(_args[i]); @@ -93,20 +143,21 @@ inline rfl::Result parse_string_views( if (key.empty()) { return error("Empty key in argument: " + std::string(arg_raw)); } - const auto kind = _long_options.kind_of(key); - if (kind == LongOptionKind::unknown && _long_options.reject_unknown) { + const auto option = _options.find_long(key); + if (option.kind == OptionKind::unknown && _options.reject_unknown) { return error("Unknown option '--" + key + "'."); } auto val = std::string(); if (eq != std::string_view::npos) { val = std::string(arg.substr(eq + 1)); } - else if (kind == LongOptionKind::value) { - // --key value - if (i + 1 >= _args.size() || looks_like_option(_args[i + 1])) { - return error("Missing value for option '--" + key + "'."); + else { + auto v = take_value(option, arg_raw, false, &i); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + if (option.kind != OptionKind::value) { + result.named_without_value.insert(key); } - val = std::string(_args[++i]); } if (!result.named.emplace(std::move(key), std::move(val)).second) { return error("Duplicate argument: " + std::string(arg_raw)); @@ -118,7 +169,7 @@ inline rfl::Result parse_string_views( // A negative number such as -5 or -.5 is not an option; it falls through // to positional, unless the struct has a short option such as -1. if (looks_like_option(arg_raw) - || (_negative_numbers_are_options && arg_raw.size() >= 2 + || (negative_numbers_are_options && arg_raw.size() >= 2 && arg_raw[0] == '-')) { const auto arg = arg_raw.substr(1); const auto eq = arg.find('='); @@ -132,13 +183,25 @@ inline rfl::Result parse_string_views( continue; } - // -x value or -x (bool flag). - // Peek at next token: consume as value if it doesn't look like an option. + auto key = std::string(arg); + const auto option = _options.find_short(key); + const auto start = i; auto val = std::string(); - if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) { - val = std::string(_args[++i]); + if (option.kind == OptionKind::unknown) { + // Not in `_options`: consume the next token as the value if it + // doesn't look like an option. resolve_args reports unknown short + // options. + if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) { + val = std::string(_args[++i]); + } } - const auto r = add_short(std::string(arg), std::move(val), arg_raw); + else { + auto v = take_value(option, arg_raw, true, &i); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + } + result.short_without_equals[key] = i != start; + const auto r = add_short(std::move(key), std::move(val), arg_raw); if (!r) { return error(r.error().what()); } continue; } @@ -190,8 +253,7 @@ bool is_null(const S& _str) noexcept { /// `_first_index` is the index of the first element in error messages. template rfl::Result parse_strings(R&& _args, size_t _first_index, - const LongOptions& _long_options, - bool _negative_numbers_are_options) { + const Options& _options) { std::vector views; auto i = _first_index; for (auto&& arg : _args) { @@ -202,16 +264,14 @@ rfl::Result parse_strings(R&& _args, size_t _first_index, views.push_back(view); ++i; } - return parse_string_views(views, _long_options, - _negative_numbers_are_options); + return parse_string_views(views, _options); } /// Converts every element of `_args` to UTF-8 and parses it. /// `_first_index` is the index of the first element in error messages. template rfl::Result parse_wide_strings(R&& _args, size_t _first_index, - const LongOptions& _long_options, - bool _negative_numbers_are_options) { + const Options& _options) { std::vector narrow; auto i = _first_index; for (auto&& arg : _args) { @@ -227,8 +287,7 @@ rfl::Result parse_wide_strings(R&& _args, size_t _first_index, narrow.emplace_back(std::move(*str)); ++i; } - return parse_strings(narrow, _first_index, _long_options, - _negative_numbers_are_options); + return parse_strings(narrow, _first_index, _options); } /// Validates argc/argv and returns the arguments after argv[0], the program @@ -245,107 +304,78 @@ rfl::Result> skip_program_name( return std::span(argv + 1, static_cast(argc - 1)); } -/// Parses every element of `_args`, as parse_argv(_args, _long_options) does. -/// `_negative_numbers_are_options` is as for parse_string_views. -template +/// Parses a sequence of command-line arguments with the options of the +/// target struct, as rfl::cli::read does. Every element is parsed. +/// A negative number such as -5 or -.5 is a positional argument, unless +/// `_options.negative_numbers_are_options` is set: by default, and by +/// make_options if the struct has a short option like rfl::Short<"1", ...>. +/// @param _args The command-line arguments to parse +/// @param _options The options of the target struct (see make_options) +/// @return A Result containing ParsedArgs with categorized arguments or an error +template > requires StringRange || WideStringRange -rfl::Result parse_args(R&& _args, const LongOptions& _long_options, - bool _negative_numbers_are_options) { +rfl::Result parse_argv(R&& _args, const Options& _options) { if constexpr (StringRange) { - return parse_strings(std::forward(_args), 0, _long_options, - _negative_numbers_are_options); + return parse_strings(std::forward(_args), 0, _options); } else { - return parse_wide_strings(std::forward(_args), 0, _long_options, - _negative_numbers_are_options); + return parse_wide_strings(std::forward(_args), 0, _options); } } -/// Parses argc/argv, skipping argv[0], as parse_argv(argc, argv, -/// _long_options) does. -/// `_negative_numbers_are_options` is as for parse_string_views. -template -rfl::Result parse_args(int argc, const CharT* const argv[], - const LongOptions& _long_options, - bool _negative_numbers_are_options) { - return skip_program_name(argc, argv).and_then([&](auto _args) { - if constexpr (std::is_same_v) { - return parse_strings(_args, 1, _long_options, - _negative_numbers_are_options); - } else { - return parse_wide_strings(_args, 1, _long_options, - _negative_numbers_are_options); - } - }); +/// Parses argc/argv with the options of the target struct, skipping argv[0] +/// (the program name). +inline rfl::Result parse_argv(int argc, const char* const argv[], + const Options& _options) { + return skip_program_name(argc, argv).and_then( + [&](auto _args) { return parse_strings(_args, 1, _options); }); +} + +/// Parses wide argc/argv with the options of the target struct, skipping +/// argv[0] (the program name). Converts each wide string to UTF-8. +inline rfl::Result parse_argv(int argc, const wchar_t* const argv[], + const Options& _options) { + return skip_program_name(argc, argv).and_then( + [&](auto _args) { return parse_wide_strings(_args, 1, _options); }); } } // namespace internal -/// Parses a sequence of command-line arguments into categorized buckets. +/// Parses a sequence of command-line arguments into categorized buckets, +/// without knowing the target struct. /// Accepts a range of narrow or wide strings (wide strings are converted /// to UTF-8) or a braced list of narrow strings. A range of narrow strings /// must be multi-pass and must not yield temporary `std::string`s, as for /// rfl::cli::read. Every element is parsed: unlike the argc/argv overloads, /// the first one is NOT skipped as the program name. -/// A token such as -5 or -.5 is a negative number, so a positional argument. -/// @param _args The command-line arguments to parse -/// @param _long_options The long options of the target struct -/// @return A Result containing ParsedArgs with categorized arguments or an error -template > - requires internal::StringRange || internal::WideStringRange -rfl::Result parse_argv(R&& _args, - const LongOptions& _long_options) { - return internal::parse_args(std::forward(_args), _long_options, false); -} - -/// Parses a sequence of command-line arguments without knowing the target -/// struct. Long options never consume the next token, so values must be -/// passed as --key=value. A token such as -5 or -.5 is a short option, as it -/// always was in parse_argv(argc, argv). +/// Long options never consume the next token, so values must be passed as +/// --key=value. Short options consume it unless it looks like an option. A +/// token such as -5 or -.5 is a short option. resolve_args +/// then fixes up what depends on the types of T: bool flags and +/// rfl::ImplicitValue. /// @param _args The command-line arguments to parse /// @return A Result containing ParsedArgs with categorized arguments or an error template > requires internal::StringRange || internal::WideStringRange rfl::Result parse_argv(R&& _args) { - return internal::parse_args(std::forward(_args), LongOptions{}, true); -} - -/// Parses command-line arguments into categorized buckets, skipping argv[0] -/// (the program name). -/// @param argc Number of command-line arguments -/// @param argv Array of command-line argument strings -/// @param _long_options The long options of the target struct -/// @return A Result containing ParsedArgs with categorized arguments or an error -inline rfl::Result parse_argv(int argc, const char* const argv[], - const LongOptions& _long_options) { - return internal::parse_args(argc, argv, _long_options, false); + return internal::parse_argv(std::forward(_args), internal::Options{}); } /// Parses command-line arguments without knowing the target struct, /// skipping argv[0] (the program name). Long options never consume the next -/// token, so values must be passed as --key=value. A token such as -5 or -.5 -/// is a short option. +/// token, so values must be passed as --key=value. Short options consume it +/// unless it looks like an option. A token such as -5 or -.5 is a short +/// option. /// @param argc Number of command-line arguments /// @param argv Array of command-line argument strings /// @return A Result containing ParsedArgs with categorized arguments or an error inline rfl::Result parse_argv(int argc, const char* const argv[]) { - return internal::parse_args(argc, argv, LongOptions{}, true); + return internal::parse_argv(argc, argv, internal::Options{}); } inline rfl::Result parse_argv(int argc, char* argv[]) { return parse_argv(argc, static_cast(argv)); } -/// Parses wide-character command-line arguments into categorized buckets, -/// skipping argv[0] (the program name). Converts each wide string to UTF-8. -/// @param argc Number of wide-character command-line arguments -/// @param argv Array of wide-character command-line argument strings -/// @param _long_options The long options of the target struct -/// @return A Result containing ParsedArgs with UTF-8 encoded arguments -inline rfl::Result parse_argv(int argc, const wchar_t* const argv[], - const LongOptions& _long_options) { - return internal::parse_args(argc, argv, _long_options, false); -} - /// Parses wide-character command-line arguments without knowing the target /// struct. See the narrow overload. /// @param argc Number of wide-character command-line arguments @@ -353,7 +383,7 @@ inline rfl::Result parse_argv(int argc, const wchar_t* const argv[], /// @return A Result containing ParsedArgs with UTF-8 encoded arguments inline rfl::Result parse_argv(int argc, const wchar_t* const argv[]) { - return internal::parse_args(argc, argv, LongOptions{}, true); + return internal::parse_argv(argc, argv, internal::Options{}); } inline rfl::Result parse_argv(int argc, wchar_t* argv[]) { diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index 786bd2fcb..8d5e1e435 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -9,7 +9,7 @@ #include "../SnakeCaseToKebabCase.hpp" #include "Parser.hpp" #include "Reader.hpp" -#include "long_options.hpp" +#include "options.hpp" #include "parse_argv.hpp" #include "resolve_args.hpp" @@ -17,24 +17,17 @@ namespace rfl::cli { namespace internal { -/// True if T has a short option whose name looks like a number, such as -/// rfl::Short<"1", ...>. Then, as in argparse, tokens like -5 and -.5 are -/// short options rather than negative numbers. -template -constexpr bool negative_numbers_are_options() { - using ProcessorsType = Processors; - using NT = rfl::internal::processed_t; - return has_numeric_short_name(std::make_index_sequence{}); -} - -/// Categorizes the arguments with `_parse`, which takes the long options of -/// T (see make_long_options) and returns ParsedArgs, and turns them into a -/// struct. +/// Categorizes the arguments with `_parse`, which takes the options of T +/// (see make_options) and returns ParsedArgs, and turns them into a struct. template rfl::Result parse_and_read(const ParseFn& _parse) { using ProcessorsType = Processors; - return _parse(make_long_options()) - .and_then(resolve_args) + const auto options = make_options(); + return check_short_names(options) + .and_then([&](bool) { return _parse(options); }) + .and_then([&](ParsedArgs _parsed) { + return resolve_args(std::move(_parsed), options); + }) .and_then([](auto _args) -> rfl::Result { const auto r = Reader(); const auto var = CliVarType{&_args, "", std::nullopt}; @@ -72,9 +65,7 @@ template || internal::WideStringRange rfl::Result read(R&& _args) { return internal::parse_and_read([&](const auto& _options) { - return internal::parse_args( - std::forward(_args), _options, - internal::negative_numbers_are_options()); + return internal::parse_argv(std::forward(_args), _options); }); } @@ -88,11 +79,10 @@ rfl::Result read(R&& _args) { /// @return A Result containing the parsed struct or an error template rfl::Result read(int argc, const char* const argv[]) { - return internal::parse_and_read([&](const auto& _options) { - return internal::parse_args( - argc, argv, _options, - internal::negative_numbers_are_options()); - }); + return internal::parse_and_read( + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); } template @@ -110,11 +100,10 @@ rfl::Result read(int argc, char* argv[]) { /// @return A Result containing the parsed struct or an error template rfl::Result read(int argc, const wchar_t* const argv[]) { - return internal::parse_and_read([&](const auto& _options) { - return internal::parse_args( - argc, argv, _options, - internal::negative_numbers_are_options()); - }); + return internal::parse_and_read( + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); } template diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 3cf639f1d..36cd3f30e 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -1,17 +1,15 @@ #ifndef RFL_CLI_RESOLVE_ARGS_HPP_ #define RFL_CLI_RESOLVE_ARGS_HPP_ +#include #include #include #include -#include #include #include #include "../Result.hpp" -#include "../internal/is_positional.hpp" -#include "../internal/is_short.hpp" -#include "../internal/processed_t.hpp" +#include "options.hpp" namespace rfl::cli { @@ -23,200 +21,54 @@ struct ParsedArgs { std::vector positional; /// Insertion order of short arg keys (for stable reclaim ordering). std::vector short_order; + /// The keys of `named` given without '=' that took no value (`--help`). + std::set named_without_value; + /// The keys of `short_args` given without '=' (`-h`, `-h x`), and whether + /// they took the next token as their value. + std::map short_without_equals; }; namespace internal { -template -consteval bool check_no_nested_wrappers() { - if constexpr (_is_positional) { - return !rfl::internal::is_short_v; - } - else if constexpr (_is_short) { - return !rfl::internal::is_positional_v; - } - else { - return true; - } -} - -template -struct field_info { - using FieldType = rfl::tuple_element_t<_i, typename NamedTupleType::Fields>; - using InnerType = typename FieldType::Type; - - static constexpr bool is_positional = - rfl::internal::is_positional_v; - static constexpr bool is_short = rfl::internal::is_short_v; - - static_assert( - check_no_nested_wrappers(), - "Nested wrappers (Positional> or Short<..., Positional<...>>) " - "are not allowed."); - - static constexpr std::string_view name() { return FieldType::name(); } -}; - -template -constexpr auto get_short_name() { - using Info = field_info; - if constexpr (Info::is_short) { - return Info::InnerType::short_name_; - } - else { - return rfl::internal::StringLiteral<1>(""); - } -} - -template -void collect_positional_names( - std::vector& _names, - std::index_sequence<_i, _is...> -) { - using Info = field_info; - if constexpr (Info::is_positional) { - _names.emplace_back(Info::name()); - } - if constexpr (sizeof...(_is) > 0) { - collect_positional_names(_names, std::index_sequence<_is...>{}); - } -} - -template -void collect_positional_names( - std::vector&, - std::index_sequence<> -) {} - -template -rfl::Result collect_short_mapping( - std::map& _mapping, - std::index_sequence<_i, _is...> -) { - using Info = field_info; - if constexpr (Info::is_short) { - constexpr auto short_lit = get_short_name(); - const auto short_str = std::string(short_lit.string_view()); - const auto long_str = std::string(Info::name()); - if (!_mapping.emplace(short_str, long_str).second) { - return rfl::error( - "Duplicate short name '-" + short_str + "' in struct definition."); +/// Applies what parse_argv could not know without the option table. +/// Without it, every short option takes the next token, so `-v somefile` +/// makes "somefile" the value of -v. If -v is a bool flag (by its type once +/// unwrapped, as in options.hpp), "somefile" is not a valid bool value and +/// is returned to the positional list. An rfl::ImplicitValue option never +/// takes the next token: `-h in.txt` returns "in.txt" to the positional +/// list, and `-h` and `--help` given without a value get the implicit +/// value. We iterate in insertion order (short_order) to preserve argv +/// ordering. +inline void apply_option_kinds(const Options& _options, ParsedArgs* _parsed) { + for (const auto& key : _parsed->named_without_value) { + const auto option = _options.find_long(key); + const auto it = _parsed->named.find(key); + if (option.kind == OptionKind::implicit_value + && it != _parsed->named.end()) { + it->second = option.implicit_value; } } - if constexpr (sizeof...(_is) > 0) { - return collect_short_mapping( - _mapping, std::index_sequence<_is...>{}); - } - return true; -} - -template -rfl::Result collect_short_mapping( - std::map&, - std::index_sequence<> -) { - return true; -} - -template -consteval bool is_short_bool() { - using Info = field_info; - if constexpr (Info::is_short) { - return std::is_same_v; - } - else { - return false; - } -} - -template -void collect_short_bool_names( - std::set& _names, - std::index_sequence<_i, _is...> -) { - if constexpr (is_short_bool()) { - constexpr auto short_lit = get_short_name(); - _names.emplace(short_lit.string_view()); - } - if constexpr (sizeof...(_is) > 0) { - collect_short_bool_names( - _names, std::index_sequence<_is...>{}); - } -} - -template -void collect_short_bool_names( - std::set&, - std::index_sequence<> -) {} - -/// Returns true if a field of NamedTupleType has a short name that looks -/// like a number, such as rfl::Short<"1", ...>. Then, as in argparse, -/// parse_argv treats tokens like -5 and -.5 as short options rather than as -/// negative numbers. -template -consteval bool has_numeric_short_name(std::index_sequence<_is...>) { - const auto is_numeric = [](std::string_view _name) { - return !_name.empty() - && ((_name[0] >= '0' && _name[0] <= '9') || _name[0] == '.'); - }; - return (is_numeric(get_short_name().string_view()) - || ...); -} - -} // namespace internal - -/// Resolves ParsedArgs into a flat key-value map using compile-time -/// metadata from the target struct T. -/// This function: -/// 1. Maps positional arguments to their corresponding field names based on declaration order -/// 2. Expands short arguments (e.g., -p) to long names (e.g., --port) using Short<> annotations -/// 3. Handles special cases like boolean short flags that don't consume values -/// 4. Detects conflicts between different ways of specifying the same field -/// @tparam T The target struct type -/// @tparam ProcessorsType The processors applied to the struct -/// @param _parsed The parsed command-line arguments -/// @return A Result containing a flat map of field names to values or an error -template -rfl::Result> resolve_args( - ParsedArgs _parsed -) { - using NT = rfl::internal::processed_t; - constexpr auto sz = NT::size(); - using Indices = std::make_index_sequence; - - // Collect positional field names (in declaration order). - std::vector positional_names; - internal::collect_positional_names(positional_names, Indices{}); - - // Collect short-to-long mapping. - std::map short_to_long; - const auto short_result = - internal::collect_short_mapping(short_to_long, Indices{}); - if (!short_result) { - return rfl::error(short_result.error().what()); - } - // Reclaim non-boolean values from short bool flags. - // parse_argv doesn't know types, so `-v somefile` consumes "somefile" as - // the value of -v. Since -v is bool, "somefile" is not a valid bool value - // and must be returned to the positional list. - // We iterate in insertion order (short_order) to preserve argv ordering. - std::set short_bool_names; - internal::collect_short_bool_names(short_bool_names, Indices{}); std::vector reclaimed; - for (const auto& short_name : _parsed.short_order) { - if (!short_bool_names.count(short_name)) { - continue; - } - auto it = _parsed.short_args.find(short_name); - if (it == _parsed.short_args.end()) { + for (const auto& short_name : _parsed->short_order) { + const auto option = _options.find_short(short_name); + auto it = _parsed->short_args.find(short_name); + if (it == _parsed->short_args.end()) { continue; } auto& value = it->second; - if (value != "true" && value != "false" - && value != "0" && value != "1" - && !value.empty()) { + if (option.kind == OptionKind::implicit_value) { + const auto how = _parsed->short_without_equals.find(short_name); + if (how == _parsed->short_without_equals.end()) { + continue; + } + if (how->second) { + reclaimed.push_back(value); + } + value = option.implicit_value; + } + else if (option.kind == OptionKind::flag && !value.empty() + && !is_bool_literal(value)) { reclaimed.push_back(value); value.clear(); } @@ -224,15 +76,40 @@ rfl::Result> resolve_args( // Insert reclaimed values before existing positional args to preserve // the original argv order: `-v file1 file2` → positional ["file1", "file2"]. if (!reclaimed.empty()) { - _parsed.positional.insert( - _parsed.positional.begin(), + _parsed->positional.insert( + _parsed->positional.begin(), std::make_move_iterator(reclaimed.begin()), std::make_move_iterator(reclaimed.end())); } +} +/// Fails if two fields of the struct have the same outermost rfl::Short +/// name, so every read of such a struct fails. +inline rfl::Result check_short_names(const Options& _options) { + if (!_options.duplicate_short_name.empty()) { + return rfl::error("Duplicate short name '-" + _options.duplicate_short_name + + "' in struct definition."); + } + return true; +} + +/// Resolves ParsedArgs into a flat key-value map using the options of the +/// target struct. +/// This function: +/// 1. Maps positional arguments to their corresponding field names based on declaration order +/// 2. Expands short arguments (e.g., -p) to long names (e.g., --port) using Short<> annotations +/// 3. Detects conflicts between different ways of specifying the same field +/// The caller checks the short names first (check_short_names). +/// @param _parsed The arguments, parsed by parse_argv with the same options +/// @param _options The options of the target struct (see make_options) +/// @return A Result containing a flat map of field names to values or an error +inline rfl::Result> resolve_args( + ParsedArgs _parsed, const Options& _options +) { auto& result = _parsed.named; // Merge positional args. + const auto& positional_names = _options.positionals; if (_parsed.positional.size() > positional_names.size()) { auto msg = std::string("Too many positional arguments: expected at most "); msg += std::to_string(positional_names.size()); @@ -253,8 +130,8 @@ rfl::Result> resolve_args( // Merge short args. for (auto& [short_name, value] : _parsed.short_args) { - const auto it = short_to_long.find(short_name); - if (it == short_to_long.end()) { + const auto it = _options.short_options.find(short_name); + if (it == _options.short_options.end()) { return rfl::error("Unknown short argument: -" + short_name); } const auto& long_name = it->second; @@ -269,6 +146,31 @@ rfl::Result> resolve_args( return std::move(result); } +} // namespace internal + +/// Resolves ParsedArgs into a flat key-value map using compile-time +/// metadata from the target struct T. Like the overload taking the options +/// of T, but for arguments parsed by parse_argv without them: values that +/// boolean and rfl::ImplicitValue short options took from the next token +/// are returned to the positional arguments, and rfl::ImplicitValue +/// options given without a value get their implicit value. +/// @tparam T The target struct type +/// @tparam ProcessorsType The processors applied to the struct +/// @param _parsed The parsed command-line arguments +/// @return A Result containing a flat map of field names to values or an error +template +rfl::Result> resolve_args( + ParsedArgs _parsed +) { + const auto options = internal::make_options(); + const auto short_names = internal::check_short_names(options); + if (!short_names) { + return rfl::error(short_names.error().what()); + } + internal::apply_option_kinds(options, &_parsed); + return internal::resolve_args(std::move(_parsed), options); +} + } // namespace rfl::cli #endif diff --git a/tests/cli/test_implicit_value.cpp b/tests/cli/test_implicit_value.cpp new file mode 100644 index 000000000..c628a5aab --- /dev/null +++ b/tests/cli/test_implicit_value.cpp @@ -0,0 +1,297 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_implicit_value { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +enum class Color { red, green, blue }; + +struct Opts { + rfl::Positional> input; + rfl::Short<"h", rfl::ImplicitValue>> help; + rfl::ImplicitValue, "all"> help_reports; + rfl::ImplicitValue, "2"> verbosity = 0; + rfl::ImplicitValue, "green"> color; + std::optional force_export; +}; + +TEST(cli, test_implicit_value_bare) { + const auto result = + read({"--help", "--help-reports", "--verbosity", "--color"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_EQ(o.help().value().value(), ""); + EXPECT_EQ(o.help_reports().value(), "all"); + EXPECT_EQ(o.verbosity().value(), 2); + EXPECT_EQ(o.color().value(), Color::green); + EXPECT_FALSE(o.input().has_value()); +} + +TEST(cli, test_implicit_value_with_equals) { + const auto result = read({"--help=tag", "--help-reports=memory", + "--verbosity=5", "--color=blue"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_EQ(o.help().value().value(), "tag"); + EXPECT_EQ(o.help_reports().value(), "memory"); + EXPECT_EQ(o.verbosity().value(), 5); + EXPECT_EQ(o.color().value(), Color::blue); +} + +TEST(cli, test_implicit_value_empty_with_equals) { + const auto result = read({"--help-reports="}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().help_reports().value(), ""); +} + +TEST(cli, test_implicit_value_does_not_consume_next_token) { + for (const char* option : {"--help", "--help-reports", "--verbosity", "-h"}) { + const auto result = read({option, "r.rep"}); + ASSERT_TRUE(result) << option << ": " << result.error().what(); + EXPECT_EQ(result.value().input().value(), "r.rep") << option; + } + const auto result = read({"--help-reports", "--force-export"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().help_reports().value(), "all"); + EXPECT_EQ(result.value().force_export, true); +} + +TEST(cli, test_implicit_value_next_token_is_too_many_positionals) { + const auto result = read({"in.rep", "--help-reports", "memory"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Too many positional arguments: expected at most 1, got 2."); +} + +TEST(cli, test_implicit_value_absent) { + const auto result = read({"r.rep"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_FALSE(o.help().value().has_value()); + EXPECT_FALSE(o.help_reports().has_value()); + EXPECT_EQ(o.verbosity().value(), 0); + EXPECT_FALSE(o.color().has_value()); + EXPECT_EQ(rfl::json::write(o), R"({"input":"r.rep","verbosity":0})"); +} + +TEST(cli, test_implicit_value_short) { + const auto bare = read({"-h"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().help().value().value(), ""); + + const auto with_value = read({"-h=tag", "r.rep"}); + ASSERT_TRUE(with_value) << with_value.error().what(); + EXPECT_EQ(with_value.value().help().value().value(), "tag"); + EXPECT_EQ(with_value.value().input().value(), "r.rep"); +} + +struct Required { + rfl::ImplicitValue tag; +}; + +TEST(cli, test_implicit_value_required) { + const auto absent = read({}); + ASSERT_FALSE(absent); + EXPECT_EQ(std::string(absent.error().what()), + "Field named 'tag' not found."); + + const auto bare = read({"--tag"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().tag(), "x"); +} + +struct Database { + rfl::ImplicitValue, "require"> ssl_mode; +}; + +// The same option, wrapped in other orders and in a nested struct. +struct Orders { + rfl::ImplicitValue>, "A"> a; + rfl::Description<"B", rfl::Short<"b", rfl::ImplicitValue< + std::optional, "B">>> + b; + rfl::Short<"c", rfl::Description<"C", rfl::ImplicitValue< + std::optional, "C">>> + c; + rfl::Rename<"dee", rfl::ImplicitValue, "D">> d; + std::optional> e; + rfl::DefaultVal> f = std::string("f"); + rfl::ImplicitValue, "G"> g = std::string("g"); + std::optional database; + rfl::Positional> input; +}; + +TEST(cli, test_implicit_value_wrapper_orders) { + const auto bare = + read({"-a", "-b", "-c", "--dee", "--e", "--f", + "--g", "--database.ssl-mode", "r.rep"}); + ASSERT_TRUE(bare) << bare.error().what(); + const auto& o = bare.value(); + EXPECT_EQ(o.a().value().value(), "A"); + EXPECT_EQ(o.b().value().value().value(), "B"); + EXPECT_EQ(o.c().value().value().value(), "C"); + EXPECT_EQ(o.d().value().value(), "D"); + EXPECT_EQ(o.e.value().value(), "E"); + EXPECT_EQ(o.f().value(), "F"); + EXPECT_EQ(o.g().value(), "G"); + EXPECT_EQ(o.database->ssl_mode().value(), "require"); + EXPECT_EQ(o.input().value(), "r.rep"); + + const auto with_values = read( + {"-a=1", "--b=2", "-c=3", "--dee=4", "--e=5", "--f=6", "--g=7", + "--database.ssl-mode=off"}); + ASSERT_TRUE(with_values) << with_values.error().what(); + const auto& v = with_values.value(); + EXPECT_EQ(v.a().value().value(), "1"); + EXPECT_EQ(v.b().value().value().value(), "2"); + EXPECT_EQ(v.c().value().value().value(), "3"); + EXPECT_EQ(v.d().value().value(), "4"); + EXPECT_EQ(v.e.value().value(), "5"); + EXPECT_EQ(v.f().value(), "6"); + EXPECT_EQ(v.g().value(), "7"); + EXPECT_EQ(v.database->ssl_mode().value(), "off"); + + const auto absent = read({}); + ASSERT_TRUE(absent) << absent.error().what(); + EXPECT_FALSE(absent.value().a().value().has_value()); + EXPECT_FALSE(absent.value().e.has_value()); + EXPECT_EQ(absent.value().f().value(), "f"); + EXPECT_EQ(absent.value().g().value(), "g"); +} + +TEST(cli, test_implicit_value_options) { + const auto options = + rfl::cli::internal::make_options>(); + const auto help_reports = options.find_long("help-reports"); + EXPECT_EQ(help_reports.kind, rfl::cli::internal::OptionKind::implicit_value); + EXPECT_EQ(help_reports.implicit_value, "all"); + const auto help = options.find_short("h"); + EXPECT_EQ(help.kind, rfl::cli::internal::OptionKind::implicit_value); + EXPECT_EQ(help.implicit_value, ""); + EXPECT_EQ(options.find_long("force-export").kind, + rfl::cli::internal::OptionKind::flag); +} + +TEST(cli, test_implicit_value_without_options_table) { + // parse_argv without the options cannot know that --help-reports and -h + // have implicit values. resolve_args applies them, and gives back the + // token that -h took. + using ProcessorsType = rfl::Processors; + const auto resolve = + [](std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::parse_argv(static_cast(_args.size()), + _args.data()) + .and_then([](rfl::cli::ParsedArgs _parsed) { + return rfl::cli::resolve_args( + std::move(_parsed)); + }); + }; + + const auto bare = resolve({"--help-reports", "-h", "in.rep", "--verbosity"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().at("help-reports"), "all"); + EXPECT_EQ(bare.value().at("help"), ""); + EXPECT_EQ(bare.value().at("verbosity"), "2"); + EXPECT_EQ(bare.value().at("input"), "in.rep"); + + const auto with_values = + resolve({"--help-reports=", "-h=x", "--verbosity=3"}); + ASSERT_TRUE(with_values) << with_values.error().what(); + EXPECT_EQ(with_values.value().at("help-reports"), ""); + EXPECT_EQ(with_values.value().at("help"), "x"); + EXPECT_EQ(with_values.value().at("verbosity"), "3"); + EXPECT_FALSE(with_values.value().contains("input")); + + // With the options, parse_argv has already applied them. + const auto options = rfl::cli::internal::make_options(); + const char* args[] = {"program", "--help-reports", "-h", "in.rep"}; + const auto parsed = rfl::cli::internal::parse_argv(4, args, options); + ASSERT_TRUE(parsed) << parsed.error().what(); + const auto resolved = + rfl::cli::resolve_args(parsed.value()); + ASSERT_TRUE(resolved) << resolved.error().what(); + EXPECT_EQ(resolved.value().at("help-reports"), "all"); + EXPECT_EQ(resolved.value().at("help"), ""); + EXPECT_EQ(resolved.value().at("input"), "in.rep"); +} + +// An rfl::Rename renames the option if it is the outermost wrapper, as for +// every other wrapper. +struct RenamedOutermost { + rfl::Rename<"report", + rfl::ImplicitValue, "all">> + help_reports; + rfl::Rename<"out", rfl::Short<"o", rfl::ImplicitValue< + std::optional, "O">>> + output; + rfl::Rename<"in", rfl::Positional>> input; +}; + +TEST(cli, test_implicit_value_rename_outermost) { + const auto bare = + read({"--report", "x.rep"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().help_reports().value(), "all"); + EXPECT_EQ(bare.value().input().value(), "x.rep"); + + const auto named = read( + {"--report=r", "--out=o", "--in=i"}); + ASSERT_TRUE(named) << named.error().what(); + EXPECT_EQ(named.value().help_reports().value(), "r"); + EXPECT_EQ(named.value().output().value().value(), "o"); + EXPECT_EQ(named.value().input().value(), "i"); + + const auto short_bare = read({"-o", "x.rep"}); + ASSERT_TRUE(short_bare) << short_bare.error().what(); + EXPECT_EQ(short_bare.value().output().value().value(), "O"); + EXPECT_EQ(short_bare.value().input().value(), "x.rep"); + + const auto field_name = + read({"--help-reports"}); + ASSERT_FALSE(field_name); + EXPECT_EQ(std::string(field_name.error().what()), + "Unknown option '--help-reports'."); +} + +// Inside another wrapper, an rfl::Rename is ignored, as everywhere in +// reflect-cpp: the option keeps the field's name. +struct RenamedInside { + rfl::ImplicitValue>, "all"> + help_reports; + rfl::Short<"o", rfl::Rename<"out", std::optional>> output; + rfl::Positional>> input; +}; + +TEST(cli, test_rename_inside_other_wrappers_is_ignored) { + const auto named = read( + {"--help-reports", "--output", "o", "--input=i"}); + ASSERT_TRUE(named) << named.error().what(); + EXPECT_EQ(named.value().help_reports().value(), "all"); + EXPECT_EQ(named.value().output().value(), "o"); + EXPECT_EQ(named.value().input().value(), "i"); + + const auto short_name = read({"-o", "o", "in.txt"}); + ASSERT_TRUE(short_name) << short_name.error().what(); + EXPECT_EQ(short_name.value().output().value(), "o"); + EXPECT_EQ(short_name.value().input().value(), "in.txt"); + + const auto renamed = read({"--report"}); + ASSERT_FALSE(renamed); + EXPECT_EQ(std::string(renamed.error().what()), + "Unknown option '--report'."); +} + +} // namespace test_implicit_value diff --git a/tests/cli/test_long_option_values.cpp b/tests/cli/test_long_option_values.cpp index 742e37c64..4ecd31205 100644 --- a/tests/cli/test_long_option_values.cpp +++ b/tests/cli/test_long_option_values.cpp @@ -433,6 +433,29 @@ TEST(cli, test_long_variant_and_generic_without_value) { (std::variant(std::string("fast")))); } +struct ShortVariants { + rfl::Short<"m", std::variant> mode; + rfl::Short<"g", std::optional> extra; + rfl::Positional> input_file; +}; + +TEST(cli, test_short_variant_and_generic_take_next_token) { + // A short alias of a variant or rfl::Generic takes the next token unless + // it looks like an option. + const auto word = read({"-m", "fast", "in.txt"}); + ASSERT_TRUE(word) << word.error().what(); + EXPECT_EQ(word.value().mode(), + (std::variant(std::string("fast")))); + EXPECT_EQ(word.value().input_file(), "in.txt"); + + const auto number = read({"-m", "5", "-g", "x"}); + ASSERT_TRUE(number) << number.error().what(); + EXPECT_EQ(number.value().mode(), (std::variant(5))); + ASSERT_TRUE(number.value().extra().has_value()); + EXPECT_EQ(number.value().extra()->to_string().value(), "x"); + EXPECT_FALSE(number.value().input_file().has_value()); +} + TEST(cli, test_long_space_range_overload) { // The range overload of rfl::cli::read uses the option table too. const std::vector args = {"--sql", "SELECT 1", "--verbose", @@ -527,15 +550,15 @@ TEST(cli, test_parse_argv_without_long_options) { TEST(cli, test_parse_argv_with_long_options) { const auto options = - rfl::cli::make_long_options>(); - EXPECT_EQ(options.kind_of("sql"), rfl::cli::LongOptionKind::value); - EXPECT_EQ(options.kind_of("verbose"), rfl::cli::LongOptionKind::flag); - EXPECT_EQ(options.kind_of("input_file"), rfl::cli::LongOptionKind::value); - EXPECT_EQ(options.kind_of("nope"), rfl::cli::LongOptionKind::unknown); + rfl::cli::internal::make_options>(); + EXPECT_EQ(options.find_long("sql").kind, rfl::cli::internal::OptionKind::value); + EXPECT_EQ(options.find_long("verbose").kind, rfl::cli::internal::OptionKind::flag); + EXPECT_EQ(options.find_long("input_file").kind, rfl::cli::internal::OptionKind::value); + EXPECT_EQ(options.find_long("nope").kind, rfl::cli::internal::OptionKind::unknown); const wchar_t* args[] = {L"program", L"--sql", L"SELECT 1"}; const auto parsed = - rfl::cli::parse_argv(3, const_cast(args), options); + rfl::cli::internal::parse_argv(3, const_cast(args), options); ASSERT_TRUE(parsed) << parsed.error().what(); EXPECT_EQ(parsed.value().named.at("sql"), "SELECT 1"); EXPECT_TRUE(parsed.value().positional.empty()); diff --git a/tests/cli/test_wrapper_order.cpp b/tests/cli/test_wrapper_order.cpp new file mode 100644 index 000000000..5cdf0016b --- /dev/null +++ b/tests/cli/test_wrapper_order.cpp @@ -0,0 +1,327 @@ +#include + +#include +#include +#include +#include +#include + +// rfl::Short and rfl::Positional work through rfl::DefaultVal, std::optional, +// rfl::Description, rfl::Rename and rfl::Deprecated, in either order. +namespace test_wrapper_order { + +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 Shorts { + rfl::DefaultVal> output = std::string("o"); + rfl::Short<"O", rfl::DefaultVal> other_output = + std::string("O"); + std::optional> format; + rfl::Short<"F", std::optional> other_format; + rfl::Description<"Log file", rfl::Short<"l", std::optional>> + log; + rfl::Short<"L", rfl::Description<"Level", rfl::DefaultVal>> level = 1; + rfl::Rename<"outDir", rfl::Short<"d", std::optional>> out_dir; + rfl::Deprecated<"Use -j.", "Threads", rfl::Short<"t", rfl::DefaultVal>> + threads = 2; + rfl::Short<"j", rfl::Deprecated<"", "Jobs", rfl::DefaultVal>> jobs = 3; + rfl::Description<"Title", rfl::DefaultVal>> + title = std::string("T"); +}; + +TEST(cli, test_short_through_wrappers_given) { + const auto result = read( + {"-o", "a", "-O", "b", "-f", "c", "-F", "d", "-l", "e", "-L", "4", "-d", + "f", "-t", "5", "-j", "6", "-T", "g"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& s = result.value(); + EXPECT_EQ(s.output().value(), "a"); + EXPECT_EQ(s.other_output().value(), "b"); + EXPECT_EQ(s.format.value().value(), "c"); + EXPECT_EQ(s.other_format().value(), "d"); + EXPECT_EQ(s.log().value().value(), "e"); + EXPECT_EQ(s.level().value().value(), 4); + EXPECT_EQ(s.out_dir().value().value(), "f"); + EXPECT_EQ(s.threads().value().value(), 5); + EXPECT_EQ(s.jobs().value().value(), 6); + EXPECT_EQ(s.title().value().value(), "g"); +} + +TEST(cli, test_short_through_wrappers_absent) { + const auto result = read({}); + ASSERT_TRUE(result) << result.error().what(); + const auto& s = result.value(); + EXPECT_EQ(s.output().value(), "o"); + EXPECT_EQ(s.other_output().value(), "O"); + EXPECT_FALSE(s.format.has_value()); + EXPECT_FALSE(s.other_format().has_value()); + EXPECT_FALSE(s.log().value().has_value()); + EXPECT_EQ(s.level().value().value(), 1); + EXPECT_FALSE(s.out_dir().value().has_value()); + EXPECT_EQ(s.threads().value().value(), 2); + EXPECT_EQ(s.jobs().value().value(), 3); + EXPECT_EQ(s.title().value().value(), "T"); +} + +TEST(cli, test_short_through_wrappers_conflict_with_long) { + const auto result = read({"-d", "a", "--outDir=b"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Conflict: '-d' and '--outDir' both provided."); +} + +// `second` and `fourth` are rfl::Positional outermost, so they take the first +// two arguments, as when only they were positional. The others follow in +// declaration order. +struct Positionals { + rfl::DefaultVal> first = std::string("1"); + rfl::Positional> second = std::string("2"); + rfl::Description<"Third", rfl::Positional>> third; + rfl::Positional>> + fourth; + std::optional> fifth; + rfl::Rename<"sixth", rfl::Positional>> sixth_; + rfl::Deprecated<"", "Seventh", rfl::Positional>> + seventh; + std::optional verbose; +}; + +TEST(cli, test_positional_through_wrappers_given) { + const auto result = read( + {"a", "b", "c", "--verbose", "d", "e", "f", "g"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& p = result.value(); + EXPECT_EQ(p.second().value(), "a"); + EXPECT_EQ(p.fourth().value().value(), "b"); + EXPECT_EQ(p.first().value(), "c"); + EXPECT_EQ(p.third().value().value(), "d"); + EXPECT_EQ(p.fifth.value().value(), "e"); + EXPECT_EQ(p.sixth_().value().value(), "f"); + EXPECT_EQ(p.seventh().value().value(), "g"); + EXPECT_EQ(p.verbose, true); +} + +TEST(cli, test_positional_through_wrappers_absent) { + const auto result = read({"a"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& p = result.value(); + EXPECT_EQ(p.second().value(), "a"); + EXPECT_EQ(p.first().value(), "1"); + EXPECT_FALSE(p.third().value().has_value()); + EXPECT_FALSE(p.fifth.has_value()); + EXPECT_FALSE(p.seventh().value().has_value()); + + const auto none = read({}); + ASSERT_TRUE(none) << none.error().what(); + EXPECT_EQ(none.value().first().value(), "1"); + EXPECT_EQ(none.value().second().value(), "2"); +} + +TEST(cli, test_positional_through_wrappers_by_name) { + const auto result = read({"--sixth=f", "a"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().second().value(), "a"); + EXPECT_EQ(result.value().sixth_().value().value(), "f"); +} + +// A Positional found through other wrappers comes after the outermost ones, +// so a struct that worked when only those were positional reads the same. +struct WrappedPositionalFirst { + std::optional> out; + rfl::Positional in; +}; + +TEST(cli, test_outermost_positionals_come_first) { + const auto one = read({"x"}); + ASSERT_TRUE(one) << one.error().what(); + EXPECT_EQ(one.value().in(), "x"); + EXPECT_FALSE(one.value().out.has_value()); + + const auto two = read({"x", "y"}); + ASSERT_TRUE(two) << two.error().what(); + EXPECT_EQ(two.value().in(), "x"); + EXPECT_EQ(two.value().out.value().value(), "y"); +} + +struct ShortFlags { + rfl::Short<"q", rfl::DefaultVal> quiet = false; + rfl::Short<"v", std::optional> verbose; + rfl::Description<"Dry run", rfl::Short<"n", bool>> dry_run; + rfl::DefaultVal> force = false; + rfl::Positional> input; + rfl::Positional> output; +}; + +TEST(cli, test_short_flags_through_wrappers_do_not_consume_token) { + for (const char* flag : {"-q", "-v", "-n", "-f"}) { + std::vector args = {flag, "in.rep"}; + if (std::string(flag) != "-n") { + args.push_back("--dry-run=false"); + } + const auto result = read(args); + ASSERT_TRUE(result) << flag << ": " << result.error().what(); + EXPECT_EQ(result.value().input().value(), "in.rep") << flag; + } + + const auto result = + read({"-q", "-v", "in.rep", "-n", "out.csv", "-f"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& f = result.value(); + EXPECT_TRUE(f.quiet().value()); + EXPECT_EQ(f.verbose(), true); + EXPECT_TRUE(f.dry_run().value()); + EXPECT_TRUE(f.force().value()); + EXPECT_EQ(f.input().value(), "in.rep"); + EXPECT_EQ(f.output().value(), "out.csv"); +} + +TEST(cli, test_short_flags_through_wrappers_keep_argv_order) { + const auto result = read({"in.rep", "-q", "out.csv", "-n"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input().value(), "in.rep"); + EXPECT_EQ(result.value().output().value(), "out.csv"); +} + +TEST(cli, test_short_flags_through_wrappers_take_bool_literal) { + const auto result = + read({"-q", "true", "-v", "0", "-n", "false", "-f=1", "x"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& f = result.value(); + EXPECT_TRUE(f.quiet().value()); + EXPECT_EQ(f.verbose(), false); + EXPECT_FALSE(f.dry_run().value()); + EXPECT_TRUE(f.force().value()); + EXPECT_EQ(f.input().value(), "x"); +} + +TEST(cli, test_short_flags_through_wrappers_explicit_value_is_not_reclaimed) { + const auto result = read({"-q=in.rep", "-n"}); + ASSERT_FALSE(result); + EXPECT_NE(std::string(result.error().what()) + .find("Could not cast 'in.rep' to boolean for key 'quiet'."), + std::string::npos) + << result.error().what(); +} + +TEST(cli, test_short_flags_through_wrappers_without_options_table) { + // parse_argv without the options lets -q take "in.rep". resolve_args + // gives it back to the positional arguments, as for Short<"v", bool>. + const char* args[] = {"program", "-q", "in.rep", "-n"}; + const auto parsed = rfl::cli::parse_argv(4, const_cast(args)); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().short_args.at("q"), "in.rep"); + const auto resolved = rfl::cli::resolve_args< + ShortFlags, rfl::Processors>(parsed.value()); + ASSERT_TRUE(resolved) << resolved.error().what(); + EXPECT_EQ(resolved.value().at("quiet"), ""); + EXPECT_EQ(resolved.value().at("input"), "in.rep"); +} + +struct ShortValues { + rfl::Short<"o", std::string> output; + rfl::Short<"p", rfl::DefaultVal> port = 80; +}; + +TEST(cli, test_short_missing_value) { + for (const auto& args : std::vector>{ + {"-o"}, {"-o", "-p", "1"}, {"-o", "--", "x"}}) { + const auto result = read(args); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Missing value for option '-o'."); + } + const auto empty = read({"-o=", "-p", "-1"}); + ASSERT_TRUE(empty) << empty.error().what(); + EXPECT_EQ(empty.value().output(), ""); + EXPECT_EQ(empty.value().port().value(), -1); +} + +// Of several rfl::Short and rfl::Positional on one field, the outermost +// counts, as when only the outermost wrapper was looked at. +struct ShortInShort { + rfl::Short<"a", rfl::Short<"b", std::string>> value; +}; + +struct PositionalInShort { + rfl::Short<"o", rfl::Description<"Out", rfl::Positional>> out; +}; + +struct PositionalInPositional { + rfl::Positional> input; +}; + +TEST(cli, test_outermost_short_or_positional_counts) { + const auto a = read({"-a", "x"}); + ASSERT_TRUE(a) << a.error().what(); + EXPECT_EQ(a.value().value().value(), "x"); + EXPECT_EQ(std::string(read({"-b", "x"}).error().what()), + "Unknown short argument: -b"); + + const auto b = read({"-o", "x"}); + ASSERT_TRUE(b) << b.error().what(); + EXPECT_EQ(b.value().out().value().value(), "x"); + EXPECT_EQ(std::string(read({"x"}).error().what()), + "Too many positional arguments: expected at most 0, got 1."); + + const auto c = read({"x"}); + ASSERT_TRUE(c) << c.error().what(); + EXPECT_EQ(c.value().input().value(), "x"); +} + +// A Short found through other wrappers counts only if no other field has its +// name. An outermost one always counts. +struct WrappedAndDirectShort { + rfl::Description<"Name", rfl::Short<"o", std::string>> name; + rfl::Short<"o", int> count; +}; + +struct TwoWrappedShorts { + rfl::Description<"A", rfl::Short<"o", std::string>> a; + rfl::Description<"B", rfl::Short<"o", std::string>> b; +}; + +TEST(cli, test_wrapped_short_name_taken_by_another_field) { + const auto direct = read({"-o", "5", "--name=x"}); + ASSERT_TRUE(direct) << direct.error().what(); + EXPECT_EQ(direct.value().count(), 5); + EXPECT_EQ(direct.value().name().value(), "x"); + + const auto both = read({"--a=x", "--b=y"}); + ASSERT_TRUE(both) << both.error().what(); + EXPECT_EQ(both.value().a().value(), "x"); + EXPECT_EQ(both.value().b().value(), "y"); + EXPECT_EQ(std::string(read({"-o", "x"}).error().what()), + "Unknown short argument: -o"); +} + +// Two fields with the same outermost Short compile, but every read fails. +struct DuplicateShort { + rfl::Short<"o", std::optional> a; + rfl::Short<"o", std::optional> b; +}; + +TEST(cli, test_duplicate_short_name_fails_every_read) { + for (const auto& args : std::vector>{ + {}, {"-o", "x"}, {"--a=x", "--b=y"}}) { + const auto result = read(args); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Duplicate short name '-o' in struct definition."); + } + + const char* argv[] = {"program", "--a=x"}; + const auto resolved = + rfl::cli::parse_argv(2, argv) + .and_then(rfl::cli::resolve_args< + DuplicateShort, rfl::Processors>); + ASSERT_FALSE(resolved); + EXPECT_EQ(std::string(resolved.error().what()), + "Duplicate short name '-o' in struct definition."); +} + +} // namespace test_wrapper_order