diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index f7672ebe..7c4443f7 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -119,14 +119,35 @@ 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`. + +Any other short option takes the next token as its value unless that token +looks like an option (`-` followed by anything except a digit or `.`): +`-o out.csv`, `-o=out.csv`. If the value is missing, parsing fails with +`Missing value for option '-o'.` Use `=` to pass an empty value or one that +starts with `-`: `-o=`, `-o=-x`. + +## Combining wrappers + +`Short` and `Positional` can be nested 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. + +Bare arguments go to the `Positional` fields in declaration order. Two fields +with the same `Short` name make every read fail with +`Duplicate short name '-o' in struct definition.` A field with more than one +`Short` or `Positional`, such as `rfl::Positional>` or +`rfl::Short<"o", rfl::Description<"...", rfl::Positional>>`, is a +compile-time error: ```cpp struct Config { @@ -161,12 +182,16 @@ struct Config { 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. -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 + what each option does with the next token and whether a short option's + name looks like a number. The public `parse_argv` has no table: it 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`. The public `resolve_args(parsed)`, + for arguments parsed without the table, also returns the tokens that bool + short flags took to the positional arguments. 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`. @@ -177,6 +202,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/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 diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 763f335b..85881e7b 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/options.hpp" #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp new file mode 100644 index 00000000..3fa06110 --- /dev/null +++ b/include/rfl/cli/options.hpp @@ -0,0 +1,356 @@ +#ifndef RFL_CLI_OPTIONS_HPP_ +#define RFL_CLI_OPTIONS_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.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/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`, `-k value` or `-k=value`. + value, + /// A known path whose kind cannot be decided from the type (a nested + /// struct, a map, a variant or rfl::Generic). `--key` + /// 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; +}; + +/// The options that a target struct accepts, built from its fields by +/// make_options on every read. parse_argv uses it to decide whether a short +/// option takes the next token as its value, and resolve_args to map short +/// aliases and positional arguments to fields. Names are the field names +/// after processors (kebab-case, rfl::Rename) are applied. +struct Options { + /// The options of the top-level fields, by name. + 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, in declaration order, wherever + /// rfl::Positional sits among a field's wrappers. Each takes one positional + /// argument. + std::vector positionals; + + /// 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 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); + return it == long_options.end() ? Option{} : it->second; + } + + /// 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); + } +}; + +/// 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"; +} + +/// What rfl::Short and rfl::Positional say about a field of type T. They are +/// found through rfl::DefaultVal, std::optional, rfl::Description, +/// rfl::Deprecated and rfl::Rename, in any order. `count` is the number of +/// rfl::Short and rfl::Positional wrappers; a field may have at most one. +template +struct cli_annotations { + static constexpr bool is_short = false; + static constexpr bool is_positional = false; + static constexpr rfl::internal::StringLiteral<1> short_name = ""; + static constexpr int count = 0; +}; + +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; + static constexpr int count = cli_annotations_t::count + 1; +}; + +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; + static constexpr int count = cli_annotations_t::count + 1; +}; + +/// 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; + + static_assert(Annotations::count <= 1, + "A field can have only one rfl::Short or rfl::Positional, " + "wherever it sits among the field's other wrappers."); + + 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::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_read_reflector) { + return unwrap_option_type< + typename Reflector::ReflType, ProcessorsType>(); + } + else if constexpr (rfl::internal::has_reflection_type_v) { + return unwrap_option_type(); + } + 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; + +/// 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; + +/// Adds the option of the top-level field `_name` of type T. +template +void add_option(const std::string& _name, Options* _options) { + using U = unwrapped_option_t; + if constexpr (std::is_same_v) { + _options->long_options[_name] = Option{OptionKind::flag}; + } + else if constexpr (is_open_option_v || parsing::is_string_map_v + || is_option_struct_v) { + _options->long_options[_name] = Option{OptionKind::other}; + } + else { + _options->long_options[_name] = Option{OptionKind::value}; + } +} + +template +void add_option_for_field(Options* _options) { + using T = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + add_option(std::string(FieldType::name()), _options); + } +} + +/// Adds the options of the top-level fields of T. +template +void collect_options(Options* _options) { + using NT = option_fields_t; + [&](std::index_sequence<_is...>) { + (add_option_for_field, + ProcessorsType>(_options), + ...); + }(std::make_index_sequence()); +} + +/// Adds the short alias and the positional slot of the _i-th top-level +/// field, if it has them. Two fields with the same short name are kept as +/// an error (Options::duplicate_short_name). +template +void add_short_and_positional(Options* _options) { + using Info = field_info; + if constexpr (Info::is_short) { + const auto name = + std::string(get_short_name().string_view()); + if (!_options->short_options.emplace(name, std::string(Info::name())) + .second + && _options->duplicate_short_name.empty()) { + _options->duplicate_short_name = name; + } + } + if constexpr (Info::is_positional) { + _options->positionals.emplace_back(Info::name()); + } +} + +template +void collect_short_and_positional(Options* _options) { + using NT = option_fields_t; + [&](std::index_sequence<_is...>) { + (add_short_and_positional(_options), ...); + }(std::make_index_sequence()); +} + +/// Derives the options that T accepts from its fields: the option of every +/// top-level field, with whether it is a flag or takes a value, and the +/// rfl::Short aliases and rfl::Positional fields. +/// @tparam T The target struct type +/// @tparam ProcessorsType The processors applied to the struct +/// @return The options +template +Options make_options() { + Options options; + using U = unwrapped_option_t; + if constexpr (is_option_struct_v) { + collect_options(&options); + collect_short_and_positional(&options); + } + // As in argparse, -5 is a negative number unless a short option's name + // 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 6991abe5..76fce449 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -15,12 +15,14 @@ #include "../Result.hpp" #include "../internal/strings/utf8_conversions.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 @@ -39,21 +41,29 @@ 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. -/// Every element of `_args` is parsed; nothing is skipped as the program name. +/// `_options` says what each short option does with the token that follows +/// it when it is given without '='. One that takes a value consumes it, and +/// fails if there is none. A bool flag consumes it only if it is "true", +/// "false", "1" or "0". Short options missing from `_options` consume it +/// unless it looks like an option, as they do without `_options`. Long +/// options never consume it. /// 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.negative_numbers_are_options` is set, as it is +/// without `_options` and when the struct has a short option whose name +/// looks like a number (rfl::Short<"1", ...>), as in argparse. +/// Every element of `_args` is parsed; nothing is skipped as the program name. /// @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 /// --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, - 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 { @@ -64,6 +74,41 @@ inline rfl::Result parse_string_views( return true; }; + // The value of the short 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, + size_t* _i) -> rfl::Result { + const bool has_next = *_i + 1 < _args.size(); + switch (_option.kind) { + case OptionKind::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 flag takes a bool literal. Any other token stays where + // it is, so `-v input.txt` leaves "input.txt" positional. + if (has_next && is_bool_literal(_args[*_i + 1])) { + return std::string(_args[++*_i]); + } + return std::string(); + + case OptionKind::other: + // A variant, rfl::Generic or nested struct: `-m fast` takes the next + // token unless it looks like an option. + if (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]); @@ -97,11 +142,15 @@ inline rfl::Result parse_string_views( } // Short argument: -x value, -x=value, or -x (bool). - // 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 - && arg_raw[0] == '-')) { + if (arg_raw.size() >= 2 && arg_raw[0] == '-') { + // A negative number such as -42 or -.5 is a positional argument, + // unless, as in argparse, a short option's name looks like a number + // (-1). Without a table, it is the short option "42". + if (!looks_like_option(arg_raw) && !negative_numbers_are_options) { + result.positional.emplace_back(arg_raw); + continue; + } + const auto arg = arg_raw.substr(1); const auto eq = arg.find('='); @@ -114,13 +163,23 @@ 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); 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, &i); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + } + const auto r = add_short(std::move(key), std::move(val), arg_raw); if (!r) { return error(r.error().what()); } continue; } @@ -172,7 +231,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, - bool _negative_numbers_are_options) { + const Options& _options) { std::vector views; auto i = _first_index; for (auto&& arg : _args) { @@ -183,14 +242,14 @@ 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, _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 Options& _options) { std::vector narrow; auto i = _first_index; for (auto&& arg : _args) { @@ -206,7 +265,7 @@ 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, _options); } /// Validates argc/argv and returns the arguments after argv[0], the program @@ -223,75 +282,85 @@ rfl::Result> skip_program_name( return std::span(argv + 1, static_cast(argc - 1)); } -/// Parses every element of `_args`, as parse_argv(_args) 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, - bool _negative_numbers_are_options) { +rfl::Result parse_argv(R&& _args, const Options& _options) { if constexpr (StringRange) { - return parse_strings(std::forward(_args), 0, - _negative_numbers_are_options); + return parse_strings(std::forward(_args), 0, _options); } else { - return parse_wide_strings(std::forward(_args), 0, - _negative_numbers_are_options); + return parse_wide_strings(std::forward(_args), 0, _options); } } -/// Parses argc/argv, skipping argv[0], as parse_argv(argc, argv) does. -/// `_negative_numbers_are_options` is as for parse_string_views. -template -rfl::Result parse_args(int argc, const CharT* const argv[], - 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); - } else { - return parse_wide_strings(_args, 1, _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. -/// 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", ...>. +/// 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. /// @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_argv(std::forward(_args), internal::Options{}); } -/// Parses command-line arguments into categorized buckets, skipping argv[0] -/// (the program name). +/// 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. 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, 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. +/// 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_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 d9883f07..abcbc4ce 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 "options.hpp" #include "parse_argv.hpp" #include "resolve_args.hpp" @@ -16,21 +17,10 @@ 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{}); -} - -/// Turns categorized arguments into a struct. -template -rfl::Result read_parsed(ParsedArgs _parsed) { - using ProcessorsType = Processors; - return resolve_args(std::move(_parsed)) +/// Resolves the parsed arguments and reads them into T. +template +rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { + return resolve_args(std::move(_parsed), _options) .and_then([](auto _args) -> rfl::Result { const auto r = Reader(); const auto var = CliVarType{&_args, "", std::nullopt}; @@ -38,6 +28,19 @@ rfl::Result read_parsed(ParsedArgs _parsed) { }); } +/// 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; + const auto options = make_options(); + return check_short_names(options) + .and_then([&](bool) { return _parse(options); }) + .and_then([&](ParsedArgs _parsed) { + return read_parsed(std::move(_parsed), options); + }); +} + } // namespace internal /// Parses a sequence of command-line arguments into a struct using reflection. @@ -67,9 +70,9 @@ 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_argv(std::forward(_args), _options); + }); } /// Parses command-line arguments into a struct using reflection. @@ -82,9 +85,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_args(argc, argv, - internal::negative_numbers_are_options()) - .and_then(internal::read_parsed); + return internal::parse_and_read( + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); } template @@ -102,9 +106,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_args(argc, argv, - internal::negative_numbers_are_options()) - .and_then(internal::read_parsed); + 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 3cf639f1..1bd79d9e 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -1,17 +1,14 @@ #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 { @@ -27,196 +24,23 @@ struct ParsedArgs { 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."); - } - } - 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{}); +/// 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. We iterate in insertion order +/// (short_order) to preserve argv ordering. +inline void apply_option_kinds(const Options& _options, ParsedArgs* _parsed) { 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::flag && !value.empty() + && !is_bool_literal(value)) { reclaimed.push_back(value); value.clear(); } @@ -224,22 +48,52 @@ 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 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; +} + +/// The error for more positional arguments than positional fields. +inline rfl::Unexpected too_many_positionals(const size_t _expected, + const size_t _got) { + return rfl::error("Too many positional arguments: expected at most " + + std::to_string(_expected) + ", got " + + std::to_string(_got) + "."); +} +/// 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()); - msg += ", got "; - msg += std::to_string(_parsed.positional.size()); - msg += "."; - return rfl::error(std::move(msg)); + return internal::too_many_positionals(positional_names.size(), + _parsed.positional.size()); } for (size_t i = 0; i < _parsed.positional.size(); ++i) { const auto& long_name = positional_names[i]; @@ -253,8 +107,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 +123,30 @@ 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 short options took from the next token are returned to the +/// positional arguments. +/// @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_option_table.cpp b/tests/cli/test_option_table.cpp new file mode 100644 index 00000000..28d57dce --- /dev/null +++ b/tests/cli/test_option_table.cpp @@ -0,0 +1,157 @@ +#include + +#include +#include +#include +#include +#include +#include + +// rfl::cli::read parses with the options of the struct: it knows while +// parsing which short options are bool flags and which take a value, so +// positional arguments keep their command-line order. +namespace test_option_table { + +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 ShortFlags { + rfl::Short<"q", rfl::DefaultVal> quiet = false; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"n", bool> dry_run; + rfl::Positional> input; + rfl::Positional> output; +}; + +TEST(cli, test_short_flags_keep_argv_order) { + const auto result = read({"in.rep", "-n", "out.csv", "-q"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input().value(), "in.rep"); + EXPECT_EQ(result.value().output().value(), "out.csv"); + EXPECT_TRUE(result.value().dry_run()); + EXPECT_TRUE(result.value().quiet().value()); + + // Wrapped bools are flags, too. + const auto wrapped = read({"-v", "in.rep", "-q", "out.csv", "-n"}); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().verbose(), true); + EXPECT_EQ(wrapped.value().input().value(), "in.rep"); + EXPECT_EQ(wrapped.value().output().value(), "out.csv"); +} + +TEST(cli, test_short_flags_explicit_value_is_not_reclaimed) { + // A value after '=' belongs to the flag, also for a plain bool. + const auto plain = read({"-n=in.rep"}); + ASSERT_FALSE(plain); + EXPECT_NE(std::string(plain.error().what()) + .find("Could not cast 'in.rep' to boolean for key 'dry-run'."), + std::string::npos) + << plain.error().what(); + + const auto wrapped = read({"-q=in.rep", "-n"}); + ASSERT_FALSE(wrapped); + EXPECT_NE(std::string(wrapped.error().what()) + .find("Could not cast 'in.rep' to boolean for key 'quiet'."), + std::string::npos) + << wrapped.error().what(); +} + +TEST(cli, test_short_flags_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<"n", 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); +} + +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()); +} + +// Two fields with the same 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."); +} + +// The Short and Positional fields of a root rfl::NamedTuple, whose names the +// processors leave alone (output_dir is --output_dir, not --output-dir). +using RootTuple = + rfl::NamedTuple>, + rfl::Field<"output_dir", rfl::Short<"o", std::string>>>; + +TEST(cli, test_root_named_tuple_short_and_positional) { + const auto result = read({"-o", "out", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().get<"input_file">().value(), "in.txt"); + EXPECT_EQ(result.value().get<"output_dir">().value(), "out"); +} + +} // namespace test_option_table diff --git a/tests/cli/test_wrapper_order.cpp b/tests/cli/test_wrapper_order.cpp new file mode 100644 index 00000000..794da374 --- /dev/null +++ b/tests/cli/test_wrapper_order.cpp @@ -0,0 +1,191 @@ +#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", std::optional> other_output; + 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", std::optional>> level; + rfl::Rename<"outDir", rfl::Short<"d", std::optional>> out_dir; + rfl::Deprecated<"Use -j.", "Threads", rfl::Short<"t", std::optional>> + threads; + rfl::Short<"j", rfl::Deprecated<"", "Jobs", std::optional>> jobs; + rfl::Description<"Title", std::optional>> + title; +}; + +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_FALSE(s.other_output().has_value()); + EXPECT_FALSE(s.format.has_value()); + EXPECT_FALSE(s.other_format().has_value()); + EXPECT_FALSE(s.log().value().has_value()); + EXPECT_FALSE(s.level().value().has_value()); + EXPECT_FALSE(s.out_dir().value().has_value()); + EXPECT_FALSE(s.threads().value().has_value()); + EXPECT_FALSE(s.jobs().value().has_value()); + EXPECT_FALSE(s.title().has_value()); +} + +TEST(cli, test_short_through_wrappers_conflict_with_long) { + const auto result = read({"-d", "a", "--outDir=b"}); + EXPECT_FALSE(result); +} + +// Positional fields take bare arguments in declaration order, wherever +// rfl::Positional sits among their wrappers. +struct Positionals { + rfl::DefaultVal> first = std::string("1"); + rfl::Positional> second; + 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.first().value(), "a"); + EXPECT_EQ(p.second().value(), "b"); + EXPECT_EQ(p.third().value().value(), "c"); + EXPECT_EQ(p.fourth().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.first().value(), "a"); + EXPECT_FALSE(p.second().has_value()); + 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_FALSE(none.value().second().has_value()); +} + +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().first().value(), "a"); + EXPECT_EQ(result.value().sixth_().value().value(), "f"); +} + +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"); + } + if (std::string(flag) != "-q") { + args.push_back("--quiet=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_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"); +} + +// Two fields with the same short name fail every read, wherever rfl::Short +// sits among their wrappers. A field with two rfl::Short or rfl::Positional +// wrappers, such as rfl::Short<"o", rfl::Description<"...", +// rfl::Positional>>, does not compile. +struct WrappedAndDirectShort { + rfl::Description<"Name", rfl::Short<"o", std::string>> name; + rfl::Short<"o", int> count; +}; + +TEST(cli, test_wrapped_duplicate_short_name) { + const auto result = read({"--count=5", "--name=x"}); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Duplicate short name '-o' in struct definition."); +} + +} // namespace test_wrapper_order