diff --git a/README.md b/README.md index 42648928..33f883ef 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,14 @@ if (argc > 1 && std::string_view(argv[1]) == "--help") { } ``` +`rfl::ImplicitValue` lets an option be given without a value, which then stands for the text: + +```cpp +rfl::ImplicitValue, "auto"> color; +// ./app --color -> color = "auto" +// ./app --color=never -> color = "never" +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages diff --git a/docs/content/default_val.md b/docs/content/default_val.md index dc0b7dd6..d7d53ec1 100644 --- a/docs/content/default_val.md +++ b/docs/content/default_val.md @@ -52,7 +52,7 @@ const auto homer = rfl::json::read(R"(["Homer"])").va // homer.town == "" ``` -An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description`, `rfl::Deprecated` or `rfl::Rename`, in any order, works like a bare one: a field `rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4;` may be omitted and is then 4. +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description`, `rfl::Deprecated` or `rfl::Rename`, in any order, works like a bare one: a field `rfl::Description<"Worker threads", rfl::DefaultVal> jobs = 4;` may be omitted and is then 4. `rfl::ImplicitValue` is read as its inner type by every format but the command line, so an `rfl::DefaultVal` inside it counts as a bare one in all of the following. ## All fields need a valid default value @@ -90,9 +90,9 @@ The field is still required. If `favorite_foods` is missing in the input, you ge The same restriction applies to every struct that is read with the `rfl::DefaultIfMissing` processor, whether it contains an `rfl::DefaultVal` or not. -An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` gets its default only if the struct can be default-constructed. If all its `rfl::DefaultVal` fields are wrapped and the struct cannot be default-constructed, because a field's type has no default constructor or the default constructor throws, the struct is read without its default values, so those fields must be present in the input. With a bare `rfl::DefaultVal`, such a struct does not compile, or you get the error above. +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` (but not one inside only `rfl::ImplicitValue`, which is a bare one) gets its default only if the struct can be default-constructed. If all its `rfl::DefaultVal` fields are wrapped and the struct cannot be default-constructed, because a field's type has no default constructor or the default constructor throws, the struct is read without its default values, so those fields must be present in the input. With a bare `rfl::DefaultVal`, such a struct does not compile, or you get the error above. -An `rfl::NamedTuple` has no in-class initializers. A missing bare `rfl::DefaultVal` field in it is set to `T{}`. If `T` has no default constructor, or `T{}` throws (for instance a validator that rejects its zero value), the field must be present in the input. An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` must always be present in an `rfl::NamedTuple`. +An `rfl::NamedTuple` has no in-class initializers. A missing bare `rfl::DefaultVal` field in it, also inside `rfl::ImplicitValue`, is set to `T{}`. If `T` has no default constructor, or `T{}` throws (for instance a validator that rejects its zero value), the field must be present in the input. An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` or `rfl::Deprecated` must always be present in an `rfl::NamedTuple`. ## When to use diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 3b1df7b4..e6db6c44 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -92,7 +92,8 @@ as `rfl::Short`, `rfl::Description` or `rfl::DefaultVal`. The next token is the value unless it looks like an option (`-` followed by anything except a digit or `.`), so `--offset -5` works. 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`. +value or one that starts with `-`: `--sql=`, `--pattern=-x`. 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 @@ -105,6 +106,35 @@ Without the processor, `--sql SELECT` sets `sql` to an empty string and passes `SELECT` as a positional argument. The public `rfl::cli::parse_argv` does not know the struct, so it always reads it that way. +## 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 / -htag -> help = "" / "tag" / "tag" +// ./app --verbosity -> verbosity = 2 +``` + +A bare option stands for the text, which is parsed like any other value; +the next token is never taken. The text may be left out (it is then empty) +only for a `bool`, a `std::string` or a list, where an empty value means +something; any other type needs one, such as `rfl::ImplicitValue`. 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 @@ -128,9 +158,9 @@ rfl::cli::read(argc, argv); A long option can then be shortened to a prefix that matches only one option: with fields `report` and `format`, `--rep=a` and `--form` stand for -`--report=a` and `--format`. This works for flags, -positional fields given by name and nested fields, where only the last part -of the dotted name is shortened: `--database.h` stands for +`--report=a` and `--format`. This works for flags, `rfl::ImplicitValue` +options, positional fields given by name and nested fields, where only the +last part of the dotted name is shortened: `--database.h` stands for `--database.host`, but `--data` and `--database.` stand for nothing. - An exact name always wins: `--format` is `--format` even when @@ -242,9 +272,11 @@ struct Config { ``` Flags are set up to the first option that takes a value. That option takes -the rest of the token, or the next token if nothing is left. The last -option in a token treats the next token as it would alone (`-qv false` sets -`verbose` to `false`). +the rest of the token, or the next token if nothing is left. An +`rfl::ImplicitValue` option takes the rest of the token if there is any and +its implicit value otherwise, never the next token. The last option in a +token treats the next token as it would alone (`-qv false` sets `verbose` +to `false`). - `-f=csv` and `-qf=csv` give `csv`: the `=` is not part of the value. - A flag inside a group takes no value: `-vq=false` is an error. @@ -280,6 +312,9 @@ struct Config { - Repeating is the same as joining with a comma, so the size of a `std::array` and validators such as `rfl::Size` see all items. An empty occurrence (`--report=`) adds none. +- A bare occurrence of an `rfl::ImplicitValue` list adds its implicit value: + with `rfl::ImplicitValue>, "all">`, + `--help-reports --help-reports=cpu` gives `{"all", "cpu"}`. - Nested lists (`--database.replicas=a --database.replicas=b`) and map entries whose values are lists (`--groups.x=a --groups.x=b`) work the same way. @@ -316,8 +351,8 @@ struct Config { ## Combining wrappers -`Short` and `Positional` can be nested with `DefaultVal`, `std::optional`, -`Description`, `Rename` and `Deprecated` in any order: +`Short`, `Positional` and `ImplicitValue` can be nested with `DefaultVal`, +`std::optional`, `Description`, `Rename` and `Deprecated` in any order: `rfl::Description<"...", rfl::Short<"o", T>>` is `-o`, and `rfl::DefaultVal>` is positional. Put `rfl::Rename` outermost, as in `rfl::Rename<"out", rfl::Short<"o", T>>`; inside other @@ -327,8 +362,8 @@ Bare arguments go to the `Positional` fields in declaration order. Two fields with the same `Short` name make every read fail with `Duplicate short name '-o' in struct definition.` A field with more than one `Short` or `Positional`, such as `rfl::Positional>` or -`rfl::Short<"o", rfl::Description<"...", rfl::Positional>>`, is a -compile-time error: +`rfl::Short<"o", rfl::Description<"...", rfl::Positional>>`, and a +`Positional` field with an `ImplicitValue`, are compile-time errors: ```cpp struct Config { @@ -428,11 +463,12 @@ Arguments: Each argument is shown as the option table that `read` parses with (see [Architecture](#architecture)) reads it: a `bool`, also inside a nested -struct, is a flag whose value can be left out (`--verbose[=]`), a list -takes comma-separated items and can be repeated (`--tags=`, with -`Can be repeated.` in its row), a list as the last `rfl::Positional` takes -the remaining arguments (`...`), and every other option takes a value -(`--port=`). +struct, is a flag whose value can be left out (`--verbose[=]`), so is +an `rfl::ImplicitValue` option (`--color[=]`, with +`Without a value: always.` in its row), a list takes comma-separated items +and can be repeated (`--tags=`, with `Can be repeated.` in its +row), a list as the last `rfl::Positional` takes the remaining arguments +(`...`), and every other option takes a value (`--port=`). `rfl::Positional` and `rfl::Short` are found through the other wrappers, as the parser does (see [Combining wrappers](#combining-wrappers)), so @@ -468,6 +504,7 @@ int main(int argc, char* argv[]) { | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | | `rfl::Positional` | bare token | Matched in declaration order; a list last takes the rest | | `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) | +| `rfl::ImplicitValue` | `--key` or `--key=value` | Bare means `x` | ## Architecture @@ -502,3 +539,4 @@ Parsing proceeds in three stages: - `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..c8a82c78 --- /dev/null +++ b/include/rfl/ImplicitValue.hpp @@ -0,0 +1,236 @@ +#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; + + /// Every format but the command line reads and writes the underlying + /// value, as for rfl::Description. + using ReflectionType = Type; + + /// 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_; } + + /// Returns the underlying value for reflection (used by parsers). + const Type& reflection() const { return value_; } + + /// The underlying value. + Type value_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 69806ef2..dcaee846 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -15,6 +15,7 @@ #include "../Deprecated.hpp" #include "../Description.hpp" #include "../Generic.hpp" +#include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" @@ -44,6 +45,10 @@ enum class OptionKind { /// A field that takes a value: `--key=value`, `-k value`, `-k=value`, and /// with rfl::cli::SeparateOptionValues `--key 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 @@ -61,6 +66,11 @@ struct Option { /// occurrence of a list option adds to it, however the option is spelled, /// so it may be repeated. Any other option may be given only once. bool is_list = false; + + /// For OptionKind::implicit_value: the value that the option stands for + /// when it is given without one. It views the rfl::ImplicitValue's + /// template argument, which lives as long as the program. + std::string_view implicit_value = {}; }; /// The options that a target struct accepts, built from its fields by @@ -229,16 +239,19 @@ inline bool is_bool_literal(std::string_view _token) noexcept { || _token == "0"; } -/// What rfl::Short and rfl::Positional say about a field of type T. They are -/// found through rfl::DefaultVal, std::optional, rfl::Description, -/// rfl::Deprecated and rfl::Rename, in any order. `count` is the number of -/// rfl::Short and rfl::Positional wrappers; a field may have at most one. +/// 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. `count` is the number of rfl::Short and rfl::Positional wrappers; a +/// field may have at most one. template struct cli_annotations { static constexpr bool is_short = false; static constexpr bool is_positional = false; + static constexpr size_t num_implicit_value = 0; static constexpr rfl::internal::StringLiteral<1> short_name = ""; static constexpr int count = 0; + static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; }; template @@ -276,6 +289,13 @@ struct cli_annotations> : cli_annotations_t { static constexpr int count = cli_annotations_t::count + 1; }; +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; +}; + /// 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 @@ -287,10 +307,17 @@ struct field_info { static constexpr bool is_positional = Annotations::is_positional; static constexpr bool is_short = Annotations::is_short; + static constexpr bool has_implicit_value = + Annotations::num_implicit_value > 0; static_assert(Annotations::count <= 1, "A field can have only one rfl::Short or rfl::Positional, " "wherever it sits among the field's other wrappers."); + static_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(); } }; @@ -309,7 +336,7 @@ constexpr auto get_short_name() { /// Strips everything that does not change how a field is written on the /// command line: optionals, pointers, rfl::Short, rfl::Positional, -/// rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a +/// rfl::ImplicitValue, rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a /// ReflectionType (rfl::Validator, rfl::Description, rfl::Literal, ...), /// reflectors and custom parsers. template @@ -335,6 +362,7 @@ auto unwrap_option_type() { } 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) { @@ -411,12 +439,41 @@ constexpr bool is_option_list_v = || parsing::is_c_array_v || parsing::is_tuple_v || parsing::is_rfl_tuple_v || parsing::is_pair_v; +/// Whether an empty implicit value means something for T: a bool flag is +/// true, a string is empty, a list has no items. +template +constexpr bool empty_implicit_value_is_valid_v = + std::is_same_v || std::is_same_v + || is_option_list_v; + +/// 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(empty_implicit_value_is_valid_v + || Annotations::implicit_value.length > 0, + "rfl::ImplicitValue needs an implicit value unless it wraps a " + "bool, a std::string or a list, such as " + "rfl::ImplicitValue."); + return Option{OptionKind::implicit_value, is_option_list_v, + Annotations::implicit_value.string_view()}; +} + /// The option for a field, or a key of a map or of rfl::ExtraFields, with /// values of type T. template Option option_for() { using U = unwrapped_option_t; - if constexpr (std::is_same_v) { + 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 @@ -441,9 +498,10 @@ template void add_open_prefix(const std::string& _prefix, Options* _options) { using U = unwrapped_option_t; _options->open_prefixes[_prefix] = option_for(); - if constexpr (parsing::is_string_map_v - || (is_option_struct_v - && !VisitedType::template contains)) { + if constexpr (cli_annotations_t::num_implicit_value == 0 + && (parsing::is_string_map_v + || (is_option_struct_v + && !VisitedType::template contains))) { auto nested = rfl::Box::make(); collect_value_options(nested.get()); _options->open_prefix_options.insert_or_assign(_prefix, std::move(nested)); @@ -470,7 +528,11 @@ void collect_value_options(Options* _options) { template void add_option(const std::string& _path, Options* _options) { using U = unwrapped_option_t; - if constexpr (std::is_same_v) { + 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) { @@ -572,8 +634,8 @@ void collect_top_level_options(Options* _options) { } /// Derives the options that T accepts from its fields: the long options, -/// with whether each is a flag or takes a value, and the rfl::Short aliases -/// and rfl::Positional fields of the top-level struct. +/// with whether each 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 /// @tparam _all_paths Whether to list every long option through nested diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index d6b8f8fb..b32e673d 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -48,10 +48,12 @@ namespace internal { /// it, and fails if there is none; so does a long one with /// `_options.separate_values` (rfl::cli::SeparateOptionValues). A long /// boolean flag never consumes it; a short one consumes it only if it is -/// "true", "false", "1" or "0". Other long options never consume it. Short options missing from `_options` -/// consume it unless it looks like an option, as they do without -/// `_options`. With `_options.reject_unknown`, a long option that matches -/// no field is an error. +/// "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`. With +/// `_options.reject_unknown`, a long option that matches no field is an +/// error. /// A token that looks like a negative number (-5, -.5) is a positional /// argument unless `_options.negative_numbers_are_options` is set, as it is /// without `_options` and when the struct has a short option whose name @@ -59,8 +61,10 @@ namespace internal { /// Short options known to `_options` can be grouped as in getopt: in `-qvf` /// every flag is set until the first option that takes a value, which /// takes the rest of the token (`-qfcsv`) or, if nothing is left, the next -/// token (`-qf csv`). Without `_options` from make_options, short options -/// are not grouped: `-abc` is the short option `abc`. +/// token (`-qf csv`). An rfl::ImplicitValue option takes the rest of the +/// token if there is one, and never the next token. Without `_options` from +/// make_options, short options are not grouped: `-abc` is the short option +/// `abc`. /// If `_options.allow_abbreviations` is set (rfl::cli::AllowAbbreviations), /// a long option that matches no field stands for the one long option it is /// a prefix of (`--rep` for `--report`), and a prefix of several is an @@ -154,6 +158,11 @@ inline rfl::Result parse_string_views( } return std::string(); + case OptionKind::implicit_value: + // Never takes the next token: `-h input.txt` leaves "input.txt" + // positional. + return std::string(_option.implicit_value); + case OptionKind::other: // A variant, rfl::Generic or nested struct: `-m fast` takes the next // token unless it looks like an option. @@ -217,6 +226,12 @@ inline rfl::Result parse_string_views( if (!v) { return error(v.error().what()); } val = std::move(*v); } + else if (eq == std::string_view::npos + && option.kind == OptionKind::implicit_value) { + // --help: no value. An rfl::ImplicitValue option stands for its + // implicit value. + val = std::string(option.implicit_value); + } const auto r = add_long(std::move(key), std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } continue; @@ -283,8 +298,8 @@ inline rfl::Result parse_string_views( continue; } else if (!rest.empty()) { - // -fvalue, -qfvalue: the rest of the token is the value. -qf=value - // is the same as -qfvalue, as -f=value is. + // -fvalue, -qfvalue, -hvalue: the rest of the token is the value. + // -qf=value is the same as -qfvalue, as -f=value is. val = std::string(rest.starts_with('=') ? rest.substr(1) : rest); } else { diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 47422dcb..81d24ede 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -200,7 +200,8 @@ inline rfl::Result> expand_abbreviations( /// With rfl::cli::AllowAbbreviations, long options that match no field are /// expanded here (`--rep=a` for `--report=a`), but parse_argv, which does /// not know the struct, has already read `--rep value` as `--rep` and a -/// positional argument. +/// positional argument. rfl::ImplicitValue needs the options, too: without +/// them, `--help` gets an empty value and `-h x` gives `x` to `-h`. /// @tparam T The target struct type /// @tparam ProcessorsType The processors applied to the struct /// @param _parsed The parsed command-line arguments diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 383b2092..e8e1c53e 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -53,8 +53,12 @@ struct UsageArg { std::string short_name; bool positional = false; /// What the option does with a value, from the parser's option table: - /// flags (`--verbose`) can be given without one. + /// flags (`--verbose`) and rfl::ImplicitValue (`--help`) can be given + /// without one. OptionKind kind = OptionKind::value; + /// For OptionKind::implicit_value: what the option stands for without a + /// value. + std::string implicit_value; /// Whether the field is a list, which can be repeated. bool is_list = false; /// Whether the field is the last positional one and a list, so that it @@ -97,8 +101,8 @@ void add_usage_field_meta(const bool _default_vals_are_optional, /// Collects whether each top-level field is required from the same /// compile-time traits that the parser uses, so the help matches what the -/// parser accepts. Positional, Short, flags and lists come from the parser's -/// option table (make_options). +/// parser accepts. Positional, Short, flags, implicit values and lists come +/// from the parser's option table (make_options). template std::map collect_usage_field_meta( const bool _default_vals_are_optional, std::index_sequence<_is...>) { @@ -469,6 +473,7 @@ class UsageCollector { // key ("labels.") is found through its open prefix. const auto option = options_->find_long(_arg.name); _arg.kind = option.kind; + _arg.implicit_value = std::string(option.implicit_value); _arg.is_list = option.is_list; if (_default) { _arg.default_value = usage_default_to_string(*_default); @@ -509,7 +514,8 @@ inline std::string usage_value_to_string(const UsageArg& _arg) { return ""; } -/// "", "...", "-p|--port=", "--verbose[=]" +/// "", "...", "-p|--port=", "--verbose[=]", +/// "--help[=]" inline std::string usage_arg_to_string(const UsageArg& _arg, const std::string& _short_sep) { if (_arg.positional) { @@ -523,7 +529,8 @@ inline std::string usage_arg_to_string(const UsageArg& _arg, const auto value = usage_value_to_string(_arg); switch (_arg.kind) { case OptionKind::flag: - // `--verbose`: the value can be left out. + case OptionKind::implicit_value: + // `--verbose`, `--help`: the value can be left out. str += "[=" + value + "]"; break; default: @@ -555,6 +562,10 @@ inline std::string usage_help_text(const UsageArg& _arg) { } sentences.insert(sentences.end(), _arg.constraints.begin(), _arg.constraints.end()); + if (_arg.kind == OptionKind::implicit_value && !_arg.positional + && !_arg.implicit_value.empty()) { + sentences.push_back("Without a value: " + _arg.implicit_value); + } if (_arg.default_value) { sentences.push_back("Default: " + *_arg.default_value); } 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 dc3cdedc..518fc318 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/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 24e4f225..d284b524 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -18,6 +18,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" @@ -552,6 +553,12 @@ struct Parser { return ParserPositional::to_schema(_definitions); + } else if constexpr (rfl::internal::is_implicit_value::value) { + // Read and written through its ReflectionType, but described as the + // type itself rather than as a named reference, like rfl::Short. + return Parser::to_schema( + _definitions); + } else if constexpr (is_reference_wrapper_v) { return ParserReferenceWrapper::to_schema(_definitions); diff --git a/tests/cli/test_abbreviations.cpp b/tests/cli/test_abbreviations.cpp index cc47f199..43316cac 100644 --- a/tests/cli/test_abbreviations.cpp +++ b/tests/cli/test_abbreviations.cpp @@ -39,6 +39,7 @@ struct Export { std::optional format_version; std::optional force_export; std::optional> report; + rfl::ImplicitValue, "all"> help_reports; rfl::Short<"o", std::optional> output; rfl::Positional> input_file; std::optional database; @@ -77,6 +78,17 @@ TEST(cli, test_abbreviation_flag) { EXPECT_EQ(with_equals.value().force_export, false); } +TEST(cli, test_abbreviation_implicit_value) { + const auto bare = read({"--help", "in.txt"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().help_reports().value(), "all"); + EXPECT_EQ(bare.value().input_file(), "in.txt"); + + const auto with_value = read({"--help-r=memory"}); + ASSERT_TRUE(with_value) << with_value.error().what(); + EXPECT_EQ(with_value.value().help_reports().value(), "memory"); +} + TEST(cli, test_abbreviation_exact_match_wins) { const auto result = read({"--format=csv", "--format-v=2"}); ASSERT_TRUE(result) << result.error().what(); diff --git a/tests/cli/test_implicit_value.cpp b/tests/cli/test_implicit_value.cpp new file mode 100644 index 00000000..58dc06f3 --- /dev/null +++ b/tests/cli/test_implicit_value.cpp @@ -0,0 +1,157 @@ +#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_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({}); + EXPECT_FALSE(absent); + + 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"); + + // A nested option has its implicit value without rfl::NoExtraFields, too. + const auto nested = read({"--database.ssl-mode", "r.rep"}); + ASSERT_TRUE(nested) << nested.error().what(); + EXPECT_EQ(nested.value().database->ssl_mode().value(), "require"); + EXPECT_EQ(nested.value().input().value(), "r.rep"); + + 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"); +} + +} // namespace test_implicit_value diff --git a/tests/cli/test_repeated_options.cpp b/tests/cli/test_repeated_options.cpp index 9fb42926..1da2e045 100644 --- a/tests/cli/test_repeated_options.cpp +++ b/tests/cli/test_repeated_options.cpp @@ -46,6 +46,7 @@ struct Opts { std::optional database; std::optional> labels; std::optional> groups; + rfl::ImplicitValue, "all"> help_reports; rfl::Positional> input; }; @@ -152,6 +153,28 @@ TEST(cli, test_repeated_nested_scalar_and_map_key_error) { (std::map{{"env", "a"}, {"os", "b"}})); } +TEST(cli, test_repeated_implicit_value_list) { + // A bare occurrence adds the implicit value, split like any other value. + const auto bare = read({"--help-reports"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().help_reports(), (Strings{"all"})); + + const auto mixed = read( + {"--help-reports=cpu", "--help-reports", "--help-rep=gpu,mem"}); + ASSERT_TRUE(mixed) << mixed.error().what(); + EXPECT_EQ(mixed.value().help_reports(), (Strings{"cpu", "all", "gpu", "mem"})); + + // It still never takes the next token. + const auto next = read({"--help-reports", "in.txt"}); + ASSERT_TRUE(next) << next.error().what(); + EXPECT_EQ(next.value().help_reports(), (Strings{"all"})); + EXPECT_EQ(next.value().input(), "in.txt"); + + const auto absent = read({}); + ASSERT_TRUE(absent) << absent.error().what(); + EXPECT_FALSE(absent.value().help_reports().has_value()); +} + struct Wrapped { rfl::Description<"Files to include", rfl::DefaultVal>> diff --git a/tests/cli/test_short_clusters.cpp b/tests/cli/test_short_clusters.cpp index acbfc394..86109bbd 100644 --- a/tests/cli/test_short_clusters.cpp +++ b/tests/cli/test_short_clusters.cpp @@ -28,6 +28,8 @@ struct Opts { rfl::Short<"q", rfl::DefaultVal> quiet = false; rfl::Short<"f", std::optional> format; rfl::Short<"p", std::optional> port; + rfl::Short<"h", rfl::ImplicitValue>> help; + rfl::Short<"l", rfl::ImplicitValue, "3">> level; rfl::Positional> input; rfl::Positional> output; }; @@ -175,6 +177,23 @@ TEST(cli, test_short_cluster_conflicts_with_long) { EXPECT_FALSE(read({"-afcsv", "--format=json"})); } +TEST(cli, test_short_cluster_implicit_value_attached) { + // getopt's optional argument: the rest of the token, if any. + const auto result = read({"-a", "-hfoo"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().help().value(), "foo"); + + const auto grouped = read({"-aqhfoo", "-l7"}); + ASSERT_TRUE(grouped) << grouped.error().what(); + EXPECT_TRUE(grouped.value().quiet().value()); + EXPECT_EQ(grouped.value().help().value(), "foo"); + EXPECT_EQ(grouped.value().level().value(), 7); + + const auto equals = read({"-aqh=foo"}); + ASSERT_TRUE(equals) << equals.error().what(); + EXPECT_EQ(equals.value().help().value(), "foo"); +} + TEST(cli, test_short_negative_number_value) { for (const auto& args : std::vector>{ {"-a", "-p", "-42"}, {"-a", "-p-42"}, {"-ap", "-42"}, diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp index 4cacd774..8a006850 100644 --- a/tests/cli/test_usage_options.cpp +++ b/tests/cli/test_usage_options.cpp @@ -6,9 +6,10 @@ #include #include -// rfl::cli::usage for the parser's option features: wrappers in any order, -// repeated list options, a list as the last positional field and positional -// order. Each test also reads the arguments as the help spells them. +// rfl::cli::usage for the parser's option features: rfl::ImplicitValue, +// wrappers in any order, repeated list options, a list as the last +// positional field and positional order. Each test also reads the arguments +// as the help spells them. namespace test_usage_options { template @@ -20,6 +21,46 @@ rfl::Result read(std::vector _args) { using Strings = std::vector; +enum class Color { never, always, automatic }; + +struct WithImplicitValues { + rfl::Description<"When to color the output", + rfl::ImplicitValue, "always">> + color; + rfl::Short<"j", rfl::ImplicitValue, "4">> jobs = 1; + rfl::ImplicitValue> tag; + rfl::Short<"q", bool> quiet; +}; + +TEST(cli, test_usage_implicit_value) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app [--color[=]] " + "[-j|--jobs[=]] [--tag[=]] -q|--quiet[=]\n" + "\n" + "Arguments:\n" + " --color[=] When to color the output. " + "Without a value: always.\n" + " -j, --jobs[=] Without a value: 4. " + "Default: 1.\n" + " --tag[=]\n" + " -q, --quiet[=] Required.\n"); + + // Bare, the options stand for their implicit values. + const auto bare = read({"--color", "-j", "--tag", "-q"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().color.value().value(), Color::always); + EXPECT_EQ(bare.value().jobs.value().value().get(), 4); + EXPECT_EQ(bare.value().tag.value(), std::string()); + EXPECT_TRUE(bare.value().quiet.value()); + + // With a value after '=', and left out. + const auto given = read({"--color=never", "-q"}); + ASSERT_TRUE(given) << given.error().what(); + EXPECT_EQ(given.value().color.value().value(), Color::never); + EXPECT_EQ(given.value().jobs.value().value().get(), 1); + EXPECT_FALSE(given.value().tag.value()); +} + struct WrapperOrder { rfl::Description<"Where to write", rfl::Short<"o", std::string>> output; rfl::DefaultVal> input = "in.txt"; diff --git a/tests/json/test_implicit_value.cpp b/tests/json/test_implicit_value.cpp new file mode 100644 index 00000000..91142992 --- /dev/null +++ b/tests/json/test_implicit_value.cpp @@ -0,0 +1,125 @@ +#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"]}}})"); +} + +} // namespace test_implicit_value