diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 93a1084b..9532d551 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -79,6 +79,81 @@ 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, 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 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 +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 +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: @@ -129,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 { @@ -170,18 +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). 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 + 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`. @@ -192,8 +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/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.hpp b/include/rfl.hpp index 432fff2f..dc5ace36 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 00000000..b42b0e91 --- /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/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..aa822156 --- /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 6991abe5..b26f5411 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 @@ -35,25 +37,35 @@ 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. +/// `_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 _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 +/// --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, - 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 +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]); @@ -79,17 +134,31 @@ 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 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 { + 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); + } + } if (!result.named.emplace(std::move(key), std::move(val)).second) { return error("Duplicate argument: " + std::string(arg_raw)); } @@ -100,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('='); @@ -114,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; } @@ -172,7 +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, - bool _negative_numbers_are_options) { + const Options& _options) { std::vector views; auto i = _first_index; for (auto&& arg : _args) { @@ -183,14 +264,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 +287,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 +304,86 @@ 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 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), 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..8d5e1e43 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,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() { +/// 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; - 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)) + 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}; @@ -67,9 +64,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 +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_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 +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_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..36cd3f30 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/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 78920690..3ac5314c 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 00000000..efcb9b51 --- /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 7763fb46..d7dc65f9 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 00000000..2893283d --- /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 60677032..ea9b7d0a 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 7f77a7c7..851cc699 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 30fe10f6..49759492 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/cli/test_implicit_value.cpp b/tests/cli/test_implicit_value.cpp new file mode 100644 index 00000000..c628a5aa --- /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 new file mode 100644 index 00000000..4ecd3120 --- /dev/null +++ b/tests/cli/test_long_option_values.cpp @@ -0,0 +1,575 @@ +#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")))); +} + +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", + "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::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::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()); +} + +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 diff --git a/tests/cli/test_wrapper_order.cpp b/tests/cli/test_wrapper_order.cpp new file mode 100644 index 00000000..5cdf0016 --- /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 diff --git a/tests/json/test_implicit_value.cpp b/tests/json/test_implicit_value.cpp new file mode 100644 index 00000000..cef1857e --- /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