diff --git a/docs/content/enums.md b/docs/content/enums.md index 5ab5561af..b118b5005 100644 --- a/docs/content/enums.md +++ b/docs/content/enums.md @@ -215,3 +215,26 @@ constexpr auto enumerator_array = rfl::get_enumerator_array(); In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also `rfl::get_underlying_enumerators()` and `rfl::get_underlying_enumerator_array()`. + +## Custom wire names (`rfl::EnumNames` and `rfl::TransformEnumNames`) + +To customize serialized enum wire names across JSON, CLI, Generic, XML, YAML, and JSON Schema without duplicating enumerators as `rfl::Literal<...>`, specialize `rfl::EnumNames` and/or pass a `rfl::TransformEnumNames<...>` processor (`rfl::EnumSnakeCaseToKebabCase`, `rfl::EnumSnakeCaseToCamelCase`, `rfl::EnumSnakeCaseToPascalCase`, `rfl::EnumToLowerCase`, `rfl::EnumToUpperCase`): + +```cpp +enum class OptimizationLevel { no_opt, size_opt, speed_opt, cxx_standard }; + +template <> +struct rfl::EnumNames { + static constexpr rfl::EnumNameTransform transform = + rfl::EnumNameTransform::snake_to_kebab; + static constexpr std::array, 1> + overrides = {{ + {OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; +``` + +- `overrides` (either a static contiguous range or a static `overrides()` returning a borrowed contiguous range such as `std::span>`) takes precedence over `transform`, and also supports enumerators outside the default reflected range. +- `transform` can be either a `rfl::EnumNameTransform` constant or a static callable `transform(std::string_view)` returning `std::string` or `std::string_view`. +- If `rfl::EnumNames` only defines `overrides` (without `transform`), non-overridden enumerators still receive any `rfl::TransformEnumNames<...>` processor passed to `read`, `write`, or `to_schema`. +- Use `rfl::get_enum_wire_names()` to inspect resolved `(wire_name, enumerator)` pairs, and `rfl::literal_from_table_t` to derive an `rfl::Literal<...>` type directly from a non-empty `constexpr` string table. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..5d252cbc1 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -40,6 +40,11 @@ reflect-cpp currently supports the following processors: - `rfl::DefaultIfMissing` - `rfl::DurationsAsCount` - `rfl::EnumNamesOnly` +- `rfl::EnumSnakeCaseToCamelCase` +- `rfl::EnumSnakeCaseToKebabCase` +- `rfl::EnumSnakeCaseToPascalCase` +- `rfl::EnumToLowerCase` +- `rfl::EnumToUpperCase` - `rfl::FailFast` - `rfl::NoExtraFields` - `rfl::NoFieldNames` diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..1efd3b871 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -23,6 +23,7 @@ #include "rfl/DefaultVal.hpp" #include "rfl/Description.hpp" #include "rfl/DurationsAsCount.hpp" +#include "rfl/EnumNames.hpp" #include "rfl/EnumNamesOnly.hpp" #include "rfl/ExtraFields.hpp" #include "rfl/FailFast.hpp" diff --git a/include/rfl/EnumNames.hpp b/include/rfl/EnumNames.hpp new file mode 100644 index 000000000..931d423c3 --- /dev/null +++ b/include/rfl/EnumNames.hpp @@ -0,0 +1,321 @@ +#ifndef RFL_ENUMNAMES_HPP_ +#define RFL_ENUMNAMES_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Literal.hpp" +#include "Processors.hpp" +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Built-in wire-name transforms applicable to C++ enum enumerator names via +/// `rfl::EnumNames::transform` or `rfl::TransformEnumNames<...>` processors. +enum class EnumNameTransform : uint8_t { + none = 0, + snake_to_kebab, + snake_to_camel, + snake_to_pascal, + to_lower, + to_upper, +}; + +namespace internal { + +constexpr char ascii_to_upper(const char _ch) noexcept { + return (_ch >= 'a' && _ch <= 'z') ? static_cast(_ch - ('a' - 'A')) : _ch; +} + +constexpr char ascii_to_lower(const char _ch) noexcept { + return (_ch >= 'A' && _ch <= 'Z') ? static_cast(_ch + ('a' - 'A')) : _ch; +} + +} // namespace internal + +/// Applies a built-in ASCII `EnumNameTransform` to an enumerator identifier. +inline std::string apply_enum_name_transform( + const std::string_view _name, const EnumNameTransform _transform) { + switch (_transform) { + case EnumNameTransform::none: + return std::string(_name); + case EnumNameTransform::snake_to_kebab: { + std::string out(_name); + for (char& ch : out) { + if (ch == '_') ch = '-'; + } + return out; + } + case EnumNameTransform::snake_to_camel: { + std::string out; + out.reserve(_name.size()); + bool cap_next = false; + for (const char ch : _name) { + if (ch == '_') { + if (!out.empty()) { + cap_next = true; + } + } else if (out.empty()) { + out.push_back(internal::ascii_to_lower(ch)); + } else if (cap_next) { + out.push_back(internal::ascii_to_upper(ch)); + cap_next = false; + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::snake_to_pascal: { + std::string out; + out.reserve(_name.size()); + bool cap_next = true; + for (const char ch : _name) { + if (ch == '_') { + cap_next = true; + } else if (cap_next) { + out.push_back(internal::ascii_to_upper(ch)); + cap_next = false; + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::to_lower: { + std::string out; + out.reserve(_name.size()); + for (const char ch : _name) { + out.push_back(internal::ascii_to_lower(ch)); + } + return out; + } + case EnumNameTransform::to_upper: { + std::string out; + out.reserve(_name.size()); + for (const char ch : _name) { + out.push_back(internal::ascii_to_upper(ch)); + } + return out; + } + } + return std::string(_name); +} + +/// Pair of `(enumerator, wire_name)` for per-enumerator overrides in +/// `rfl::EnumNames`. +template +using EnumOverride = std::pair; + +/// Specialize `rfl::EnumNames` to customize wire names for enum `E` across +/// JSON, CLI, Generic, nlohmann, YAML, XML, and JSON Schema without duplicating +/// enumerators as `rfl::Literal<...>`. +/// +/// Supported members (individually or combined; `overrides` takes precedence): +/// - `static constexpr EnumNameTransform transform = EnumNameTransform::snake_to_kebab;` +/// OR `static std::string transform(std::string_view _raw_name);` +/// (any return type convertible or explicitly constructible into `std::string`, +/// such as `std::string_view`, is accepted) +/// - `static constexpr std::array, N> overrides = {{ ... }};` +/// OR `static std::span> overrides();` +template +struct EnumNames {}; + +/// Processor that applies a whole-enum wire-name transform to all enums without +/// an explicit `rfl::EnumNames::transform`. If `rfl::EnumNames` only +/// defines `overrides`, non-overridden enumerators still receive this processor +/// transform. +template +struct TransformEnumNames { + static constexpr EnumNameTransform value = _transform; + + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +using EnumSnakeCaseToKebabCase = + TransformEnumNames; +using EnumSnakeCaseToCamelCase = + TransformEnumNames; +using EnumSnakeCaseToPascalCase = + TransformEnumNames; +using EnumToLowerCase = TransformEnumNames; +using EnumToUpperCase = TransformEnumNames; + +namespace internal { + +template +consteval auto string_literal_from_table_entry() { + constexpr std::string_view sv = std::string_view(_table[_i]); + return StringLiteral(sv); +} + +} // namespace internal + +/// Derives an `rfl::Literal<...>` type directly from a `constexpr` table +/// (`std::array`, `std::array`, or +/// `constexpr std::string_view kOps[] = { ... }`) so wire-string tables never +/// need to be duplicated as `rfl::Literal<"...">`. +/// +/// Example: +/// inline constexpr std::array kModes = { +/// "fast", "balanced", "max-compression"}; +/// using ModeLiteral = rfl::literal_from_table_t; +template > +struct literal_from_table; + +template +struct literal_from_table<_table, std::index_sequence<_is...>> { + static_assert(std::size(_table) > 0, + "rfl::literal_from_table_t requires a non-empty table."); + using type = Literal()...>; +}; + +template +using literal_from_table_t = typename literal_from_table<_table>::type; + +namespace internal { + +template +struct enum_name_transform_from_processors { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = _t; +}; + +template <> +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform head_val = + enum_name_transform_from_processors>::value; + static constexpr EnumNameTransform tail_val = + enum_name_transform_from_processors>::value; + static_assert(head_val == EnumNameTransform::none || + tail_val == EnumNameTransform::none || + head_val == tail_val, + "Conflicting rfl::TransformEnumNames processors cannot be " + "combined."); + static constexpr EnumNameTransform value = + head_val != EnumNameTransform::none ? head_val : tail_val; +}; + +template +constexpr EnumNameTransform enum_name_transform_v = + enum_name_transform_from_processors< + std::remove_cvref_t>::value; + +template +concept HasEnumOverridesVar = requires { + { EnumNames::overrides } -> std::ranges::contiguous_range; + requires std::same_as::overrides)>>, + EnumOverride>; +}; + +template +concept HasAnyEnumOverridesFn = requires { + { EnumNames::overrides() } -> std::ranges::contiguous_range; + requires std::same_as::overrides())>>, + EnumOverride>; +}; + +template +concept HasEnumOverridesFn = + HasAnyEnumOverridesFn && + std::ranges::borrowed_range::overrides())>; + +template +concept HasEnumTransformConst = requires { + { EnumNames::transform } -> std::convertible_to; +}; + +template +concept HasEnumTransformFn = requires(std::string_view _s) { + requires std::constructible_from::transform(_s))>; +}; + +template +constexpr bool has_custom_enum_names_for_transform_v = + HasEnumOverridesVar> || + HasAnyEnumOverridesFn> || + HasEnumTransformConst> || + HasEnumTransformFn> || + (_transform != EnumNameTransform::none); + +template > +constexpr bool has_custom_enum_names_v = + has_custom_enum_names_for_transform_v< + E, enum_name_transform_v>; + +template +inline std::span>> +get_enum_overrides() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyEnumOverridesFn || HasEnumOverridesFn, + "rfl::EnumNames::overrides() must return a borrowed contiguous range " + "(for example, std::span> or const auto&)."); + if constexpr (HasEnumOverridesFn) { + auto&& r = EnumNames::overrides(); + return std::span>(std::ranges::data(r), + std::ranges::size(r)); + } else if constexpr (HasEnumOverridesVar) { + return std::span>( + std::ranges::data(EnumNames::overrides), + std::ranges::size(EnumNames::overrides)); + } else { + return {}; + } +} + +template +inline std::string resolve_enum_wire_name_for_transform( + const E _val, const std::string_view _raw_name) { + using U = std::remove_cvref_t; + for (const auto& [e, wire] : get_enum_overrides()) { + if (e == _val) { + return std::string(wire); + } + } + if constexpr (HasEnumTransformFn) { + return std::string(EnumNames::transform(_raw_name)); + } else if constexpr (HasEnumTransformConst) { + return apply_enum_name_transform(_raw_name, EnumNames::transform); + } else if constexpr (_transform != EnumNameTransform::none) { + return apply_enum_name_transform(_raw_name, _transform); + } else { + return std::string(_raw_name); + } +} + +template > +inline std::string resolve_enum_wire_name(const E _val, + const std::string_view _raw_name) { + return resolve_enum_wire_name_for_transform< + E, enum_name_transform_v>(_val, _raw_name); +} + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..49a5b65be 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -1,9 +1,13 @@ #ifndef RFL_ENUMS_HPP_ #define RFL_ENUMS_HPP_ +#include #include #include +#include +#include +#include "EnumNames.hpp" #include "Result.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" @@ -52,9 +56,32 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// Converts an enum value to tis string representation. -template -std::string enum_to_string(const EnumType _enum) { +namespace internal { + +// Normalized implementations keyed only by EnumNameTransform so unrelated +// ProcessorsType packs share a single template instantiation per enum. + +template +std::string enum_to_string_with_transform(const EnumType _enum) { + const auto one_to_wire = [](const EnumType _e) -> std::string { + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [raw_name, val] : get_enumerator_array()) { + if (val == _e) { + return resolve_enum_wire_name_for_transform( + val, raw_name); + } + } + // Also check explicit overrides even for enumerators outside magic range. + for (const auto& [val, wire] : get_enum_overrides()) { + if (val == _e) { + return std::string(wire); + } + } + return std::to_string(static_cast>(_e)); + } else { + return internal::enums::to_string(_e); + } + }; if constexpr (internal::enums::is_flag_enum) { // Iterates through the enum bit by bit and matches it against the flags. using T = std::underlying_type_t; @@ -64,41 +91,89 @@ std::string enum_to_string(const EnumType _enum) { while (val != 0) { const auto bit = val & static_cast(1); if (bit == 1) { - auto str = internal::enums::to_string( - static_cast(static_cast(1) << i)); - flags.emplace_back(std::move(str)); + flags.emplace_back( + one_to_wire(static_cast(static_cast(1) << i))); } ++i; val >>= 1; } if (flags.empty()) { - return internal::enums::to_string(static_cast(0)); + return one_to_wire(static_cast(0)); } return internal::strings::join("|", flags); } else { - return internal::enums::to_string(_enum); + return one_to_wire(_enum); } } -// Converts a string to a value of the given enum type. -// -// By default, numeric values are accepted in addition to the declared -// enumerator names, even when they do not correspond to a declared -// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 -// will produce the cast value 4). Pass enum_names_only = true (or use the -// EnumNamesOnly processor with a parser) to accept only the declared -// enumerator names instead. -template -Result string_to_enum(const std::string& _str) { +template +std::vector> +get_enum_wire_names_with_transform() { + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back( + resolve_enum_wire_name_for_transform(val, + raw_name), + val); + } + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [val, wire] : get_enum_overrides()) { + bool already_present = false; + for (const auto& [_w, existing_val] : out) { + if (existing_val == val) { + already_present = true; + break; + } + } + if (!already_present) { + out.emplace_back(std::string(wire), val); + } + } + } + return out; +} + +template +std::vector> +get_unique_enum_wire_names_with_transform() { + std::vector> unique; + for (auto& entry : get_enum_wire_names_with_transform()) { + bool dup = false; + for (const auto& existing : unique) { + if (existing.first == entry.first) { + dup = true; + break; + } + } + if (!dup) { + unique.emplace_back(std::move(entry)); + } + } + return unique; +} + +template +Result string_to_enum_with_transform(const std::string& _str) { const auto make_error_msg = [&](const auto& name) { std::string msg = "Invalid enum value: '"; msg += name; msg += "'. Must be one of ["; const char* sep = ""; - for (const auto& p : get_enumerator_array()) { - msg += sep; - msg += p.first; - sep = ", "; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, _v] : + get_unique_enum_wire_names_with_transform()) { + msg += sep; + msg += wire; + sep = ", "; + } + } else { + for (const auto& p : get_enumerator_array()) { + msg += sep; + msg += p.first; + sep = ", "; + } } msg += "]."; return error(msg); @@ -106,9 +181,18 @@ Result string_to_enum(const std::string& _str) { const auto cast_numbers_or_names = [&](const std::string& name) -> Result { - const auto r = internal::enums::from_string(name); - if (r) { - return *r; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_enum_wire_names_with_transform()) { + if (wire == name) { + return val; + } + } + } else { + const auto r = internal::enums::from_string(name); + if (r) { + return *r; + } } if constexpr (enum_names_only) { return make_error_msg(name); @@ -140,6 +224,52 @@ Result string_to_enum(const std::string& _str) { } } +template +Result string_to_enum_with_transform_noexcept( + const std::string& _str) noexcept { + try { + return string_to_enum_with_transform( + _str); + } catch (const std::exception& e) { + return error(e.what()); + } +} + +} // namespace internal + +// Converts an enum value to its wire string representation, honoring +// `rfl::EnumNames` and any `rfl::TransformEnumNames<...>` processor. +template > +std::string enum_to_string(const EnumType _enum) { + return internal::enum_to_string_with_transform< + EnumType, internal::enum_name_transform_v>(_enum); +} + +// Returns all declared enumerators (plus any explicit `rfl::EnumNames` +// overrides for values outside the reflected range) paired with their resolved +// wire names. +template > +std::vector> get_enum_wire_names() { + return internal::get_enum_wire_names_with_transform< + EnumType, internal::enum_name_transform_v>(); +} + +// Converts a string to a value of the given enum type. +// +// By default, numeric values are accepted in addition to the declared +// enumerator names, even when they do not correspond to a declared +// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 +// will produce the cast value 4). Pass enum_names_only = true (or use the +// EnumNamesOnly processor with a parser) to accept only the declared +// enumerator names instead. +template > +Result string_to_enum(const std::string& _str) { + return internal::string_to_enum_with_transform< + EnumType, enum_names_only, + internal::enum_name_transform_v>(_str); +} + } // namespace rfl #endif // RFL_ENUMS_HPP_ diff --git a/include/rfl/parsing/ParserEnum.hpp b/include/rfl/parsing/ParserEnum.hpp index 4a216f434..787595f66 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -60,9 +60,13 @@ struct ParserEnum { return _r.template to_basic_type>(_var) .transform([](const auto _val) { return static_cast(_val); }); } else { + constexpr auto transform = + internal::enum_name_transform_v; + constexpr bool enum_names_only = + internal::enum_names_only_v; return _r.template to_basic_type(_var).and_then( - rfl::string_to_enum>); + &internal::string_to_enum_with_transform_noexcept< + T, enum_names_only, transform>); } } @@ -84,7 +88,10 @@ struct ParserEnum { const auto val = static_cast>(_var); ParentType::add_value(_w, val, _parent); } else { - const auto str = rfl::enum_to_string(_var); + constexpr auto transform = + internal::enum_name_transform_v; + const auto str = + internal::enum_to_string_with_transform(_var); ParentType::add_value(_w, str, _parent); } } @@ -118,16 +125,28 @@ struct ParserEnum { return Type{Type::String{}}; } else if constexpr (config::enum_descriptions::has_descriptions) { // Generate DescribedLiteral for enums with descriptions + constexpr auto transform = + internal::enum_name_transform_v; auto described = Type::DescribedLiteral{}; - constexpr auto enumerators = get_enumerator_array(); - for (const auto& [name, value] : enumerators) { + for (const auto& [wire, value] : + internal::get_unique_enum_wire_names_with_transform()) { auto desc = config::enum_descriptions::get(value); described.values_.push_back( Type::DescribedLiteral::ValueWithDescription{ - .value_ = std::string(name), - .description_ = std::string(desc)}); + .value_ = wire, .description_ = std::string(desc)}); } return Type{std::move(described)}; + } else if constexpr (internal::has_custom_enum_names_v) { + constexpr auto transform = + internal::enum_name_transform_v; + std::vector vals; + for (auto& [wire, _v] : + internal::get_unique_enum_wire_names_with_transform()) { + vals.push_back(std::move(wire)); + } + return Type{Type::Literal{.values_ = std::move(vals)}}; } else { return Parser< R, W, diff --git a/tests/json/test_enum_names.cpp b/tests/json/test_enum_names.cpp new file mode 100644 index 000000000..85cf42c54 --- /dev/null +++ b/tests/json/test_enum_names.cpp @@ -0,0 +1,462 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_enum_names { + +enum class OptimizationLevel { + no_opt, + size_opt, + speed_opt, + cxx_standard, +}; + +enum class OutputMode { + plain_text, + json_pretty, + xml_compact, +}; + +enum class CustomPrefixEnum { + fast_path, + slow_path, +}; + +enum class MixedCaseEnum { + Fast_Path, + Read, +}; + +enum class StringViewTransformEnum { + first_item, + second_item, +}; + +enum class SpanOverridesEnum { + alpha_val, + beta_val, + gamma_val, +}; + +enum class DupOverrideEnum { + first, + second, +}; + +enum class ThrowingTransformEnum { + ok, +}; + +enum class DescribedWireEnum { + fast_mode, + safe_mode, +}; + +enum UnscopedWireEnum : uint8_t { + unscoped_one = 1, + unscoped_two = 2, +}; + +enum class WideWireEnum : int64_t { + small_val = 1, + big_val = 1000000, +}; + +enum class WireFlags : uint32_t { + none = 0, + read_access = 1u << 0, + write_access = 1u << 1, + exec_access = 1u << 2, +}; + +inline WireFlags operator|(WireFlags _a, WireFlags _b) { + return static_cast(static_cast(_a) | + static_cast(_b)); +} + +struct CompilerConfig { + OptimizationLevel opt = OptimizationLevel::speed_opt; + OutputMode output = OutputMode::plain_text; + CustomPrefixEnum mode = CustomPrefixEnum::fast_path; +}; + +struct CliEnumConfig { + rfl::DefaultVal opt = OptimizationLevel::speed_opt; + rfl::DefaultVal output = OutputMode::json_pretty; +}; + +enum class HttpStatus { + ok = 200, + not_found = 404, +}; + +struct StatusPayload { + HttpStatus status = HttpStatus::ok; +}; + +struct DescribedPayload { + DescribedWireEnum mode = DescribedWireEnum::fast_mode; +}; + +inline constexpr std::array kCompressionModes = { + "none", "fast", "max-compression"}; +using CompressionLiteral = rfl::literal_from_table_t; + +struct ArchiveSettings { + CompressionLiteral mode = CompressionLiteral::make<"max-compression">(); +}; + +} // namespace test_enum_names + +namespace rfl { + +// Combine snake_to_kebab transform with an explicit per-enumerator override +// (for identifiers like C++ keywords or non-identifier wire names like "c++20"). +template <> +struct EnumNames { + static constexpr EnumNameTransform transform = + EnumNameTransform::snake_to_kebab; + static constexpr std::array< + EnumOverride, 1> + overrides = {{ + {test_enum_names::OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; + +// Custom transform function returning std::string. +template <> +struct EnumNames { + static std::string transform(const std::string_view _raw) { + return "x-" + apply_enum_name_transform(_raw, EnumNameTransform::snake_to_kebab); + } +}; + +// Custom transform function returning std::string_view. +template <> +struct EnumNames { + static std::string_view transform(const std::string_view _raw) { + return _raw == "first_item" ? std::string_view("one") + : std::string_view("two"); + } +}; + +// Borrowed-range function form of overrides() without transform (non-overridden +// enumerators still inherit processor transforms). +template <> +struct EnumNames { + static std::span> + overrides() { + static constexpr std::array< + EnumOverride, 1> + kOverrides = {{ + {test_enum_names::SpanOverridesEnum::alpha_val, "custom-alpha"}, + }}; + return kOverrides; + } +}; + +// Duplicate override entries for the same enumerator: first entry wins everywhere. +template <> +struct EnumNames { + static constexpr std::array< + EnumOverride, 2> + overrides = {{ + {test_enum_names::DupOverrideEnum::first, "primary"}, + {test_enum_names::DupOverrideEnum::first, "shadowed"}, + }}; +}; + +// Throwing custom transform must return rfl::Error rather than terminating. +template <> +struct EnumNames { + static std::string transform(const std::string_view) { + throw std::runtime_error("transform boom"); + } +}; + +// Out-of-range enum overrides (outside default enchantum range). +template <> +struct EnumNames { + static constexpr std::array, 2> + overrides = {{ + {test_enum_names::HttpStatus::ok, "ok"}, + {test_enum_names::HttpStatus::not_found, "not-found"}, + }}; +}; + +template <> +struct EnumNames { + static constexpr std::array, 1> + overrides = {{ + {test_enum_names::WideWireEnum::big_val, "one-million"}, + }}; +}; + +template <> +struct config::enum_descriptions { + static constexpr bool has_descriptions = true; + static std::string_view get(const test_enum_names::DescribedWireEnum _e) { + return _e == test_enum_names::DescribedWireEnum::fast_mode + ? "Fast execution" + : "Safe execution"; + } +}; + +} // namespace rfl + +namespace test_enum_names { + +TEST(json, test_enum_names_trait_overrides_and_transform) { + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::no_opt), "no-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::size_opt), "size-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::speed_opt), "speed-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::cxx_standard), "c++20"); + + ASSERT_EQ(*rfl::string_to_enum("no-opt"), + OptimizationLevel::no_opt); + ASSERT_EQ(*rfl::string_to_enum("c++20"), + OptimizationLevel::cxx_standard); + // Raw C++ identifier and wrong case should not match. + EXPECT_FALSE(rfl::string_to_enum("no_opt")); + EXPECT_FALSE(rfl::string_to_enum("NO-OPT")); + EXPECT_FALSE(rfl::string_to_enum("cxx_standard")); + + // Custom transform function returning std::string and std::string_view. + EXPECT_EQ(rfl::enum_to_string(CustomPrefixEnum::fast_path), "x-fast-path"); + ASSERT_EQ(*rfl::string_to_enum("x-slow-path"), + CustomPrefixEnum::slow_path); + + EXPECT_EQ(rfl::enum_to_string(StringViewTransformEnum::first_item), "one"); + ASSERT_EQ(*rfl::string_to_enum("two"), + StringViewTransformEnum::second_item); + + // Borrowed-range overrides() function form + processor fallback. + EXPECT_EQ(rfl::enum_to_string(SpanOverridesEnum::alpha_val), "custom-alpha"); + EXPECT_EQ(rfl::enum_to_string(SpanOverridesEnum::beta_val), "beta_val"); + EXPECT_EQ((rfl::enum_to_string( + SpanOverridesEnum::alpha_val)), + "custom-alpha"); + EXPECT_EQ((rfl::enum_to_string( + SpanOverridesEnum::beta_val)), + "beta-val"); + ASSERT_EQ(*(rfl::string_to_enum("beta-val")), + SpanOverridesEnum::beta_val); + + // Duplicate override entries: first wins consistently across read/write/schema. + EXPECT_EQ(rfl::enum_to_string(DupOverrideEnum::first), "primary"); + ASSERT_EQ((*(rfl::string_to_enum("primary"))), + DupOverrideEnum::first); + EXPECT_FALSE((rfl::string_to_enum("shadowed"))); + + // Throwing custom transform returns rfl::Error instead of terminating. + const auto thrown = + rfl::json::read(R"("ok")"); + EXPECT_FALSE(thrown); + EXPECT_NE(thrown.error().what().find("transform boom"), std::string::npos); +} + +TEST(json, test_enum_names_processor_transforms_and_nested_processors) { + static_assert(rfl::internal::enum_name_transform_v< + rfl::EnumSnakeCaseToKebabCase> == + rfl::EnumNameTransform::snake_to_kebab); + static_assert( + rfl::internal::enum_name_transform_v< + rfl::Processors>> == + rfl::EnumNameTransform::snake_to_kebab); + + // Direct calls with bare processor and nested Processors<...>. + EXPECT_EQ((rfl::enum_to_string( + OutputMode::json_pretty)), + "json-pretty"); + const auto direct_wire = + rfl::get_enum_wire_names(); + ASSERT_EQ(direct_wire.size(), 3u); + EXPECT_EQ(direct_wire[1].first, "json-pretty"); + + // OutputMode has no EnumNames specialization; processor applies. + const CompilerConfig cfg{ + .opt = OptimizationLevel::cxx_standard, + .output = OutputMode::json_pretty, + .mode = CustomPrefixEnum::slow_path, + }; + + const auto kebab_json = rfl::json::write(cfg); + EXPECT_EQ( + kebab_json, + R"({"opt":"c++20","output":"json-pretty","mode":"x-slow-path"})"); + + const auto parsed = + rfl::json::read(kebab_json); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->opt, OptimizationLevel::cxx_standard); + EXPECT_EQ(parsed->output, OutputMode::json_pretty); + EXPECT_EQ(parsed->mode, CustomPrefixEnum::slow_path); + + // CamelCase lowercases the leading character too. + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Fast_Path)), + "fastPath"); + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Read)), + "read"); + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Fast_Path)), + "fast_path"); + + const auto camel_json = rfl::json::write(cfg); + EXPECT_NE(camel_json.find(R"("output":"jsonPretty")"), std::string::npos) + << camel_json; + + const auto pascal_json = rfl::json::write(cfg); + EXPECT_NE(pascal_json.find(R"("output":"JsonPretty")"), std::string::npos) + << pascal_json; + + const auto upper_json = rfl::json::write(cfg); + EXPECT_NE(upper_json.find(R"("output":"JSON_PRETTY")"), std::string::npos) + << upper_json; + + // EnumNamesOnly rejects numeric strings, while UnderlyingEnums uses integers. + EXPECT_FALSE( + (rfl::json::read(R"("1")"))); + EXPECT_EQ( + (rfl::json::write( + OutputMode::json_pretty)), + "1"); +} + +TEST(json, test_enum_names_json_schema_and_default_val) { + const auto schema = + rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("enum":["no-opt","size-opt","speed-opt","c++20"])"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("enum":["plain-text","json-pretty","xml-compact"])"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("enum":["x-fast-path","x-slow-path"])"), + std::string::npos) + << schema; + + // DefaultVal must emit the transformed wire name matching its enum schema. + const auto default_schema = + rfl::json::to_schema(); + EXPECT_NE(default_schema.find( + R"("enum":["plain-text","json-pretty","xml-compact"])"), + std::string::npos) + << default_schema; + EXPECT_NE(default_schema.find(R"("default":"json-pretty")"), + std::string::npos) + << default_schema; + EXPECT_NE(default_schema.find(R"("default":"speed-opt")"), + std::string::npos) + << default_schema; + + // DescribedLiteral respects enum wire transforms too. + const auto desc_schema = + rfl::json::to_schema(); + EXPECT_NE(desc_schema.find(R"("fast-mode")"), std::string::npos) + << desc_schema; + EXPECT_NE(desc_schema.find(R"("Fast execution")"), std::string::npos) + << desc_schema; +} + +TEST(json, test_enum_names_flags_unscoped_and_wide_underlying) { + // Flag enum with TransformEnumNames: zero flag and combined flags. + EXPECT_EQ((rfl::enum_to_string( + WireFlags::none)), + "none"); + const auto combined = WireFlags::read_access | WireFlags::exec_access; + EXPECT_EQ((rfl::enum_to_string( + combined)), + "read-access|exec-access"); + const auto parsed_flags = + rfl::string_to_enum( + "read-access|write-access"); + ASSERT_TRUE(parsed_flags) << parsed_flags.error().what(); + EXPECT_EQ(*parsed_flags, WireFlags::read_access | WireFlags::write_access); + + // Unscoped uint8_t enum. + EXPECT_EQ((rfl::enum_to_string( + unscoped_two)), + "unscoped-two"); + ASSERT_EQ(*(rfl::string_to_enum( + "unscoped-one")), + unscoped_one); + + // Non-int int64_t enum with out-of-range override + processor transform. + EXPECT_EQ((rfl::enum_to_string( + WideWireEnum::small_val)), + "small-val"); + EXPECT_EQ((rfl::enum_to_string( + WideWireEnum::big_val)), + "one-million"); + ASSERT_EQ(*(rfl::string_to_enum( + "one-million")), + WideWireEnum::big_val); +} + +TEST(json, test_enum_names_cli_read) { + const std::vector args = { + "--opt=c++20", "--output=xml-compact"}; + const auto parsed = + rfl::cli::read(args); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->opt.value(), OptimizationLevel::cxx_standard); + EXPECT_EQ(parsed->output.value(), OutputMode::xml_compact); +} + +TEST(json, test_enum_names_out_of_range_overrides_in_schema_and_errors) { + const auto names = rfl::get_enum_wire_names(); + ASSERT_EQ(names.size(), 2u); + EXPECT_EQ(names[0].first, "ok"); + EXPECT_EQ(names[1].first, "not-found"); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("enum":["ok","not-found"])"), std::string::npos) + << schema; + + const auto parsed = rfl::json::read(R"({"status":"not-found"})"); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->status, HttpStatus::not_found); + + const auto bad = rfl::string_to_enum("bogus"); + ASSERT_FALSE(bad); + EXPECT_NE(bad.error().what().find("ok, not-found"), std::string::npos) + << bad.error().what(); +} + +TEST(json, test_literal_from_table_t) { + ArchiveSettings s; + EXPECT_EQ(rfl::json::write(s), R"({"mode":"max-compression"})"); + + const auto parsed = + rfl::json::read(R"({"mode":"fast"})"); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->mode.str(), "fast"); + + const auto bad = rfl::json::read(R"({"mode":"bogus"})"); + EXPECT_FALSE(bad); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("enum":["none","fast","max-compression"])"), + std::string::npos) + << schema; +} + +} // namespace test_enum_names