From 85c2e815001798f7825735692d354243cc8a65d9 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 13:14:39 +0100 Subject: [PATCH 1/4] Add read-only field aliases (rfl::Alias) --- docs/content/_index.md | 1 + docs/content/alias.md | 79 +++++ docs/content/supported_formats/cli.md | 3 +- include/rfl.hpp | 1 + include/rfl/Alias.hpp | 253 +++++++++++++++ include/rfl/CamelCaseToSnakeCase.hpp | 4 +- include/rfl/SnakeCaseToCamelCase.hpp | 4 +- include/rfl/SnakeCaseToKebabCase.hpp | 4 +- include/rfl/SnakeCaseToPascalCase.hpp | 4 +- include/rfl/ToAllCaps.hpp | 4 +- include/rfl/cli/options.hpp | 29 +- include/rfl/cli/resolve_args.hpp | 12 +- include/rfl/env/Reader.hpp | 48 ++- .../rfl/internal/cpp20/get_field_names.hpp | 6 +- .../internal/cpp20/get_member_ptr_name.hpp | 6 +- .../rfl/internal/cpp26/get_field_names.hpp | 6 +- include/rfl/internal/field_aliases.hpp | 188 +++++++++++ include/rfl/internal/is_alias.hpp | 27 ++ include/rfl/internal/is_attribute.hpp | 4 +- include/rfl/internal/is_default_val_v.hpp | 32 +- include/rfl/parsing/NamedTupleParser.hpp | 11 +- include/rfl/parsing/ParserAlias.hpp | 71 ++++ include/rfl/parsing/Parser_default.hpp | 10 + include/rfl/parsing/ViewReader.hpp | 77 +++-- include/rfl/parsing/ViewReaderWithDefault.hpp | 65 +++- include/rfl/parsing/is_empty.hpp | 4 +- include/rfl/parsing/is_required.hpp | 3 + tests/cli/test_alias.cpp | 108 +++++++ tests/generic/CMakeLists.txt | 33 ++ .../alias_collides_with_alias.cpp | 15 + .../alias_collides_with_primary.cpp | 15 + tests/generic/test_alias.cpp | 43 +++ tests/json/test_alias.cpp | 306 ++++++++++++++++++ tests/yaml/test_alias.cpp | 43 +++ 34 files changed, 1457 insertions(+), 62 deletions(-) create mode 100644 docs/content/alias.md create mode 100644 include/rfl/Alias.hpp create mode 100644 include/rfl/internal/field_aliases.hpp create mode 100644 include/rfl/internal/is_alias.hpp create mode 100644 include/rfl/parsing/ParserAlias.hpp create mode 100644 tests/cli/test_alias.cpp create mode 100644 tests/generic/compile_fail/alias_collides_with_alias.cpp create mode 100644 tests/generic/compile_fail/alias_collides_with_primary.cpp create mode 100644 tests/generic/test_alias.cpp create mode 100644 tests/json/test_alias.cpp create mode 100644 tests/yaml/test_alias.cpp diff --git a/docs/content/_index.md b/docs/content/_index.md index 056abfd96..89bff4427 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -16,6 +16,7 @@ {{< card link="rfl_ref" title="rfl::Box and rfl::Ref" icon="book-open" subtitle="For defining recursive structures.">}} {{< card link="timestamps" title="rfl::Timestamp and std::chrono::duration" icon="book-open" subtitle="For serializing and deserializing timestamps and durations.">}} {{< card link="rfl_skip" title="rfl::Skip" icon="book-open" subtitle="For skipping fields during serialization and/or deserialization.">}} + {{< card link="alias" title="rfl::Alias" icon="book-open" subtitle="For accepting read-only field aliases during deserialization.">}} {{< card link="commented" title="rfl::Commented" icon="book-open" subtitle="For adding comments to your serialized format.">}} {{< card link="result" title="rfl::Result" icon="book-open" subtitle="For error handling without exceptions.">}} {{< card link="standard_containers" title="Standard containers" icon="book-open" subtitle="How reflect-cpp treats containers in the standard library.">}} diff --git a/docs/content/alias.md b/docs/content/alias.md new file mode 100644 index 000000000..035a22947 --- /dev/null +++ b/docs/content/alias.md @@ -0,0 +1,79 @@ +# Read-only field aliases (`rfl::Alias`) + +The `rfl::Alias<"old-name", T>` wrapper declares a read-only alias for a struct field. During deserialization, `reflect-cpp` accepts **either** the canonical primary wire name **or** any declared alias. During serialization and JSON Schema generation, `reflect-cpp` **always** emits the canonical primary wire name. + +This is especially useful when evolving an API or configuration format (for example, migrating legacy `kebab-case` or `camelCase` RPC keys to `snake_case`, or supporting deprecated CLI flag names) without maintaining manual key-translation tables. + +## Basic usage + +```cpp +#include +#include + +struct Settings { + rfl::Alias<"download-dir", std::string> download_dir; + rfl::Alias<"speedLimitDown", int> speed_limit_down; +}; + +// Accepted on read (alias or canonical name): +const auto s = rfl::json::read( + R"({"download-dir":"/downloads","speedLimitDown":250})").value(); + +// Always serialized using the canonical primary names: +const auto out = rfl::json::write(s); +// {"download_dir":"/downloads","speed_limit_down":250} +``` + +## Multiple aliases + +Nest `rfl::Alias` wrappers to accept multiple legacy names for the same field: + +```cpp +struct Settings { + rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>> + download_dir; +}; +``` + +Reading `{"download_dir": "/dl"}`, `{"download-dir": "/dl"}`, or `{"downloadDir": "/dl"}` all populate `download_dir`, and writing always emits `{"download_dir":"/dl"}`. + +## Semantics + +- **Primary wire name:** Unchanged. It comes from the C++ field name (transformed by naming processors such as `rfl::SnakeCaseToCamelCase` or `rfl::SnakeCaseToKebabCase`, or overridden by `rfl::Rename<"canonical", ...>`). +- **Serialization (write):** Always writes the canonical primary wire name. +- **JSON Schema (`to_schema`):** Emits only the canonical primary property name (preserving inner `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, and `rfl::Validator` metadata). +- **`rfl::NoExtraFields`:** Aliases are recognized as valid field names and are not rejected as unknown extra fields. +- **Conflicting / duplicate input:** If an input object specifies both the primary name and an alias (or two different aliases for the same field), deserialization fails with an error instead of silently overwriting. +- **Compile-time collision check:** If an alias on one field equals the primary wire name or an alias of a different field, compilation fails with a `static_assert`. + +## Composing with other wrappers and processors + +`rfl::Alias` is transparent and composes cleanly with `rfl::Rename`, `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, `rfl::DefaultIfMissing`, `std::optional`, `rfl::Validator`, `rfl::Short`, `rfl::Positional`, and case-transforming processors: + +```cpp +struct Config { + rfl::Rename<"download_dir", rfl::Alias<"download-dir", std::string>> dir; + rfl::Alias<"old-port", rfl::DefaultVal> port = 8080; + rfl::Description<"Timeout in seconds", rfl::Alias<"timeoutSec", std::optional>> + timeout_sec; +}; +``` + +## CLI support + +`rfl::cli::read` also recognizes `rfl::Alias` names as long options (including under `rfl::NoExtraFields`) and detects conflicts between aliases, canonical names, `rfl::Short`, and `rfl::Positional`: + +```cpp +struct CliConfig { + rfl::Alias<"download_dir", rfl::Alias<"downloadDir", std::string>> + download_dir; + rfl::Short<"v", rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; +}; + +// Accepts --download-dir=/dl, --download_dir=/dl, or --downloadDir=/dl +// Accepts --verbose, -v, or --debug +``` + +## Wrapper ergonomics + +`rfl::Alias` provides `.value()`, `.get()`, `operator*`, `operator->`, `operator()`, implicit construction from convertible values, implicit conversion to `T&` / `const T&`, `==`, `<=>`, and `std::hash` specialization. Its default constructor is constrained on `std::is_default_constructible_v`. diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 00b4002cc..cde2caedf 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -171,7 +171,7 @@ option in a token treats the next token as it would alone (`-qv false` sets ## Combining wrappers `Short` and `Positional` can be nested with `DefaultVal`, `std::optional`, -`Description`, `Rename` and `Deprecated` in any order: +`Description`, `Rename`, `Alias` 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 @@ -209,6 +209,7 @@ struct Config { | Nested struct | `--parent.child=val` | Dot-separated path | | `rfl::Flatten` | fields inlined | No prefix needed | | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | +| `rfl::Alias<"old", T>` | `--old=val` | Read-only long alias (also works with `NoExtraFields`) | | `rfl::Positional` | bare token | Matched in declaration order | | `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) | diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..2162e0b65 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -9,6 +9,7 @@ #include "rfl/AddStructName.hpp" #include "rfl/AddTagsToVariants.hpp" +#include "rfl/Alias.hpp" #include "rfl/AllOf.hpp" #include "rfl/AllowRawPtrs.hpp" #include "rfl/AnyOf.hpp" diff --git a/include/rfl/Alias.hpp b/include/rfl/Alias.hpp new file mode 100644 index 000000000..8e6028514 --- /dev/null +++ b/include/rfl/Alias.hpp @@ -0,0 +1,253 @@ +#ifndef RFL_ALIAS_HPP_ +#define RFL_ALIAS_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "default.hpp" +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Declares a read-only field alias accepted during deserialization while +/// always serializing (and generating schemas) under the canonical primary +/// field name. +/// +/// Multiple aliases can be declared by nesting `rfl::Alias`: +/// `rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>>` +/// +/// @tparam _name The compile-time string literal alias name accepted on read +/// @tparam T The underlying value (or wrapped field) type +template +struct Alias { + /// The underlying type. + using Type = T; + + /// The alias name as a compile-time string literal. + static constexpr internal::StringLiteral alias_name_ = _name; + + /// Returns the alias name as a string_view. + static constexpr std::string_view alias_name() noexcept { + return alias_name_.string_view(); + } + + /// Default constructor - enabled only when Type is default-constructible. + template + requires std::is_default_constructible_v + Alias() noexcept(std::is_nothrow_default_constructible_v) : value_() {} + + /// Constructs from a const reference to the value. + Alias(const Type& _value) : value_(_value) {} + + /// Constructs from an rvalue reference to the value. + Alias(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + /// Move constructor. + Alias(Alias&& _field) noexcept = default; + + /// Copy constructor. + Alias(const Alias& _field) = default; + + /// Copy constructor from Alias with the same alias name and a compatible + /// underlying type. + template + requires(!std::is_same_v && std::is_convertible_v) + Alias(const Alias<_name, U>& _field) : value_(_field.get()) {} + + /// Move constructor from Alias with the same alias name and a compatible + /// underlying type. + template + requires(!std::is_same_v && std::is_convertible_v) + Alias(Alias<_name, U>&& _field) noexcept( + std::is_nothrow_constructible_v) + : value_(std::move(_field.value_)) {} + + /// Constructs from any type convertible to Type. + template + requires(!std::is_same_v, Alias> && + !std::is_same_v, Type> && + !std::is_same_v, Default> && + std::is_convertible_v) + Alias(U&& _value) noexcept(std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + /// Initializes the underlying object to its default value using the Default + /// sentinel. + template + requires std::is_default_constructible_v + Alias(const Default&) noexcept(std::is_nothrow_default_constructible_v) + : value_() {} + + /// Destructor. + ~Alias() = default; + + /// Returns a const reference to the underlying value. + const Type& get() const noexcept { return value_; } + + /// Returns a reference to the underlying value. + Type& get() noexcept { return value_; } + + /// Dereference operator - returns the underlying value. + Type& operator*() noexcept { return value_; } + + /// Dereference operator (const) - returns the underlying value. + const Type& operator*() const noexcept { return value_; } + + /// Function call operator - returns the underlying value. + Type& operator()() noexcept { return value_; } + + /// Function call operator (const) - returns the underlying value. + const Type& operator()() const noexcept { return value_; } + + /// Pointer to the underlying value. + Type* operator->() noexcept { return &value_; } + + /// Pointer to the underlying value (const). + const Type* operator->() const noexcept { return &value_; } + + /// Implicit conversion to a mutable reference to the underlying value. + operator Type&() noexcept { return value_; } + + /// Implicit conversion to a const reference to the underlying value. + operator const Type&() const noexcept { return value_; } + + /// Assigns a new value (copy). + auto& operator=(const Type& _value) { + value_ = _value; + return *this; + } + + /// Assigns a new value (move). + auto& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return *this; + } + + /// Assigns from any type convertible to the underlying type. + template + requires(!std::is_same_v, Alias> && + !std::is_same_v, Type> && + !std::is_same_v, Default> && + std::is_convertible_v) + auto& operator=(U&& _value) { + value_ = std::forward(_value); + return *this; + } + + /// Assigns the value to its default using the Default sentinel. + template + requires std::is_default_constructible_v + auto& operator=(const Default&) { + value_ = Type(); + return *this; + } + + /// Copy assignment operator. + Alias& operator=(const Alias& _field) = default; + + /// Move assignment operator. + Alias& operator=(Alias&& _field) noexcept = default; + + /// Assigns from another Alias with compatible underlying type (copy). + template + requires(!std::is_same_v && std::is_convertible_v) + auto& operator=(const Alias<_name, U>& _field) { + value_ = _field.get(); + return *this; + } + + /// Assigns from another Alias with compatible underlying type (move). + template + requires(!std::is_same_v && std::is_convertible_v) + auto& operator=(Alias<_name, U>&& _field) { + value_ = std::move(_field.value_); + return *this; + } + + /// Sets the value (copy). + void set(const Type& _value) { value_ = _value; } + + /// Sets the value (move). + void set(Type&& _value) noexcept(std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + } + + /// Returns a reference to the underlying value. + Type& value() noexcept { return value_; } + + /// Returns a const reference to the underlying value. + const Type& value() const noexcept { return value_; } + + /// The underlying value. + Type value_; +}; + +namespace internal { + +template +class is_alias : public std::false_type {}; + +template +class is_alias> : public std::true_type {}; + +template +constexpr bool is_alias_v = + is_alias>>::value; + +} // namespace internal + +/// Equality comparison between two Alias wrappers. +template + requires requires(const T1& _a, const T2& _b) { _a == _b; } +inline bool operator==(const Alias<_n1, T1>& _lhs, const Alias<_n2, T2>& _rhs) { + return _lhs.value() == _rhs.value(); +} + +/// Three-way comparison between two Alias wrappers. +template + requires requires(const T1& _a, const T2& _b) { _a <=> _b; } +inline auto operator<=>(const Alias<_n1, T1>& _lhs, + const Alias<_n2, T2>& _rhs) { + return _lhs.value() <=> _rhs.value(); +} + +/// Equality comparison between an Alias wrapper and a non-Alias value. +template + requires(!internal::is_alias_v && + requires(const T& _a, const U& _b) { _a == _b; }) +inline bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { + return _lhs.value() == _rhs; +} + +/// Three-way comparison between an Alias wrapper and a non-Alias value. +template + requires(!internal::is_alias_v && + requires(const T& _a, const U& _b) { _a <=> _b; }) +inline auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) { + return _lhs.value() <=> _rhs; +} + +} // namespace rfl + +namespace std { + +/// Specialization of std::hash for rfl::Alias. +template + requires requires(const T& _v) { std::hash{}(_v); } +struct hash> { + size_t operator()(const rfl::Alias<_name, T>& _a) const { + return hash{}(_a.value()); + } +}; + +} // namespace std + +#endif diff --git a/include/rfl/CamelCaseToSnakeCase.hpp b/include/rfl/CamelCaseToSnakeCase.hpp index dcc15d9e8..7ec29c06f 100644 --- a/include/rfl/CamelCaseToSnakeCase.hpp +++ b/include/rfl/CamelCaseToSnakeCase.hpp @@ -2,6 +2,7 @@ #define RFL_CAMELCASETOSNAKECASE_HPP_ #include "Field.hpp" +#include "internal/is_alias.hpp" #include "internal/is_rename.hpp" #include "internal/transform_case.hpp" @@ -18,7 +19,8 @@ struct CamelCaseToSnakeCase { static auto process(const auto& _named_tuple) { return _named_tuple.transform([](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { + !internal::is_rename_v< + internal::remove_alias_t>) { return handle_one_field(_f); } else { return _f; diff --git a/include/rfl/SnakeCaseToCamelCase.hpp b/include/rfl/SnakeCaseToCamelCase.hpp index d073b0b4a..328a49129 100644 --- a/include/rfl/SnakeCaseToCamelCase.hpp +++ b/include/rfl/SnakeCaseToCamelCase.hpp @@ -2,6 +2,7 @@ #define RFL_SNAKECASETOCAMELCASE_HPP_ #include "Field.hpp" +#include "internal/is_alias.hpp" #include "internal/is_rename.hpp" #include "internal/transform_case.hpp" @@ -18,7 +19,8 @@ struct SnakeCaseToCamelCase { static auto process(const auto& _named_tuple) { return _named_tuple.transform([](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { + !internal::is_rename_v< + internal::remove_alias_t>) { return handle_one_field(_f); } else { return _f; diff --git a/include/rfl/SnakeCaseToKebabCase.hpp b/include/rfl/SnakeCaseToKebabCase.hpp index 4b9d09a6f..00a480dd3 100644 --- a/include/rfl/SnakeCaseToKebabCase.hpp +++ b/include/rfl/SnakeCaseToKebabCase.hpp @@ -2,6 +2,7 @@ #define RFL_SNAKECASETOKEBABCASE_HPP_ #include "Field.hpp" +#include "internal/is_alias.hpp" #include "internal/is_rename.hpp" #include "internal/transform_case.hpp" @@ -20,7 +21,8 @@ struct SnakeCaseToKebabCase { // "xml_content" is a reserved name used by the XML Reader/Writer; // all case-transform processors must leave it unchanged. if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { + !internal::is_rename_v< + internal::remove_alias_t>) { return handle_one_field(_f); } else { return _f; diff --git a/include/rfl/SnakeCaseToPascalCase.hpp b/include/rfl/SnakeCaseToPascalCase.hpp index f10361da0..8194d8b9c 100644 --- a/include/rfl/SnakeCaseToPascalCase.hpp +++ b/include/rfl/SnakeCaseToPascalCase.hpp @@ -2,6 +2,7 @@ #define RFL_SNAKECASETOPASCALCASE_HPP_ #include "Field.hpp" +#include "internal/is_alias.hpp" #include "internal/is_rename.hpp" #include "internal/transform_case.hpp" @@ -18,7 +19,8 @@ struct SnakeCaseToPascalCase { static auto process(const auto& _named_tuple) { const auto handle_one = [](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { + !internal::is_rename_v< + internal::remove_alias_t>) { return handle_one_field(_f); } else { return _f; diff --git a/include/rfl/ToAllCaps.hpp b/include/rfl/ToAllCaps.hpp index c86bad16b..2ebc60827 100644 --- a/include/rfl/ToAllCaps.hpp +++ b/include/rfl/ToAllCaps.hpp @@ -2,6 +2,7 @@ #define RFL_TOALLCAPS_HPP_ #include "Field.hpp" +#include "internal/is_alias.hpp" #include "internal/is_rename.hpp" #include "internal/transform_case.hpp" @@ -18,7 +19,8 @@ struct ToAllCaps { static auto process(const auto& _named_tuple) { return _named_tuple.transform([](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && - !internal::is_rename_v) { + !internal::is_rename_v< + internal::remove_alias_t>) { return handle_one_field(_f); } else { return _f; diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index bfa62c928..075ef9b26 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -10,6 +10,7 @@ #include #include +#include "../Alias.hpp" #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" @@ -18,8 +19,10 @@ #include "../Short.hpp" #include "../Tuple.hpp" #include "../internal/StringLiteral.hpp" +#include "../internal/field_aliases.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" +#include "../internal/is_alias.hpp" #include "../internal/is_extra_fields.hpp" #include "../internal/is_named_tuple.hpp" #include "../internal/is_positional.hpp" @@ -58,9 +61,13 @@ struct Option { /// aliases and positional arguments to fields. Names are the field names /// after processors (kebab-case, rfl::Rename) are applied. struct Options { - /// The options of the top-level fields, by name. + /// The options of the top-level fields, by name (including rfl::Alias names). std::map long_options; + /// Read-only long option aliases given by rfl::Alias (`old-name` for + /// `--old-name`), mapped to the canonical name of their field. + std::map long_aliases; + /// The short aliases given by rfl::Short (`p` for `-p`), mapped to the path /// of their field. std::map short_options; @@ -140,6 +147,9 @@ struct cli_annotations> 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; @@ -214,6 +224,7 @@ auto unwrap_option_type() { } else if constexpr (rfl::internal::is_short_v || rfl::internal::is_positional_v + || rfl::internal::is_alias_v || parsing::is_rename_v || parsing::is_default_val_v || parsing::is_skip_v) { @@ -287,7 +298,18 @@ template void add_option_for_field(Options* _options) { using T = std::remove_cvref_t; if constexpr (!rfl::internal::is_extra_fields_v) { - add_option(std::string(FieldType::name()), _options); + const auto canonical = std::string(FieldType::name()); + add_option(canonical, _options); + using Aliases = rfl::internal::field_aliases_t; + if constexpr (Aliases::size > 0) { + for (const auto alias : Aliases::to_array()) { + const auto alias_str = std::string(alias); + add_option(alias_str, _options); + if (alias_str != canonical) { + _options->long_aliases.emplace(alias_str, canonical); + } + } + } } } @@ -295,6 +317,9 @@ void add_option_for_field(Options* _options) { template void collect_options(Options* _options) { using NT = option_fields_t; + static_assert( + rfl::internal::no_alias_collisions(), + "Field alias collides with another field's name or alias."); [&](std::index_sequence<_is...>) { (add_option_for_field, ProcessorsType>(_options), diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 1bd79d9eb..733f7cc02 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -87,7 +87,17 @@ inline rfl::Unexpected too_many_positionals(const size_t _expected, inline rfl::Result> resolve_args( ParsedArgs _parsed, const Options& _options ) { - auto& result = _parsed.named; + std::map result; + for (auto& [key, val] : _parsed.named) { + const auto it = _options.long_aliases.find(key); + const auto& target = + it == _options.long_aliases.end() ? key : it->second; + if (!result.emplace(target, std::move(val)).second) { + return rfl::error( + "Conflict: '--" + key + "' and '--" + target + + "' refer to the same field."); + } + } // Merge positional args. const auto& positional_names = _options.positionals; diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..865649c25 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -8,11 +8,15 @@ #include #include #include +#include #include #include #include +#include #include "../Result.hpp" +#include "../Tuple.hpp" +#include "../internal/field_aliases.hpp" #if defined(__APPLE__) #include @@ -230,15 +234,41 @@ struct Reader { if constexpr (has_view_type) { using ViewType = typename std::remove_cvref_t::ViewType; - using NamesType = typename ViewType::Names; - const auto names = NamesType::names(); - for (const auto& name : names) { - const auto child_path = _obj.prefix.empty() ? name : _obj.prefix + name; - const auto var = InputVarType{.path = child_path}; - if (!is_empty(var)) { - _object_reader.read(std::string_view(name), var); - } - } + using FieldsType = typename ViewType::Fields; + [&](std::index_sequence) { + ( + [&]() { + using FieldType = + std::remove_cvref_t>; + const std::string primary(FieldType::name()); + const auto child_path = + _obj.prefix.empty() ? primary : _obj.prefix + primary; + const auto var = InputVarType{.path = child_path}; + if (!is_empty(var)) { + _object_reader.read(std::string_view(primary), var); + } + using Aliases = + rfl::internal::field_aliases_t; + if constexpr (Aliases::size > 0) { + std::set seen_aliases; + seen_aliases.insert(FieldType::name()); + for (const auto alias : Aliases::to_array()) { + if (!seen_aliases.insert(alias).second) { + continue; + } + const std::string alias_str(alias); + const auto alias_path = _obj.prefix.empty() + ? alias_str + : _obj.prefix + alias_str; + const auto alias_var = InputVarType{.path = alias_path}; + if (!is_empty(alias_var)) { + _object_reader.read(alias, alias_var); + } + } + } + }.template operator()(), + ...); + }(std::make_index_sequence>()); } else { for (char** env = get_environ(); *env != nullptr; ++env) { diff --git a/include/rfl/internal/cpp20/get_field_names.hpp b/include/rfl/internal/cpp20/get_field_names.hpp index 707a0590a..2b3c85cf9 100644 --- a/include/rfl/internal/cpp20/get_field_names.hpp +++ b/include/rfl/internal/cpp20/get_field_names.hpp @@ -12,6 +12,7 @@ #include "../../Literal.hpp" #include "../concat_literals.hpp" +#include "../is_alias.hpp" #include "../is_flatten_field.hpp" #include "../is_rename.hpp" #include "get_ith_field_from_fake_object.hpp" @@ -88,8 +89,9 @@ consteval auto get_field_name() { #else using Type = std::remove_cvref_t>; #endif - if constexpr (is_rename_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v) { + using Name = typename UnwrappedType::Name; return Name(); } else if constexpr (is_flatten_field_v) { return get_field_names>(); diff --git a/include/rfl/internal/cpp20/get_member_ptr_name.hpp b/include/rfl/internal/cpp20/get_member_ptr_name.hpp index 37e3a81da..d8c1b5ac9 100644 --- a/include/rfl/internal/cpp20/get_member_ptr_name.hpp +++ b/include/rfl/internal/cpp20/get_member_ptr_name.hpp @@ -5,6 +5,7 @@ #include #include "../StringLiteral.hpp" +#include "../is_alias.hpp" #include "../is_field.hpp" #include "../is_rename.hpp" #include "../lit_name.hpp" @@ -66,8 +67,9 @@ using ptr_type_t = member_type_helper::ptr_type; template consteval auto get_member_ptr_name() { using Type = ptr_type_t; - if constexpr (is_rename_v || is_field_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v || is_field_v) { + using Name = typename UnwrappedType::Name; return lit_name_v; } else { using StructType = struct_type_t; diff --git a/include/rfl/internal/cpp26/get_field_names.hpp b/include/rfl/internal/cpp26/get_field_names.hpp index 07d872f84..e82993589 100644 --- a/include/rfl/internal/cpp26/get_field_names.hpp +++ b/include/rfl/internal/cpp26/get_field_names.hpp @@ -13,6 +13,7 @@ #include "../../Tuple.hpp" #include "../StringLiteral.hpp" #include "../concat_literals.hpp" +#include "../is_alias.hpp" #include "../is_flatten_field.hpp" #include "../is_rename.hpp" #include "bind_to_tuple.hpp" @@ -26,8 +27,9 @@ consteval auto get_field_names(); template consteval auto get_field_names_impl() { using Type = std::remove_cvref_t>; - if constexpr (is_rename_v) { - using Name = typename Type::Name; + using UnwrappedType = remove_alias_t; + if constexpr (is_rename_v) { + using Name = typename UnwrappedType::Name; return Name(); } else if constexpr (is_flatten_field_v) { return get_field_names>(); diff --git a/include/rfl/internal/field_aliases.hpp b/include/rfl/internal/field_aliases.hpp new file mode 100644 index 000000000..0ea794814 --- /dev/null +++ b/include/rfl/internal/field_aliases.hpp @@ -0,0 +1,188 @@ +#ifndef RFL_INTERNAL_FIELD_ALIASES_HPP_ +#define RFL_INTERNAL_FIELD_ALIASES_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "../Alias.hpp" +#include "../Attribute.hpp" +#include "../Commented.hpp" +#include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.hpp" +#include "../Positional.hpp" +#include "../Rename.hpp" +#include "../Short.hpp" +#include "../Skip.hpp" +#include "../Tuple.hpp" +#include "StringLiteral.hpp" + +namespace rfl::internal { + +/// Compile-time list of read-only alias names declared on a field. +template +struct AliasList { + static constexpr size_t size = sizeof...(_names); + + static constexpr std::array + to_array() noexcept { + return {_names.string_view()...}; + } + + static constexpr bool contains(std::string_view _name) noexcept { + return ((_name == _names.string_view()) || ...); + } +}; + +template +struct prepend_alias; + +template +struct prepend_alias<_head, AliasList<_tail...>> { + using type = AliasList<_head, _tail...>; +}; + +/// Collects all rfl::Alias names declared on a field type, unwrapping through +/// transparent field wrappers (Alias, Rename, Description, Deprecated, +/// DefaultVal, Short, Positional, std::optional, Skip, Attribute, Commented). +template +struct field_aliases_impl { + using type = AliasList<>; +}; + +template +using field_aliases_t = typename field_aliases_impl< + std::remove_cvref_t>>::type; + +template +struct field_aliases_impl> { + using type = typename prepend_alias<_name, field_aliases_t>::type; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +/// Returns true if any field in Fields declares at least one rfl::Alias. +template +consteval bool has_any_aliases() { + constexpr size_t N = rfl::tuple_size_v; + return [](std::index_sequence) { + return (false || ... || + (field_aliases_t>::Type>::size > 0)); + }(std::make_index_sequence()); +} + +/// Checks at compile time that no alias on field A equals the primary wire name +/// or any alias on a different field B. +template +consteval bool no_alias_collisions() { + constexpr size_t N = rfl::tuple_size_v; + if constexpr (N <= 1 || !has_any_aliases()) { + return true; + } else { + constexpr auto primary_names = + [](std::index_sequence) { + return std::array{ + std::remove_cvref_t>::name()...}; + }(std::make_index_sequence()); + + constexpr size_t total_aliases = + [](std::index_sequence) { + return (size_t{0} + ... + + field_aliases_t>::Type>::size); + }(std::make_index_sequence()); + + struct AliasEntry { + size_t field_idx; + std::string_view name; + }; + + std::array all_aliases{}; + size_t pos = 0; + [&](std::index_sequence) { + ( + [&]() { + constexpr auto arr = + field_aliases_t>::Type>::to_array(); + for (const auto sv : arr) { + all_aliases[pos++] = AliasEntry{I, sv}; + } + }.template operator()(), + ...); + }(std::make_index_sequence()); + + for (size_t a = 0; a < total_aliases; ++a) { + for (size_t f = 0; f < N; ++f) { + if (f != all_aliases[a].field_idx && + all_aliases[a].name == primary_names[f]) { + return false; + } + } + for (size_t b = a + 1; b < total_aliases; ++b) { + if (all_aliases[a].field_idx != all_aliases[b].field_idx && + all_aliases[a].name == all_aliases[b].name) { + return false; + } + } + } + return true; + } +} + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/is_alias.hpp b/include/rfl/internal/is_alias.hpp new file mode 100644 index 000000000..b0b688398 --- /dev/null +++ b/include/rfl/internal/is_alias.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_ISALIAS_HPP_ +#define RFL_INTERNAL_ISALIAS_HPP_ + +#include + +#include "../Alias.hpp" +#include "StringLiteral.hpp" + +namespace rfl::internal { + +template +struct remove_alias { + using Type = T; +}; + +template +struct remove_alias> { + using Type = typename remove_alias>::Type; +}; + +template +using remove_alias_t = + typename remove_alias>>::Type; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/is_attribute.hpp b/include/rfl/internal/is_attribute.hpp index 408dbfafa..9d3e7e5be 100644 --- a/include/rfl/internal/is_attribute.hpp +++ b/include/rfl/internal/is_attribute.hpp @@ -4,6 +4,7 @@ #include #include "../Attribute.hpp" +#include "is_alias.hpp" #include "remove_rename.hpp" namespace rfl::internal { @@ -18,7 +19,8 @@ template class is_attribute> : public std::true_type {}; template -constexpr bool is_attribute_v = is_attribute>::value; +constexpr bool is_attribute_v = + is_attribute>>>::value; } // namespace rfl::internal diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 01189f634..5d039ce40 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -4,8 +4,13 @@ #include #include +#include "../Alias.hpp" #include "../DefaultVal.hpp" +#include "../Deprecated.hpp" +#include "../Description.hpp" +#include "../Positional.hpp" #include "../Rename.hpp" +#include "../Short.hpp" #include "StringLiteral.hpp" namespace rfl::internal { @@ -20,8 +25,29 @@ template class is_default_val> : public std::true_type {}; template -class is_default_val>> : public std::true_type { -}; +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; + +template +class is_default_val> + : public is_default_val> {}; template constexpr bool is_default_val_v = @@ -35,7 +61,7 @@ const DefaultVal& get_default_val(const DefaultVal& _field) noexcept { template requires is_default_val_v -const auto& get_default_val(const T& _field) noexcept { +const auto& get_default_val(const T& _field) { return get_default_val(_field.value()); } diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..6d8213e62 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -12,6 +12,7 @@ #include "../Result.hpp" #include "../internal/always_inline.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/field_aliases.hpp" #include "../internal/has_default_val_v.hpp" #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" @@ -71,7 +72,7 @@ concept CanWriteGeneric = /// it must be a `DefaultVal` that satisfies `CanWriteGeneric`. template concept CanEmitDefault = - is_default_val_v && CanWriteGeneric; + is_default_val_v && CanWriteGeneric::Type>; } // namespace internal } // namespace rfl @@ -115,6 +116,10 @@ struct NamedTupleParser { "You cannot use the rfl::NoFieldNames processor if you are " "including rfl::ExtraFields."); + static_assert( + internal::no_alias_collisions(), + "Field alias collides with another field's name or alias."); + public: /** * @brief Reads a named tuple from the input. @@ -297,8 +302,8 @@ struct NamedTupleParser { s.variant_.visit([&](auto& value) { if constexpr (std::is_same_v, schema::Type::DefaultVal>) { - value.default_value_ = - rfl::to_generic((*rfl::get<_i>(*_view)).get()); + value.default_value_ = rfl::to_generic( + internal::get_default_val(*rfl::get<_i>(*_view)).get()); } }); } diff --git a/include/rfl/parsing/ParserAlias.hpp b/include/rfl/parsing/ParserAlias.hpp new file mode 100644 index 000000000..623bd9886 --- /dev/null +++ b/include/rfl/parsing/ParserAlias.hpp @@ -0,0 +1,71 @@ +#ifndef RFL_PARSING_PARSER_ALIAS_HPP_ +#define RFL_PARSING_PARSER_ALIAS_HPP_ + +#include +#include +#include +#include + +#include "../Alias.hpp" +#include "../Result.hpp" +#include "../internal/StringLiteral.hpp" +#include "Parser_base.hpp" +#include "schema/Type.hpp" + +namespace rfl::parsing { + +template +struct is_alias : std::false_type {}; + +template +struct is_alias> : std::true_type { + using element_type = T; + static constexpr auto name = _name; +}; + +template +constexpr bool is_alias_v = is_alias>::value; + +template +struct ParserAlias; + +template +struct ParserAlias, ProcessorsType> { + using InputVarType = typename R::InputVarType; + + /** + * @brief Reads an aliased value from the input. + */ + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_alias = [](auto&& _t) { + return Alias<_name, T>(std::forward(_t)); + }; + return Parser, ProcessorsType>::read(_r, _var) + .transform(to_alias); + } + + /** + * @brief Writes an aliased value to the output. + */ + template + static void write(const W& _w, const Alias<_name, T>& _alias, + const P& _parent) { + Parser, ProcessorsType>::write( + _w, _alias.value(), _parent); + } + + /** + * @brief Generates the schema for the aliased value. + */ + 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 80d98b31a..3671f74da 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -27,6 +27,7 @@ #include "AreReaderAndWriter.hpp" #include "MapParser.hpp" #include "Parent.hpp" +#include "ParserAlias.hpp" #include "ParserArray.hpp" #include "ParserAtomic.hpp" #include "ParserAtomicFlag.hpp" @@ -141,6 +142,9 @@ struct Parser { } else if constexpr (is_rename_v) { return ParserRename::read(_r, _var); + } else if constexpr (is_alias_v) { + return ParserAlias::read(_r, _var); + } else if constexpr (is_result_v) { return ParserResult::read(_r, _var); @@ -342,6 +346,9 @@ struct Parser { } else if constexpr (is_rename_v) { ParserRename::write(_w, _var, _parent); + } else if constexpr (is_alias_v) { + ParserAlias::write(_w, _var, _parent); + } else if constexpr (is_duration_v) { using U = std::remove_cvref_t; ParserDuration) { return ParserRename::to_schema(_definitions); + } else if constexpr (is_alias_v) { + return ParserAlias::to_schema(_definitions); + } else if constexpr (is_result_v) { return ParserResult::to_schema(_definitions); diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..505ab8bb4 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -10,6 +10,7 @@ #include "../Tuple.hpp" #include "../internal/always_inline.hpp" +#include "../internal/field_aliases.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" @@ -90,7 +91,14 @@ class ViewReader { template static bool is_matching(const std::string_view& _current_name) { - return _current_name == FieldType::name(); + if (_current_name == FieldType::name()) { + return true; + } + using Aliases = internal::field_aliases_t; + if constexpr (Aliases::size > 0) { + return Aliases::contains(_current_name); + } + return false; } static ErrorDetail::PathSegment to_path_segment(const int _current_index) { @@ -111,25 +119,58 @@ class ViewReader { using OriginalType = typename FieldType::Type; using T = std::remove_cvref_t>; - if (!(*_already_assigned) && !std::get(*_found) && - is_matching(_current_name_or_index)) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) [[unlikely]] { - constexpr auto name = FieldType::name(); - // Reserve lazily to avoid error-vector reallocations while keeping - // successful reads allocation-free. - _errors->reserve(size_); - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; + using Aliases = internal::field_aliases_t; + if constexpr (Aliases::size == 0) { + if (!(*_already_assigned) && !std::get(*_found) && + is_matching(_current_name_or_index)) { + std::get(*_found) = true; + *_already_assigned = true; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + constexpr auto name = FieldType::name(); + // Reserve lazily to avoid error-vector reallocations while keeping + // successful reads allocation-free. + _errors->reserve(size_); + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } + std::get(*_set) = true; } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); + } else { + if (!(*_already_assigned) && + is_matching(_current_name_or_index)) { + if (std::get(*_found)) [[unlikely]] { + *_already_assigned = true; + std::stringstream stream; + stream << "Field named '" << FieldType::name() + << "' was specified more than once (conflicting key '" + << _current_name_or_index << "')."; + _errors->reserve(size_); + _errors->emplace_back(make_nested_error( + to_path_segment(_current_name_or_index), stream.str())); + return; + } + std::get(*_found) = true; + *_already_assigned = true; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + constexpr auto name = FieldType::name(); + _errors->reserve(size_); + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } + std::get(*_set) = true; } - std::get(*_set) = true; } } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..0532a94c8 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -10,6 +10,7 @@ #include "../Ref.hpp" #include "../Tuple.hpp" +#include "../internal/field_aliases.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" @@ -68,6 +69,18 @@ class ViewReaderWithDefault { static constexpr size_t size() { return size_; } private: + template + static bool is_matching(const std::string_view& _current_name) { + if (_current_name == FieldType::name()) { + return true; + } + using Aliases = internal::field_aliases_t; + if constexpr (Aliases::size > 0) { + return Aliases::contains(_current_name); + } + return false; + } + template static void assign_if_field_matches(const R& _r, const std::string_view& _current_name, @@ -78,20 +91,48 @@ class ViewReaderWithDefault { using OriginalType = typename FieldType::Type; using T = std::remove_cvref_t>; + using Aliases = internal::field_aliases_t; constexpr auto name = FieldType::name(); - if (!(*_already_assigned) && !std::get(*_found) && - _current_name == name) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; + if constexpr (Aliases::size == 0) { + if (!(*_already_assigned) && !std::get(*_found) && + _current_name == name) { + std::get(*_found) = true; + *_already_assigned = true; + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); + } else { + if (!(*_already_assigned) && is_matching(_current_name)) { + if (std::get(*_found)) [[unlikely]] { + *_already_assigned = true; + std::stringstream stream; + stream << "Field named '" << name + << "' was specified more than once (conflicting key '" + << _current_name << "')."; + _errors->emplace_back( + make_nested_error(std::string(_current_name), stream.str())); + return; + } + std::get(*_found) = true; + *_already_assigned = true; + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } } } } diff --git a/include/rfl/parsing/is_empty.hpp b/include/rfl/parsing/is_empty.hpp index 7f77a7c78..1fa587633 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_alias.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_alias_v) { return is_empty(_var.value()); } else if constexpr (is_map_like_v || is_vector_like_v) { return _var.begin() == _var.end(); diff --git a/include/rfl/parsing/is_required.hpp b/include/rfl/parsing/is_required.hpp index 30fe10f6a..633e0f88f 100644 --- a/include/rfl/parsing/is_required.hpp +++ b/include/rfl/parsing/is_required.hpp @@ -11,6 +11,7 @@ #include "../Short.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_alias.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_rename.hpp" #include "../internal/is_short.hpp" @@ -63,6 +64,8 @@ consteval bool is_required() { return is_required(); } else if constexpr (internal::is_short_v) { return is_required(); + } else if constexpr (internal::is_alias_v) { + return is_required(); } else { return !(is_never_required_v || (_ignore_empty_containers && diff --git a/tests/cli/test_alias.cpp b/tests/cli/test_alias.cpp new file mode 100644 index 000000000..9166fd568 --- /dev/null +++ b/tests/cli/test_alias.cpp @@ -0,0 +1,108 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_cli_alias { + +struct ServerConfig { + rfl::Alias<"download_dir", rfl::Alias<"downloadDir", std::string>> + download_dir; + rfl::Short<"v", rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; + rfl::Alias<"listen-port", rfl::DefaultVal> port = 8080; + rfl::Positional>> input; +}; + +TEST(cli, test_alias_basic_and_no_extra_fields) { + const auto res = rfl::cli::read( + {"--download_dir=/var/dl", "--debug", "--listen-port=9090", + "--src=file.txt"}); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->download_dir, "/var/dl"); + EXPECT_TRUE(res->verbose.value().value().value()); + EXPECT_EQ(res->port.value().value(), 9090); + ASSERT_TRUE(res->input.value().value().has_value()); + EXPECT_EQ(*res->input.value().value(), "file.txt"); + + // Second chained alias also works. + const auto res2 = rfl::cli::read( + {"--downloadDir=/camel"}); + ASSERT_TRUE(res2) << res2.error().what(); + EXPECT_EQ(res2->download_dir, "/camel"); + EXPECT_FALSE(res2->verbose.value().value().value()); + EXPECT_EQ(res2->port.value().value(), 8080); + + // Canonical kebab-case name still works. + const auto res3 = rfl::cli::read( + {"--download-dir=/kebab", "-v", "pos.txt"}); + ASSERT_TRUE(res3) << res3.error().what(); + EXPECT_EQ(res3->download_dir, "/kebab"); + EXPECT_TRUE(res3->verbose.value().value().value()); + EXPECT_EQ(*res3->input.value().value(), "pos.txt"); +} + +TEST(cli, test_alias_conflicts_rejected) { + // Primary + alias conflict. + const auto c1 = rfl::cli::read( + {"--download-dir=/a", "--download_dir=/b"}); + EXPECT_FALSE(c1); + + // Two aliases of the same field conflict. + const auto c2 = rfl::cli::read( + {"--download_dir=/a", "--downloadDir=/b"}); + EXPECT_FALSE(c2); + + // Short flag + alias conflict. + const auto c3 = rfl::cli::read( + {"--download-dir=/a", "-v", "--debug"}); + EXPECT_FALSE(c3); + + // Positional + alias conflict. + const auto c4 = rfl::cli::read( + {"--download-dir=/a", "pos.txt", "--src=other.txt"}); + EXPECT_FALSE(c4); +} + +struct AliasWrappingShortAndPositional { + rfl::Alias<"old-flag", rfl::Short<"f", rfl::DefaultVal>> flag = false; + rfl::Alias<"old-file", rfl::Positional> file; +}; + +TEST(cli, test_alias_outer_around_short_and_positional) { + // -f must still be recognized as a bool flag through outer rfl::Alias, + // leaving "data.txt" for the positional field. + const auto res = + rfl::cli::read( + {"-f", "data.txt"}); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(res->flag.value().value().value()); + EXPECT_EQ(res->file.value().value(), "data.txt"); + + // Passing both via their aliases also works. + const auto via_alias = + rfl::cli::read( + {"--old-flag", "--old-file=other.txt"}); + ASSERT_TRUE(via_alias) << via_alias.error().what(); + EXPECT_TRUE(via_alias->flag.value().value().value()); + EXPECT_EQ(via_alias->file.value().value(), "other.txt"); +} + +struct NestedDb { + rfl::Alias<"hostname", std::string> host; +}; + +struct AppConfig { + rfl::Alias<"database", NestedDb> db; +}; + +TEST(cli, test_alias_nested_struct) { + const auto res = rfl::cli::read( + {"--database.hostname=db.local"}); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->db.value().host, "db.local"); +} + +} // namespace test_cli_alias diff --git a/tests/generic/CMakeLists.txt b/tests/generic/CMakeLists.txt index 59e1f17e2..f036a2bed 100644 --- a/tests/generic/CMakeLists.txt +++ b/tests/generic/CMakeLists.txt @@ -39,3 +39,36 @@ add_library(generic-compile-fail-flatten-cross-type-move-assign OBJECT EXCLUDE_F ) target_link_libraries(generic-compile-fail-flatten-cross-type-move-assign PRIVATE reflectcpp_tests_crt) +# Compile-time alias collision checks must fail to compile (WILL_FAIL TRUE). +add_test( + NAME compile_fail.alias_collides_with_primary + COMMAND ${CMAKE_COMMAND} + --build ${CMAKE_BINARY_DIR} + --target generic-compile-fail-alias-collides-with-primary + --config $ +) +set_tests_properties( + compile_fail.alias_collides_with_primary + PROPERTIES WILL_FAIL TRUE +) +add_library(generic-compile-fail-alias-collides-with-primary OBJECT EXCLUDE_FROM_ALL + compile_fail/alias_collides_with_primary.cpp +) +target_link_libraries(generic-compile-fail-alias-collides-with-primary PRIVATE reflectcpp_tests_crt) + +add_test( + NAME compile_fail.alias_collides_with_alias + COMMAND ${CMAKE_COMMAND} + --build ${CMAKE_BINARY_DIR} + --target generic-compile-fail-alias-collides-with-alias + --config $ +) +set_tests_properties( + compile_fail.alias_collides_with_alias + PROPERTIES WILL_FAIL TRUE +) +add_library(generic-compile-fail-alias-collides-with-alias OBJECT EXCLUDE_FROM_ALL + compile_fail/alias_collides_with_alias.cpp +) +target_link_libraries(generic-compile-fail-alias-collides-with-alias PRIVATE reflectcpp_tests_crt) + diff --git a/tests/generic/compile_fail/alias_collides_with_alias.cpp b/tests/generic/compile_fail/alias_collides_with_alias.cpp new file mode 100644 index 000000000..2fc0e3b82 --- /dev/null +++ b/tests/generic/compile_fail/alias_collides_with_alias.cpp @@ -0,0 +1,15 @@ +#include + +struct CollidesWithAlias { + rfl::Alias<"legacy", int> first; + rfl::Alias<"legacy", int> second; +}; + +int main() { + rfl::Generic::Object obj; + obj["first"] = 1; + obj["second"] = 2; + auto res = rfl::from_generic(rfl::Generic(obj)); + (void)res; + return 0; +} diff --git a/tests/generic/compile_fail/alias_collides_with_primary.cpp b/tests/generic/compile_fail/alias_collides_with_primary.cpp new file mode 100644 index 000000000..e7f82498f --- /dev/null +++ b/tests/generic/compile_fail/alias_collides_with_primary.cpp @@ -0,0 +1,15 @@ +#include + +struct CollidesWithPrimary { + rfl::Alias<"other", int> first; + int other; +}; + +int main() { + rfl::Generic::Object obj; + obj["first"] = 1; + obj["other"] = 2; + auto res = rfl::from_generic(rfl::Generic(obj)); + (void)res; + return 0; +} diff --git a/tests/generic/test_alias.cpp b/tests/generic/test_alias.cpp new file mode 100644 index 000000000..ffa600082 --- /dev/null +++ b/tests/generic/test_alias.cpp @@ -0,0 +1,43 @@ +#include + +#include +#include + +namespace test_generic_alias { + +struct Settings { + rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>> + download_dir; + rfl::Alias<"speedLimitDown", int> speed_limit_down; +}; + +TEST(generic, test_alias_from_and_to_generic) { + rfl::Generic::Object obj; + obj["download-dir"] = std::string("/downloads"); + obj["speedLimitDown"] = 300; + + const auto res = + rfl::from_generic(rfl::Generic(obj)); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->download_dir, "/downloads"); + EXPECT_EQ(res->speed_limit_down, 300); + + // to_generic emits canonical primary names only. + const auto gen = rfl::to_generic(*res); + const auto out_obj = gen.to_object().value(); + EXPECT_EQ(out_obj.get("download_dir").value().to_string().value(), + "/downloads"); + EXPECT_EQ(out_obj.get("speed_limit_down").value().to_int().value(), 300); + EXPECT_FALSE(out_obj.get("download-dir")); + EXPECT_FALSE(out_obj.get("speedLimitDown")); + + // Duplicate / conflicting keys in Generic::Object are rejected. + rfl::Generic::Object dup; + dup["download_dir"] = std::string("/a"); + dup["downloadDir"] = std::string("/b"); + dup["speed_limit_down"] = 10; + const auto bad = rfl::from_generic(rfl::Generic(dup)); + EXPECT_FALSE(bad); +} + +} // namespace test_generic_alias diff --git a/tests/json/test_alias.cpp b/tests/json/test_alias.cpp new file mode 100644 index 000000000..3d31060e5 --- /dev/null +++ b/tests/json/test_alias.cpp @@ -0,0 +1,306 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_alias { + +struct TransmissionSettings { + rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>> + download_dir; + rfl::Alias<"speed-limit-down", rfl::Alias<"speedLimitDown", int>> + speed_limit_down; +}; + +TEST(json, test_alias_single_and_chained) { + // Read via canonical primary name. + const auto from_canonical = rfl::json::read( + R"({"download_dir":"/downloads","speed_limit_down":100})"); + ASSERT_TRUE(from_canonical) << from_canonical.error().what(); + EXPECT_EQ(from_canonical->download_dir, "/downloads"); + EXPECT_EQ(from_canonical->speed_limit_down, 100); + + // Read via kebab-case legacy aliases. + const auto from_kebab = rfl::json::read( + R"({"download-dir":"/legacy","speed-limit-down":250})"); + ASSERT_TRUE(from_kebab) << from_kebab.error().what(); + EXPECT_EQ(from_kebab->download_dir, "/legacy"); + EXPECT_EQ(from_kebab->speed_limit_down, 250); + + // Read via camelCase legacy aliases. + const auto from_camel = rfl::json::read( + R"({"downloadDir":"/camel","speedLimitDown":500})"); + ASSERT_TRUE(from_camel) << from_camel.error().what(); + EXPECT_EQ(from_camel->download_dir, "/camel"); + EXPECT_EQ(from_camel->speed_limit_down, 500); + + // Serialization ALWAYS emits the canonical primary wire names. + EXPECT_EQ(rfl::json::write(*from_kebab), + R"({"download_dir":"/legacy","speed_limit_down":250})"); + EXPECT_EQ(rfl::json::write(*from_camel), + R"({"download_dir":"/camel","speed_limit_down":500})"); +} + +TEST(json, test_alias_no_extra_fields) { + // Aliases must NOT be rejected by rfl::NoExtraFields. + const auto ok = rfl::json::read( + R"({"download-dir":"/downloads","speedLimitDown":42})"); + ASSERT_TRUE(ok) << ok.error().what(); + EXPECT_EQ(ok->download_dir, "/downloads"); + EXPECT_EQ(ok->speed_limit_down, 42); + + // Truly unknown keys are still rejected. + const auto bad = rfl::json::read( + R"({"download-dir":"/downloads","speedLimitDown":42,"unknown":1})"); + EXPECT_FALSE(bad); +} + +TEST(json, test_alias_duplicate_and_conflicting_keys_rejected) { + // Primary + alias in the same object. + const auto primary_then_alias = rfl::json::read( + R"({"download_dir":"/a","download-dir":"/b","speed_limit_down":1})"); + EXPECT_FALSE(primary_then_alias); + + // Alias + primary in the same object. + const auto alias_then_primary = rfl::json::read( + R"({"download-dir":"/a","download_dir":"/b","speed_limit_down":1})"); + EXPECT_FALSE(alias_then_primary); + + // Two aliases of the same field in the same object. + const auto two_aliases = rfl::json::read( + R"({"download-dir":"/a","downloadDir":"/b","speed_limit_down":1})"); + EXPECT_FALSE(two_aliases); + + // Also rejected under NoExtraFields with clear error. + const auto with_no_extra = + rfl::json::read( + R"({"download-dir":"/a","downloadDir":"/b","speed_limit_down":1})"); + EXPECT_FALSE(with_no_extra); +} + +struct WithRename { + rfl::Rename<"download_dir", rfl::Alias<"download-dir", std::string>> dir_a; + rfl::Alias<"upload-dir", rfl::Rename<"upload_dir", std::string>> dir_b; + rfl::Alias<"old-c", rfl::Rename<"canonical_c", rfl::Alias<"oldC", int>>> c; +}; + +TEST(json, test_alias_with_rename_both_orders) { + const auto r1 = rfl::json::read( + R"({"download-dir":"/a","upload-dir":"/b","oldC":7})"); + ASSERT_TRUE(r1) << r1.error().what(); + EXPECT_EQ(r1->dir_a.value(), "/a"); + EXPECT_EQ(r1->dir_b.value().value(), "/b"); + EXPECT_EQ(r1->c.value().value(), 7); + + EXPECT_EQ(rfl::json::write(*r1), + R"({"download_dir":"/a","upload_dir":"/b","canonical_c":7})"); + + // Rename overrides SnakeCaseToCamelCase regardless of wrapper order. + const auto r2 = + rfl::json::read( + R"({"download_dir":"/x","upload_dir":"/y","old-c":9})"); + ASSERT_TRUE(r2) << r2.error().what(); + EXPECT_EQ( + rfl::json::write(*r2), + R"({"download_dir":"/x","upload_dir":"/y","canonical_c":9})"); +} + +struct WithCamelCase { + rfl::Alias<"download-dir", std::string> download_dir; + rfl::Alias<"max_peers", int> max_peers; +}; + +TEST(json, test_alias_with_snake_case_to_camel_case) { + // Primary wire names become downloadDir and maxPeers; aliases stay as written. + const auto from_alias = + rfl::json::read( + R"({"download-dir":"/dl","max_peers":50})"); + ASSERT_TRUE(from_alias) << from_alias.error().what(); + EXPECT_EQ(from_alias->download_dir, "/dl"); + EXPECT_EQ(from_alias->max_peers, 50); + + EXPECT_EQ(rfl::json::write(*from_alias), + R"({"downloadDir":"/dl","maxPeers":50})"); + + // Conflict between transformed primary name and alias is rejected. + const auto conflict = + rfl::json::read( + R"({"downloadDir":"/a","download-dir":"/b","maxPeers":1})"); + EXPECT_FALSE(conflict); +} + +struct WithDefaults { + rfl::Alias<"old-host", rfl::DefaultVal> host = + std::string("localhost"); + rfl::DefaultVal> port = 8080; + rfl::Alias<"old-name", std::string> name = "default-name"; +}; + +TEST(json, test_alias_with_default_val_and_default_if_missing) { + // Omitted DefaultVal fields keep defaults; present alias overrides. + const auto r1 = rfl::json::read( + R"({"old-name":"svc"})"); + ASSERT_TRUE(r1) << r1.error().what(); + EXPECT_EQ(r1->host.value().value(), "localhost"); + EXPECT_EQ(r1->port.value(), 8080); + EXPECT_EQ(r1->name, "svc"); + + // All supplied via aliases. + const auto r2 = rfl::json::read( + R"({"old-host":"127.0.0.1","old-port":9090,"old-name":"api"})"); + ASSERT_TRUE(r2) << r2.error().what(); + EXPECT_EQ(r2->host.value().value(), "127.0.0.1"); + EXPECT_EQ(r2->port.value(), 9090); + EXPECT_EQ(r2->name, "api"); + + // DefaultIfMissing with alias. + const auto r3 = + rfl::json::read( + R"({"old-port":3000})"); + ASSERT_TRUE(r3) << r3.error().what(); + EXPECT_EQ(r3->host.value().value(), "localhost"); + EXPECT_EQ(r3->port.value(), 3000); + EXPECT_EQ(r3->name, "default-name"); + + // Conflicting primary + alias is rejected in ViewReaderWithDefault too! + const auto conflict = rfl::json::read( + R"({"host":"a","old-host":"b","name":"x"})"); + EXPECT_FALSE(conflict); + + const auto conflict_dim = + rfl::json::read( + R"({"port":1,"old-port":2})"); + EXPECT_FALSE(conflict_dim); +} + +struct WithOptionals { + rfl::Alias<"old-a", std::optional> a; + std::optional> b; + rfl::Description<"Field C", rfl::Alias<"old-c", std::optional>> c; + rfl::Alias<"old-d", rfl::Deprecated<"Use d", "Field D", std::optional>> + d; +}; + +TEST(json, test_alias_with_optionals_description_deprecated) { + // All omitted -> writes empty object. + write_and_read(WithOptionals{}, R"({})"); + + // All provided via aliases. + const auto res = rfl::json::read( + R"({"old-a":"hi","old-b":2,"old-c":3,"old-d":4})"); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->a.value(), "hi"); + ASSERT_TRUE(res->b.has_value()); + EXPECT_EQ(*res->b, 2); + EXPECT_EQ(res->c.value().value(), 3); + EXPECT_EQ(res->d.value().value(), 4); + + EXPECT_EQ(rfl::json::write(*res), R"({"a":"hi","b":2,"c":3,"d":4})"); +} + +struct WithValidator { + rfl::Alias<"old-port", + rfl::Validator, rfl::Maximum<65535>>> + port; +}; + +TEST(json, test_alias_with_validator) { + const auto ok = rfl::json::read(R"({"old-port":443})"); + ASSERT_TRUE(ok) << ok.error().what(); + EXPECT_EQ(ok->port.value().value(), 443); + EXPECT_EQ(rfl::json::write(*ok), R"({"port":443})"); + + const auto bad = rfl::json::read(R"({"old-port":0})"); + EXPECT_FALSE(bad); +} + +struct WithExtraFields { + rfl::Alias<"old-id", int> id; + rfl::ExtraFields extra; +}; + +TEST(json, test_alias_with_extra_fields) { + const auto res = rfl::json::read( + R"({"old-id":7,"other":"kept"})"); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->id, 7); + EXPECT_EQ(res->extra.size(), 1u); + EXPECT_EQ(res->extra.get("other").value(), "kept"); +} + +struct SchemaStruct { + rfl::Description<"Download directory", + rfl::Alias<"download-dir", std::string>> + download_dir; + rfl::Alias<"old-port", rfl::DefaultVal> port = 8080; + rfl::Alias<"old-limit", rfl::Validator>> limit = 10; +}; + +TEST(json, test_alias_json_schema_canonical_only) { + const auto schema = rfl::json::to_schema(); + // Primary property names are emitted; legacy alias names are NOT emitted. + EXPECT_NE(schema.find(R"("download_dir")"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("port")"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("limit")"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("Download directory")"), std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("default":8080)"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("download-dir")"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("old-port")"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("old-limit")"), std::string::npos) << schema; +} + +struct NonDefaultType { + explicit NonDefaultType(int _v) : v(_v) {} + int v; +}; + +struct NonDefaultWrapperHolder { + rfl::Alias<"old_x", NonDefaultType> x; +}; + +TEST(json, test_alias_ergonomics_and_traits) { + static_assert(std::is_default_constructible_v>); + static_assert( + !std::is_default_constructible_v>); + + rfl::Alias<"old", std::string> a = "hello"; + EXPECT_EQ(a.value(), "hello"); + EXPECT_EQ(a.get(), "hello"); + EXPECT_EQ(*a, "hello"); + EXPECT_EQ(a(), "hello"); + EXPECT_EQ(a->size(), 5u); + + // Implicit conversion to underlying type. + const std::string copy = a; + EXPECT_EQ(copy, "hello"); + + // Comparison operators (==, !=, <=>). + rfl::Alias<"old", std::string> b = "world"; + EXPECT_TRUE(a == "hello"); + EXPECT_TRUE("hello" == a); + EXPECT_TRUE(a != b); + EXPECT_TRUE(a < b); + EXPECT_TRUE((a <=> b) < 0); + + // Chained alias ergonomics. + rfl::Alias<"kebab-case", rfl::Alias<"camelCase", std::string>> chained = + "value"; + EXPECT_EQ(chained, "value"); + + // std::hash specialization. + std::unordered_set> set; + set.insert(a); + set.insert(b); + EXPECT_EQ(set.size(), 2u); + EXPECT_TRUE(set.contains(rfl::Alias<"old", std::string>("hello"))); +} + +} // namespace test_alias diff --git a/tests/yaml/test_alias.cpp b/tests/yaml/test_alias.cpp new file mode 100644 index 000000000..5425450c3 --- /dev/null +++ b/tests/yaml/test_alias.cpp @@ -0,0 +1,43 @@ +#include + +#include +#include +#include + +namespace test_yaml_alias { + +struct Config { + rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>> + download_dir; + rfl::Alias<"max-peers", rfl::DefaultVal> max_peers = 50; +}; + +TEST(yaml, test_alias_read_write_and_conflicts) { + const std::string yaml_alias = + "download-dir: /data/downloads\nmax-peers: 120\n"; + const auto res = rfl::yaml::read(yaml_alias); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->download_dir, "/data/downloads"); + EXPECT_EQ(res->max_peers.value().value(), 120); + + // Writes canonical field names. + const auto written = rfl::yaml::write(*res); + EXPECT_NE(written.find("download_dir:"), std::string::npos) << written; + EXPECT_NE(written.find("max_peers:"), std::string::npos) << written; + EXPECT_EQ(written.find("download-dir:"), std::string::npos) << written; + EXPECT_EQ(written.find("max-peers:"), std::string::npos) << written; + + // Chained alias with default preserved. + const auto res2 = + rfl::yaml::read(std::string("downloadDir: /tmp\n")); + ASSERT_TRUE(res2) << res2.error().what(); + EXPECT_EQ(res2->download_dir, "/tmp"); + EXPECT_EQ(res2->max_peers.value().value(), 50); + + // Conflicting primary + alias rejected. + const auto conflict = rfl::yaml::read( + std::string("download_dir: /a\ndownload-dir: /b\n")); + EXPECT_FALSE(conflict); +} + +} // namespace test_yaml_alias From 025ec79966462fbeb27cccce3ba81b0bcdf8764f Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:15:25 +0100 Subject: [PATCH 2/4] Fix rfl::Alias review blockers (Skip/Validator/pointer unwrapping, scoped is_default_val, zero-alloc env, CLI conflict names, header cleanup) --- README.md | 1 + include/rfl/Alias.hpp | 76 +++++++++----------- include/rfl/cli/resolve_args.hpp | 14 +++- include/rfl/env/Reader.hpp | 19 +++-- include/rfl/internal/field_aliases.hpp | 29 ++++++++ include/rfl/internal/is_alias.hpp | 21 +++++- include/rfl/internal/is_default_val_v.hpp | 21 ------ include/rfl/internal/is_skip.hpp | 14 +++- include/rfl/parsing/ParserAlias.hpp | 13 +--- include/rfl/parsing/Parser_default.hpp | 7 +- include/rfl/parsing/is_empty.hpp | 10 +-- tests/cli/test_alias.cpp | 41 +++++++---- tests/env/test_alias.cpp | 85 +++++++++++++++++++++++ tests/json/test_alias.cpp | 44 ++++++++++++ 14 files changed, 287 insertions(+), 108 deletions(-) create mode 100644 tests/env/test_alias.cpp diff --git a/README.md b/README.md index 9cfdfa223..627fc4c7c 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile - Simple [installation](https://munich-data-engineering.github.io/reflect-cpp/install) - Simple extendability to [other serialization formats](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/supporting_your_own_format) - Simple extendability to [custom classes](https://munich-data-engineering.github.io/reflect-cpp/concepts/custom_classes) +- Read-only field aliases via [`rfl::Alias`](https://munich-data-engineering.github.io/reflect-cpp/alias) for backwards-compatible schema and config migration - Being one of the fastest serialization libraries in existence, as demonstrated by our [benchmarks](https://munich-data-engineering.github.io/reflect-cpp/benchmarks)
diff --git a/include/rfl/Alias.hpp b/include/rfl/Alias.hpp index 8e6028514..f7fbf67ac 100644 --- a/include/rfl/Alias.hpp +++ b/include/rfl/Alias.hpp @@ -10,6 +10,7 @@ #include "default.hpp" #include "internal/StringLiteral.hpp" +#include "internal/is_alias.hpp" namespace rfl { @@ -38,32 +39,34 @@ struct Alias { /// Default constructor - enabled only when Type is default-constructible. template requires std::is_default_constructible_v - Alias() noexcept(std::is_nothrow_default_constructible_v) : value_() {} + constexpr Alias() noexcept(std::is_nothrow_default_constructible_v) + : value_() {} /// Constructs from a const reference to the value. - Alias(const Type& _value) : value_(_value) {} + constexpr Alias(const Type& _value) : value_(_value) {} /// Constructs from an rvalue reference to the value. - Alias(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) + constexpr Alias(Type&& _value) noexcept( + std::is_nothrow_move_constructible_v) : value_(std::move(_value)) {} /// Move constructor. - Alias(Alias&& _field) noexcept = default; + constexpr Alias(Alias&& _field) = default; /// Copy constructor. - Alias(const Alias& _field) = default; + constexpr Alias(const Alias& _field) = default; /// Copy constructor from Alias with the same alias name and a compatible /// underlying type. template requires(!std::is_same_v && std::is_convertible_v) - Alias(const Alias<_name, U>& _field) : value_(_field.get()) {} + constexpr Alias(const Alias<_name, U>& _field) : value_(_field.get()) {} /// Move constructor from Alias with the same alias name and a compatible /// underlying type. template requires(!std::is_same_v && std::is_convertible_v) - Alias(Alias<_name, U>&& _field) noexcept( + constexpr Alias(Alias<_name, U>&& _field) noexcept( std::is_nothrow_constructible_v) : value_(std::move(_field.value_)) {} @@ -73,48 +76,50 @@ struct Alias { !std::is_same_v, Type> && !std::is_same_v, Default> && std::is_convertible_v) - Alias(U&& _value) noexcept(std::is_nothrow_constructible_v) + constexpr Alias(U&& _value) noexcept( + std::is_nothrow_constructible_v) : value_(std::forward(_value)) {} /// Initializes the underlying object to its default value using the Default /// sentinel. template requires std::is_default_constructible_v - Alias(const Default&) noexcept(std::is_nothrow_default_constructible_v) + constexpr Alias(const Default&) noexcept( + std::is_nothrow_default_constructible_v) : value_() {} /// Destructor. - ~Alias() = default; + constexpr ~Alias() = default; /// Returns a const reference to the underlying value. - const Type& get() const noexcept { return value_; } + constexpr const Type& get() const noexcept { return value_; } /// Returns a reference to the underlying value. - Type& get() noexcept { return value_; } + constexpr Type& get() noexcept { return value_; } /// Dereference operator - returns the underlying value. - Type& operator*() noexcept { return value_; } + constexpr Type& operator*() noexcept { return value_; } /// Dereference operator (const) - returns the underlying value. - const Type& operator*() const noexcept { return value_; } + constexpr const Type& operator*() const noexcept { return value_; } /// Function call operator - returns the underlying value. - Type& operator()() noexcept { return value_; } + constexpr Type& operator()() noexcept { return value_; } /// Function call operator (const) - returns the underlying value. - const Type& operator()() const noexcept { return value_; } + constexpr const Type& operator()() const noexcept { return value_; } /// Pointer to the underlying value. - Type* operator->() noexcept { return &value_; } + constexpr Type* operator->() noexcept { return &value_; } /// Pointer to the underlying value (const). - const Type* operator->() const noexcept { return &value_; } + constexpr const Type* operator->() const noexcept { return &value_; } /// Implicit conversion to a mutable reference to the underlying value. - operator Type&() noexcept { return value_; } + constexpr operator Type&() noexcept { return value_; } /// Implicit conversion to a const reference to the underlying value. - operator const Type&() const noexcept { return value_; } + constexpr operator const Type&() const noexcept { return value_; } /// Assigns a new value (copy). auto& operator=(const Type& _value) { @@ -152,7 +157,7 @@ struct Alias { Alias& operator=(const Alias& _field) = default; /// Move assignment operator. - Alias& operator=(Alias&& _field) noexcept = default; + Alias& operator=(Alias&& _field) = default; /// Assigns from another Alias with compatible underlying type (copy). template @@ -179,34 +184,21 @@ struct Alias { } /// Returns a reference to the underlying value. - Type& value() noexcept { return value_; } + constexpr Type& value() noexcept { return value_; } /// Returns a const reference to the underlying value. - const Type& value() const noexcept { return value_; } + constexpr const Type& value() const noexcept { return value_; } /// The underlying value. Type value_; }; -namespace internal { - -template -class is_alias : public std::false_type {}; - -template -class is_alias> : public std::true_type {}; - -template -constexpr bool is_alias_v = - is_alias>>::value; - -} // namespace internal - /// Equality comparison between two Alias wrappers. template requires requires(const T1& _a, const T2& _b) { _a == _b; } -inline bool operator==(const Alias<_n1, T1>& _lhs, const Alias<_n2, T2>& _rhs) { +constexpr bool operator==(const Alias<_n1, T1>& _lhs, + const Alias<_n2, T2>& _rhs) { return _lhs.value() == _rhs.value(); } @@ -214,8 +206,8 @@ inline bool operator==(const Alias<_n1, T1>& _lhs, const Alias<_n2, T2>& _rhs) { template requires requires(const T1& _a, const T2& _b) { _a <=> _b; } -inline auto operator<=>(const Alias<_n1, T1>& _lhs, - const Alias<_n2, T2>& _rhs) { +constexpr auto operator<=>(const Alias<_n1, T1>& _lhs, + const Alias<_n2, T2>& _rhs) { return _lhs.value() <=> _rhs.value(); } @@ -223,7 +215,7 @@ inline auto operator<=>(const Alias<_n1, T1>& _lhs, template requires(!internal::is_alias_v && requires(const T& _a, const U& _b) { _a == _b; }) -inline bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { +constexpr bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { return _lhs.value() == _rhs; } @@ -231,7 +223,7 @@ inline bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { template requires(!internal::is_alias_v && requires(const T& _a, const U& _b) { _a <=> _b; }) -inline auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) { +constexpr auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) { return _lhs.value() <=> _rhs; } diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 733f7cc02..585e1f9ec 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -88,15 +88,17 @@ inline rfl::Result> resolve_args( ParsedArgs _parsed, const Options& _options ) { std::map result; + std::map seen_flag; for (auto& [key, val] : _parsed.named) { const auto it = _options.long_aliases.find(key); const auto& target = it == _options.long_aliases.end() ? key : it->second; if (!result.emplace(target, std::move(val)).second) { return rfl::error( - "Conflict: '--" + key + "' and '--" + target + "Conflict: '--" + key + "' and '--" + seen_flag[target] + "' refer to the same field."); } + seen_flag.emplace(target, key); } // Merge positional args. @@ -108,8 +110,11 @@ inline rfl::Result> resolve_args( for (size_t i = 0; i < _parsed.positional.size(); ++i) { const auto& long_name = positional_names[i]; if (result.count(long_name)) { + const auto flag_it = seen_flag.find(long_name); + const auto& flag_name = + flag_it != seen_flag.end() ? flag_it->second : long_name; return rfl::error( - "Conflict: positional argument and '--" + long_name + "Conflict: positional argument and '--" + flag_name + "' both provided."); } result.emplace(long_name, std::move(_parsed.positional[i])); @@ -123,8 +128,11 @@ inline rfl::Result> resolve_args( } const auto& long_name = it->second; if (result.count(long_name)) { + const auto flag_it = seen_flag.find(long_name); + const auto& flag_name = + flag_it != seen_flag.end() ? flag_it->second : long_name; return rfl::error( - "Conflict: '-" + short_name + "' and '--" + long_name + "Conflict: '-" + short_name + "' and '--" + flag_name + "' both provided."); } result.emplace(long_name, std::move(value)); diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 865649c25..c98e00516 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -250,10 +249,20 @@ struct Reader { using Aliases = rfl::internal::field_aliases_t; if constexpr (Aliases::size > 0) { - std::set seen_aliases; - seen_aliases.insert(FieldType::name()); - for (const auto alias : Aliases::to_array()) { - if (!seen_aliases.insert(alias).second) { + constexpr auto aliases = Aliases::to_array(); + for (size_t idx = 0; idx < aliases.size(); ++idx) { + const auto alias = aliases[idx]; + if (alias == FieldType::name()) { + continue; + } + bool duplicate = false; + for (size_t prev = 0; prev < idx; ++prev) { + if (aliases[prev] == alias) { + duplicate = true; + break; + } + } + if (duplicate) { continue; } const std::string alias_str(alias); diff --git a/include/rfl/internal/field_aliases.hpp b/include/rfl/internal/field_aliases.hpp index 0ea794814..456878183 100644 --- a/include/rfl/internal/field_aliases.hpp +++ b/include/rfl/internal/field_aliases.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -10,15 +11,18 @@ #include "../Alias.hpp" #include "../Attribute.hpp" +#include "../Box.hpp" #include "../Commented.hpp" #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" #include "../Positional.hpp" +#include "../Ref.hpp" #include "../Rename.hpp" #include "../Short.hpp" #include "../Skip.hpp" #include "../Tuple.hpp" +#include "../Validator.hpp" #include "StringLiteral.hpp" namespace rfl::internal { @@ -113,6 +117,31 @@ struct field_aliases_impl> { using type = field_aliases_t; }; +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + +template +struct field_aliases_impl> { + using type = field_aliases_t; +}; + /// Returns true if any field in Fields declares at least one rfl::Alias. template consteval bool has_any_aliases() { diff --git a/include/rfl/internal/is_alias.hpp b/include/rfl/internal/is_alias.hpp index b0b688398..61283b886 100644 --- a/include/rfl/internal/is_alias.hpp +++ b/include/rfl/internal/is_alias.hpp @@ -3,10 +3,24 @@ #include -#include "../Alias.hpp" #include "StringLiteral.hpp" -namespace rfl::internal { +namespace rfl { + +template +struct Alias; + +namespace internal { + +template +class is_alias : public std::false_type {}; + +template +class is_alias> : public std::true_type {}; + +template +constexpr bool is_alias_v = + is_alias>>::value; template struct remove_alias { @@ -22,6 +36,7 @@ template using remove_alias_t = typename remove_alias>>::Type; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 5d039ce40..6405b1e11 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -6,11 +6,7 @@ #include "../Alias.hpp" #include "../DefaultVal.hpp" -#include "../Deprecated.hpp" -#include "../Description.hpp" -#include "../Positional.hpp" #include "../Rename.hpp" -#include "../Short.hpp" #include "StringLiteral.hpp" namespace rfl::internal { @@ -32,23 +28,6 @@ template class is_default_val> : public is_default_val> {}; -template -class is_default_val> - : public is_default_val> {}; - -template -class is_default_val> - : public is_default_val> {}; - -template -class is_default_val> - : public is_default_val> {}; - -template -class is_default_val> - : public is_default_val> {}; - template constexpr bool is_default_val_v = is_default_val>>::value; diff --git a/include/rfl/internal/is_skip.hpp b/include/rfl/internal/is_skip.hpp index d3357d0e5..0b45d6e7c 100644 --- a/include/rfl/internal/is_skip.hpp +++ b/include/rfl/internal/is_skip.hpp @@ -4,8 +4,14 @@ #include #include "Skip.hpp" +#include "StringLiteral.hpp" -namespace rfl::internal { +namespace rfl { + +template +struct Alias; + +namespace internal { template class is_skip; @@ -17,10 +23,14 @@ template class is_skip> : public std::true_type {}; +template +class is_skip> : public is_skip> {}; + template constexpr bool is_skip_v = is_skip>>::value; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/parsing/ParserAlias.hpp b/include/rfl/parsing/ParserAlias.hpp index 623bd9886..37886b385 100644 --- a/include/rfl/parsing/ParserAlias.hpp +++ b/include/rfl/parsing/ParserAlias.hpp @@ -9,23 +9,12 @@ #include "../Alias.hpp" #include "../Result.hpp" #include "../internal/StringLiteral.hpp" +#include "../internal/is_alias.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" namespace rfl::parsing { -template -struct is_alias : std::false_type {}; - -template -struct is_alias> : std::true_type { - using element_type = T; - static constexpr auto name = _name; -}; - -template -constexpr bool is_alias_v = is_alias>::value; - template struct ParserAlias; diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 3671f74da..d62d96045 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -15,6 +15,7 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" +#include "../internal/is_alias.hpp" #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" @@ -142,7 +143,7 @@ struct Parser { } else if constexpr (is_rename_v) { return ParserRename::read(_r, _var); - } else if constexpr (is_alias_v) { + } else if constexpr (internal::is_alias>::value) { return ParserAlias::read(_r, _var); } else if constexpr (is_result_v) { @@ -346,7 +347,7 @@ struct Parser { } else if constexpr (is_rename_v) { ParserRename::write(_w, _var, _parent); - } else if constexpr (is_alias_v) { + } else if constexpr (internal::is_alias>::value) { ParserAlias::write(_w, _var, _parent); } else if constexpr (is_duration_v) { @@ -517,7 +518,7 @@ struct Parser { } else if constexpr (is_rename_v) { return ParserRename::to_schema(_definitions); - } else if constexpr (is_alias_v) { + } else if constexpr (internal::is_alias>::value) { return ParserAlias::to_schema(_definitions); } else if constexpr (is_result_v) { diff --git a/include/rfl/parsing/is_empty.hpp b/include/rfl/parsing/is_empty.hpp index 1fa587633..eee4b630c 100644 --- a/include/rfl/parsing/is_empty.hpp +++ b/include/rfl/parsing/is_empty.hpp @@ -28,6 +28,11 @@ static bool is_empty(const T& _var) { using Type = std::remove_cvref_t; if constexpr (std::is_pointer_v) { return !_var || is_empty(*_var); + } else if constexpr (internal::is_rename_v || + internal::is_short_v || + internal::is_positional_v || + internal::is_alias_v) { + return is_empty(_var.value()); } else if constexpr (internal::is_skip_v) { return Type::skip_serialization_; } else if constexpr (internal::has_reflection_type_v) { @@ -37,11 +42,6 @@ static bool is_empty(const T& _var) { const auto& [r] = _var; return is_empty(r); } - } else if constexpr (internal::is_rename_v || - internal::is_short_v || - internal::is_positional_v || - internal::is_alias_v) { - return is_empty(_var.value()); } else if constexpr (is_map_like_v || is_vector_like_v) { return _var.begin() == _var.end(); } else { diff --git a/tests/cli/test_alias.cpp b/tests/cli/test_alias.cpp index 9166fd568..4bd49b0b2 100644 --- a/tests/cli/test_alias.cpp +++ b/tests/cli/test_alias.cpp @@ -11,7 +11,7 @@ namespace test_cli_alias { struct ServerConfig { rfl::Alias<"download_dir", rfl::Alias<"downloadDir", std::string>> download_dir; - rfl::Short<"v", rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; + rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; rfl::Alias<"listen-port", rfl::DefaultVal> port = 8080; rfl::Positional>> input; }; @@ -45,29 +45,46 @@ TEST(cli, test_alias_basic_and_no_extra_fields) { } TEST(cli, test_alias_conflicts_rejected) { - // Primary + alias conflict. + // Primary + alias conflict names both flags actually passed. const auto c1 = rfl::cli::read( {"--download-dir=/a", "--download_dir=/b"}); - EXPECT_FALSE(c1); - - // Two aliases of the same field conflict. + ASSERT_FALSE(c1); + EXPECT_NE(c1.error().what().find("--download-dir"), std::string::npos) + << c1.error().what(); + EXPECT_NE(c1.error().what().find("--download_dir"), std::string::npos) + << c1.error().what(); + + // Two aliases of the same field conflict and name the two aliases passed + // (NOT the canonical flag --download-dir). const auto c2 = rfl::cli::read( {"--download_dir=/a", "--downloadDir=/b"}); - EXPECT_FALSE(c2); - - // Short flag + alias conflict. + ASSERT_FALSE(c2); + EXPECT_NE(c2.error().what().find("--download_dir"), std::string::npos) + << c2.error().what(); + EXPECT_NE(c2.error().what().find("--downloadDir"), std::string::npos) + << c2.error().what(); + EXPECT_EQ(c2.error().what().find("--download-dir"), std::string::npos) + << c2.error().what(); + + // Short flag + alias conflict names the alias passed. const auto c3 = rfl::cli::read( {"--download-dir=/a", "-v", "--debug"}); - EXPECT_FALSE(c3); + ASSERT_FALSE(c3); + EXPECT_NE(c3.error().what().find("-v"), std::string::npos) + << c3.error().what(); + EXPECT_NE(c3.error().what().find("--debug"), std::string::npos) + << c3.error().what(); - // Positional + alias conflict. + // Positional + alias conflict names the alias passed. const auto c4 = rfl::cli::read( {"--download-dir=/a", "pos.txt", "--src=other.txt"}); - EXPECT_FALSE(c4); + ASSERT_FALSE(c4); + EXPECT_NE(c4.error().what().find("--src"), std::string::npos) + << c4.error().what(); } struct AliasWrappingShortAndPositional { - rfl::Alias<"old-flag", rfl::Short<"f", rfl::DefaultVal>> flag = false; + rfl::Alias<"old-flag", rfl::DefaultVal>> flag = false; rfl::Alias<"old-file", rfl::Positional> file; }; diff --git a/tests/env/test_alias.cpp b/tests/env/test_alias.cpp new file mode 100644 index 000000000..18349fe58 --- /dev/null +++ b/tests/env/test_alias.cpp @@ -0,0 +1,85 @@ +#include + +#include +#include +#include +#include + +namespace test_env_alias { + +static void set_env_var(const char* _k, const char* _v) { +#ifdef _WIN32 + _putenv_s(_k, _v); +#else + setenv(_k, _v, 1); +#endif +} + +static void unset_env_var(const char* _k) { +#ifdef _WIN32 + _putenv_s(_k, ""); +#else + unsetenv(_k); +#endif +} + +struct EnvGuard { + const char* key; + ~EnvGuard() { unset_env_var(key); } +}; + +struct Config { + rfl::Alias<"OLD_HOST", rfl::Alias<"LEGACY_HOST", std::string>> host; + rfl::Alias<"OLD_PORT", rfl::Alias<"OLD_PORT", int>> port; +}; + +TEST(env, test_alias_read_and_conflicts) { + EnvGuard g1{"HOST"}, g2{"OLD_HOST"}, g3{"LEGACY_HOST"}; + EnvGuard g4{"PORT"}, g5{"OLD_PORT"}; + unset_env_var("HOST"); + unset_env_var("OLD_HOST"); + unset_env_var("LEGACY_HOST"); + unset_env_var("PORT"); + unset_env_var("OLD_PORT"); + + // 1. Read via aliases (including duplicate alias declaration on `port`). + set_env_var("OLD_HOST", "alias-host"); + set_env_var("OLD_PORT", "9090"); + const auto res1 = rfl::env::read(); + ASSERT_TRUE(res1) << res1.error().what(); + EXPECT_EQ(res1->host, "alias-host"); + EXPECT_EQ(res1->port, 9090); + + // 2. Second chained alias works. + unset_env_var("OLD_HOST"); + set_env_var("LEGACY_HOST", "legacy-host"); + const auto res2 = rfl::env::read(); + ASSERT_TRUE(res2) << res2.error().what(); + EXPECT_EQ(res2->host, "legacy-host"); + + // 3. Conflicting primary + alias is rejected. + set_env_var("HOST", "primary-host"); + const auto conflict = rfl::env::read(); + EXPECT_FALSE(conflict.has_value()); +} + +struct NestedConfig { + Config myapp; +}; + +TEST(env, test_alias_with_nested_prefix) { + EnvGuard g1{"MYAPP_HOST"}, g2{"MYAPP_OLD_HOST"}, g3{"MYAPP_OLD_PORT"}; + unset_env_var("MYAPP_HOST"); + unset_env_var("MYAPP_OLD_HOST"); + unset_env_var("MYAPP_OLD_PORT"); + + set_env_var("MYAPP_OLD_HOST", "prefixed-host"); + set_env_var("MYAPP_OLD_PORT", "7000"); + + const auto res = rfl::env::read(); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->myapp.host, "prefixed-host"); + EXPECT_EQ(res->myapp.port, 7000); +} + +} // namespace test_env_alias diff --git a/tests/json/test_alias.cpp b/tests/json/test_alias.cpp index 3d31060e5..1eed02866 100644 --- a/tests/json/test_alias.cpp +++ b/tests/json/test_alias.cpp @@ -303,4 +303,48 @@ TEST(json, test_alias_ergonomics_and_traits) { EXPECT_TRUE(set.contains(rfl::Alias<"old", std::string>("hello"))); } +struct WithSkipAndAlias { + int visible = 1; + rfl::Alias<"old_skip", rfl::Skip> skipped_inner = 99; + rfl::Skip> skipped_outer = 100; +}; + +struct WithValidatorAndPointerWrappers { + rfl::Validator, rfl::Minimum<1>> val; + rfl::Box> boxed; + rfl::Ref> refed; + std::unique_ptr> uptr; + std::shared_ptr> sptr; +}; + +TEST(json, test_alias_with_skip_validator_and_pointer_wrappers) { + // Alias wrapping Skip must NOT leak into JSON output or JSON Schema. + const WithSkipAndAlias ws; + EXPECT_EQ(rfl::json::write(ws), R"({"visible":1})"); + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("visible")"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("skipped_inner")"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("skipped_outer")"), std::string::npos) << schema; + EXPECT_EQ(schema.find(R"("old_skip")"), std::string::npos) << schema; + + // Aliases inside Validator, Box, Ref, unique_ptr, shared_ptr must work. + const auto parsed = + rfl::json::read( + R"({"old_v":5,"old_box":10,"old_ref":20,"old_uptr":30,"old_sptr":40})"); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->val.value().value(), 5); + EXPECT_EQ(parsed->boxed->value(), 10); + EXPECT_EQ(parsed->refed->value(), 20); + ASSERT_NE(parsed->uptr, nullptr); + EXPECT_EQ(parsed->uptr->value(), 30); + ASSERT_NE(parsed->sptr, nullptr); + EXPECT_EQ(parsed->sptr->value(), 40); + + // Validator constraint still enforced when supplied via inner alias. + EXPECT_FALSE( + (rfl::json::read( + R"({"old_v":0,"old_box":10,"old_ref":20,"old_uptr":30,"old_sptr":40})")) + .has_value()); +} + } // namespace test_alias From 91e5bf1b8781e86203f8cae068464b8cd98878d4 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:29:05 +0100 Subject: [PATCH 3/4] Remove explicit constexpr on defaulted Alias special members and fix CLI doc example --- docs/content/alias.md | 2 +- include/rfl/Alias.hpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/content/alias.md b/docs/content/alias.md index 035a22947..1ab67bfca 100644 --- a/docs/content/alias.md +++ b/docs/content/alias.md @@ -67,7 +67,7 @@ struct Config { struct CliConfig { rfl::Alias<"download_dir", rfl::Alias<"downloadDir", std::string>> download_dir; - rfl::Short<"v", rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; + rfl::Alias<"debug", rfl::DefaultVal>> verbose = false; }; // Accepts --download-dir=/dl, --download_dir=/dl, or --downloadDir=/dl diff --git a/include/rfl/Alias.hpp b/include/rfl/Alias.hpp index f7fbf67ac..eb0dc6704 100644 --- a/include/rfl/Alias.hpp +++ b/include/rfl/Alias.hpp @@ -51,10 +51,10 @@ struct Alias { : value_(std::move(_value)) {} /// Move constructor. - constexpr Alias(Alias&& _field) = default; + Alias(Alias&& _field) = default; /// Copy constructor. - constexpr Alias(const Alias& _field) = default; + Alias(const Alias& _field) = default; /// Copy constructor from Alias with the same alias name and a compatible /// underlying type. @@ -89,7 +89,7 @@ struct Alias { : value_() {} /// Destructor. - constexpr ~Alias() = default; + ~Alias() = default; /// Returns a const reference to the underlying value. constexpr const Type& get() const noexcept { return value_; } From 7df687d0ed14b27156a0eb80db93cf8432f4268c Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 21:47:39 +0100 Subject: [PATCH 4/4] Fix raw-pointer Alias write/read handling and CLI resolve_args fast path --- include/rfl/Alias.hpp | 4 +- include/rfl/cli/resolve_args.hpp | 27 +++++++---- include/rfl/internal/field_aliases.hpp | 8 +++- include/rfl/parsing/ParserAlias.hpp | 1 - include/rfl/parsing/Parser_default.hpp | 6 ++- include/rfl/parsing/is_required.hpp | 4 +- tests/json/test_alias.cpp | 64 ++++++++++++++++++++++++++ 7 files changed, 98 insertions(+), 16 deletions(-) diff --git a/include/rfl/Alias.hpp b/include/rfl/Alias.hpp index eb0dc6704..cf7144a29 100644 --- a/include/rfl/Alias.hpp +++ b/include/rfl/Alias.hpp @@ -213,7 +213,7 @@ constexpr auto operator<=>(const Alias<_n1, T1>& _lhs, /// Equality comparison between an Alias wrapper and a non-Alias value. template - requires(!internal::is_alias_v && + requires(!internal::is_alias>::value && requires(const T& _a, const U& _b) { _a == _b; }) constexpr bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { return _lhs.value() == _rhs; @@ -221,7 +221,7 @@ constexpr bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) { /// Three-way comparison between an Alias wrapper and a non-Alias value. template - requires(!internal::is_alias_v && + requires(!internal::is_alias>::value && requires(const T& _a, const U& _b) { _a <=> _b; }) constexpr auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) { return _lhs.value() <=> _rhs; diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 585e1f9ec..fd7433074 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -89,16 +89,25 @@ inline rfl::Result> resolve_args( ) { std::map result; std::map seen_flag; - for (auto& [key, val] : _parsed.named) { - const auto it = _options.long_aliases.find(key); - const auto& target = - it == _options.long_aliases.end() ? key : it->second; - if (!result.emplace(target, std::move(val)).second) { - return rfl::error( - "Conflict: '--" + key + "' and '--" + seen_flag[target] - + "' refer to the same field."); + if (_options.long_aliases.empty()) { + result = std::move(_parsed.named); + } else { + for (auto& [key, val] : _parsed.named) { + const auto it = _options.long_aliases.find(key); + const auto& target = + it == _options.long_aliases.end() ? key : it->second; + if (!result.emplace(target, std::move(val)).second) { + const auto seen_it = seen_flag.find(target); + const auto& prev = + seen_it != seen_flag.end() ? seen_it->second : target; + return rfl::error( + "Conflict: '--" + key + "' and '--" + prev + + "' refer to the same field."); + } + if (key != target) { + seen_flag.emplace(target, key); + } } - seen_flag.emplace(target, key); } // Merge positional args. diff --git a/include/rfl/internal/field_aliases.hpp b/include/rfl/internal/field_aliases.hpp index 456878183..a3037234f 100644 --- a/include/rfl/internal/field_aliases.hpp +++ b/include/rfl/internal/field_aliases.hpp @@ -52,7 +52,8 @@ struct prepend_alias<_head, AliasList<_tail...>> { /// Collects all rfl::Alias names declared on a field type, unwrapping through /// transparent field wrappers (Alias, Rename, Description, Deprecated, -/// DefaultVal, Short, Positional, std::optional, Skip, Attribute, Commented). +/// DefaultVal, Short, Positional, std::optional, Skip, Attribute, Commented, +/// Validator, Box, Ref, std::unique_ptr, std::shared_ptr, and raw pointers). template struct field_aliases_impl { using type = AliasList<>; @@ -62,6 +63,11 @@ template using field_aliases_t = typename field_aliases_impl< std::remove_cvref_t>>::type; +template +struct field_aliases_impl { + using type = field_aliases_t; +}; + template struct field_aliases_impl> { using type = typename prepend_alias<_name, field_aliases_t>::type; diff --git a/include/rfl/parsing/ParserAlias.hpp b/include/rfl/parsing/ParserAlias.hpp index 37886b385..c4de5a235 100644 --- a/include/rfl/parsing/ParserAlias.hpp +++ b/include/rfl/parsing/ParserAlias.hpp @@ -9,7 +9,6 @@ #include "../Alias.hpp" #include "../Result.hpp" #include "../internal/StringLiteral.hpp" -#include "../internal/is_alias.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index d62d96045..ac25f95b0 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -144,7 +144,8 @@ struct Parser { return ParserRename::read(_r, _var); } else if constexpr (internal::is_alias>::value) { - return ParserAlias::read(_r, _var); + return ParserAlias, ProcessorsType>::read( + _r, _var); } else if constexpr (is_result_v) { return ParserResult::read(_r, _var); @@ -348,7 +349,8 @@ struct Parser { ParserRename::write(_w, _var, _parent); } else if constexpr (internal::is_alias>::value) { - ParserAlias::write(_w, _var, _parent); + ParserAlias, ProcessorsType>::write( + _w, _var, _parent); } else if constexpr (is_duration_v) { using U = std::remove_cvref_t; diff --git a/include/rfl/parsing/is_required.hpp b/include/rfl/parsing/is_required.hpp index 633e0f88f..aedf3aa28 100644 --- a/include/rfl/parsing/is_required.hpp +++ b/include/rfl/parsing/is_required.hpp @@ -54,7 +54,9 @@ constexpr bool is_never_required_v = is_never_required::value; template consteval bool is_required() { using Type = std::remove_cvref_t>; - if constexpr (internal::has_reflection_type_v && + if constexpr (std::is_pointer_v) { + return is_required(); + } else if constexpr (internal::has_reflection_type_v && !std::is_same_v) { return is_required(); diff --git a/tests/json/test_alias.cpp b/tests/json/test_alias.cpp index 1eed02866..1a1e40da1 100644 --- a/tests/json/test_alias.cpp +++ b/tests/json/test_alias.cpp @@ -347,4 +347,68 @@ TEST(json, test_alias_with_skip_validator_and_pointer_wrappers) { .has_value()); } +struct WithRawPointerAlias { + rfl::Alias<"old_outer", int*> outer_ptr = nullptr; + rfl::Alias<"old_inner", int>* inner_ptr = nullptr; +}; + +struct FlattenedAliasedInner { + rfl::Alias<"legacy_port", int> port = 80; +}; + +struct FlattenedAliasedOuter { + std::string host; + rfl::Flatten inner; +}; + +struct SkipSerializationAlias { + std::string name; + rfl::SkipSerialization> secret; + rfl::Alias<"old_token", rfl::SkipSerialization> token; +}; + +TEST(json, test_alias_raw_pointers_flatten_and_skip_serialization) { + // Raw pointers: both Alias<"old", int*> and Alias<"old", int>* under + // AllowRawPtrs must compile and support read (by alias and canonical), + // conflict rejection, and write. + int a = 11; + rfl::Alias<"old_inner", int> b = 22; + const WithRawPointerAlias to_write{.outer_ptr = &a, .inner_ptr = &b}; + EXPECT_EQ((rfl::json::write(to_write)), + R"({"outer_ptr":11,"inner_ptr":22})"); + + const auto read_null = + rfl::json::read( + R"({"old_outer":null,"old_inner":null})"); + ASSERT_TRUE(read_null) << read_null.error().what(); + EXPECT_EQ(read_null->outer_ptr.value(), nullptr); + EXPECT_EQ(read_null->inner_ptr, nullptr); + + // Conflict between canonical and alias on raw pointer field is detected. + EXPECT_FALSE( + (rfl::json::read( + R"({"inner_ptr":null,"old_inner":null})")) + .has_value()); + + // Flatten preserves aliases on inner struct fields. + const auto flat = rfl::json::read( + R"({"host":"localhost","legacy_port":8443})"); + ASSERT_TRUE(flat) << flat.error().what(); + EXPECT_EQ(flat->host, "localhost"); + EXPECT_EQ(flat->inner.get().port.value(), 8443); + EXPECT_EQ(rfl::json::write(*flat), R"({"host":"localhost","port":8443})"); + + // SkipSerialization + Alias (both orders): aliases populate on read, omitted + // on write. + const auto skipped = + rfl::json::read( + R"({"name":"svc","old_secret":"s1","old_token":"t1"})"); + ASSERT_TRUE(skipped) << skipped.error().what(); + EXPECT_EQ(skipped->name, "svc"); + EXPECT_EQ(skipped->secret.value().value(), "s1"); + EXPECT_EQ(skipped->token.value().value(), "t1"); + EXPECT_EQ(rfl::json::write(*skipped), R"({"name":"svc"})"); +} + } // namespace test_alias