From dacb81ee80ab9610b230dbdab01ff078865517de Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 21:26:20 +0100 Subject: [PATCH 1/2] Add rfl::EnumNames and enum wire-name transform processors --- include/rfl.hpp | 1 + include/rfl/EnumNames.hpp | 286 +++++++++++++++++++++++++++++ include/rfl/enums.hpp | 117 ++++++++++-- include/rfl/parsing/ParserEnum.hpp | 41 ++++- tests/json/test_enum_names.cpp | 214 +++++++++++++++++++++ 5 files changed, 637 insertions(+), 22 deletions(-) create mode 100644 include/rfl/EnumNames.hpp create mode 100644 tests/json/test_enum_names.cpp 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..121565edb --- /dev/null +++ b/include/rfl/EnumNames.hpp @@ -0,0 +1,286 @@ +#ifndef RFL_ENUMNAMES_HPP_ +#define RFL_ENUMNAMES_HPP_ + +#include +#include +#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, +}; + +/// Applies a built-in `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 (cap_next) { + out.push_back( + static_cast(std::toupper(static_cast(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( + static_cast(std::toupper(static_cast(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( + static_cast(std::tolower(static_cast(ch)))); + } + return out; + } + case EnumNameTransform::to_upper: { + std::string out; + out.reserve(_name.size()); + for (const char ch : _name) { + out.push_back( + static_cast(std::toupper(static_cast(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);` +/// - `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` override/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...>> { + 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 = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors< + Processors, Tail...>> { + static constexpr EnumNameTransform value = _t; +}; + +template +struct enum_name_transform_from_processors> + : enum_name_transform_from_processors> {}; + +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) { + { EnumNames::transform(_s) } -> std::convertible_to; +}; + +template > +constexpr bool has_custom_enum_names_v = + HasEnumOverridesVar> || + HasAnyEnumOverridesFn> || + HasEnumTransformConst> || + HasEnumTransformFn> || + (enum_name_transform_v != EnumNameTransform::none); + +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(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 (enum_name_transform_v != + EnumNameTransform::none) { + return apply_enum_name_transform(_raw_name, + enum_name_transform_v); + } else { + return std::string(_raw_name); + } +} + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..d604797ff 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -4,6 +4,7 @@ #include #include +#include "EnumNames.hpp" #include "Result.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" @@ -52,9 +53,29 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// Converts an enum value to tis string representation. -template +// 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) { + const auto one_to_wire = [](const EnumType _e) -> std::string { + if constexpr (internal::has_custom_enum_names_v) { + for (const auto& [raw_name, val] : get_enumerator_array()) { + if (val == _e) { + return internal::resolve_enum_wire_name( + val, raw_name); + } + } + // Also check explicit overrides even for enumerators outside magic range. + for (const auto& [val, wire] : internal::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,22 +85,52 @@ 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); } } +// 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() { + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back( + internal::resolve_enum_wire_name(val, + raw_name), + val); + } + if constexpr (internal::has_custom_enum_names_v) { + for (const auto& [val, wire] : internal::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; +} + // Converts a string to a value of the given enum type. // // By default, numeric values are accepted in addition to the declared @@ -88,17 +139,39 @@ std::string enum_to_string(const EnumType _enum) { // 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 +template > Result string_to_enum(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 (internal::has_custom_enum_names_v) { + std::vector seen; + for (const auto& [wire, _v] : + get_enum_wire_names()) { + bool dup = false; + for (const auto& prev : seen) { + if (prev == wire) { + dup = true; + break; + } + } + if (dup) { + continue; + } + seen.push_back(wire); + 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 +179,23 @@ 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 (internal::has_custom_enum_names_v) { + for (const auto& [raw_name, val] : get_enumerator_array()) { + if (internal::resolve_enum_wire_name( + val, raw_name) == name) { + return val; + } + } + for (const auto& [val, wire] : internal::get_enum_overrides()) { + 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); diff --git a/include/rfl/parsing/ParserEnum.hpp b/include/rfl/parsing/ParserEnum.hpp index 4a216f434..d99b9b4f9 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -61,8 +61,11 @@ struct ParserEnum { .transform([](const auto _val) { return static_cast(_val); }); } else { return _r.template to_basic_type(_var).and_then( - rfl::string_to_enum>); + [](const std::string& _s) { + return rfl::string_to_enum< + T, internal::enum_names_only_v, + ProcessorsType>(_s); + }); } } @@ -84,7 +87,7 @@ struct ParserEnum { const auto val = static_cast>(_var); ParentType::add_value(_w, val, _parent); } else { - const auto str = rfl::enum_to_string(_var); + const auto str = rfl::enum_to_string(_var); ParentType::add_value(_w, str, _parent); } } @@ -119,15 +122,39 @@ struct ParserEnum { } else if constexpr (config::enum_descriptions::has_descriptions) { // Generate DescribedLiteral for enums with descriptions auto described = Type::DescribedLiteral{}; - constexpr auto enumerators = get_enumerator_array(); - for (const auto& [name, value] : enumerators) { + for (const auto& [wire, value] : + get_enum_wire_names()) { + bool dup = false; + for (const auto& existing : described.values_) { + if (existing.value_ == wire) { + dup = true; + break; + } + } + if (dup) { + continue; + } 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) { + std::vector vals; + for (const auto& [wire, _v] : get_enum_wire_names()) { + bool dup = false; + for (const auto& existing : vals) { + if (existing == wire) { + dup = true; + break; + } + } + if (!dup) { + vals.push_back(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..dad2e01e1 --- /dev/null +++ b/tests/json/test_enum_names.cpp @@ -0,0 +1,214 @@ +#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, +}; + +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; +}; + +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. +template <> +struct EnumNames { + static std::string transform(const std::string_view _raw) { + return "x-" + apply_enum_name_transform(_raw, EnumNameTransform::snake_to_kebab); + } +}; + +// 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"}, + }}; +}; + +} // 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 should no longer match when transformed. + EXPECT_FALSE(rfl::string_to_enum("no_opt")); + EXPECT_FALSE(rfl::string_to_enum("cxx_standard")); + + // Custom transform function. + EXPECT_EQ(rfl::enum_to_string(CustomPrefixEnum::fast_path), "x-fast-path"); + ASSERT_EQ(*rfl::string_to_enum("x-slow-path"), + CustomPrefixEnum::slow_path); +} + +TEST(json, test_enum_names_processor_transforms) { + // 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 and UpperCase processors. + 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; +} + +TEST(json, test_enum_names_json_schema) { + 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; +} + +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 From 3466efe76a154c4079b54e210f08c8dc0e9614a1 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 22:23:05 +0100 Subject: [PATCH 2/2] Address Judge blockers: nested Processors & bare TransformEnumNames, ASCII snake_to_camel, normalize ParserEnum/enums template args, docs & tests --- docs/content/enums.md | 23 +++ docs/content/processors.md | 5 + include/rfl/EnumNames.hpp | 101 +++++++---- include/rfl/enums.hpp | 139 +++++++++------ include/rfl/parsing/ParserEnum.hpp | 48 +++--- tests/json/test_enum_names.cpp | 260 ++++++++++++++++++++++++++++- 6 files changed, 461 insertions(+), 115 deletions(-) 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/EnumNames.hpp b/include/rfl/EnumNames.hpp index 121565edb..931d423c3 100644 --- a/include/rfl/EnumNames.hpp +++ b/include/rfl/EnumNames.hpp @@ -1,18 +1,16 @@ #ifndef RFL_ENUMNAMES_HPP_ #define RFL_ENUMNAMES_HPP_ -#include -#include #include +#include #include -#include +#include #include #include #include #include #include #include -#include #include "Literal.hpp" #include "Processors.hpp" @@ -31,7 +29,19 @@ enum class EnumNameTransform : uint8_t { to_upper, }; -/// Applies a built-in `EnumNameTransform` to an enumerator identifier. +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) { @@ -53,9 +63,10 @@ inline std::string apply_enum_name_transform( 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( - static_cast(std::toupper(static_cast(ch)))); + out.push_back(internal::ascii_to_upper(ch)); cap_next = false; } else { out.push_back(ch); @@ -71,8 +82,7 @@ inline std::string apply_enum_name_transform( if (ch == '_') { cap_next = true; } else if (cap_next) { - out.push_back( - static_cast(std::toupper(static_cast(ch)))); + out.push_back(internal::ascii_to_upper(ch)); cap_next = false; } else { out.push_back(ch); @@ -84,8 +94,7 @@ inline std::string apply_enum_name_transform( std::string out; out.reserve(_name.size()); for (const char ch : _name) { - out.push_back( - static_cast(std::tolower(static_cast(ch)))); + out.push_back(internal::ascii_to_lower(ch)); } return out; } @@ -93,8 +102,7 @@ inline std::string apply_enum_name_transform( std::string out; out.reserve(_name.size()); for (const char ch : _name) { - out.push_back( - static_cast(std::toupper(static_cast(ch)))); + out.push_back(internal::ascii_to_upper(ch)); } return out; } @@ -114,13 +122,17 @@ using EnumOverride = std::pair; /// 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` override/transform. +/// 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; @@ -165,6 +177,8 @@ 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()...>; }; @@ -178,20 +192,30 @@ 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< - Processors, Tail...>> { - static constexpr EnumNameTransform value = _t; -}; - template -struct enum_name_transform_from_processors> - : enum_name_transform_from_processors> {}; +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 = @@ -226,16 +250,22 @@ concept HasEnumTransformConst = requires { template concept HasEnumTransformFn = requires(std::string_view _s) { - { EnumNames::transform(_s) } -> std::convertible_to; + requires std::constructible_from::transform(_s))>; }; -template > -constexpr bool has_custom_enum_names_v = +template +constexpr bool has_custom_enum_names_for_transform_v = HasEnumOverridesVar> || HasAnyEnumOverridesFn> || HasEnumTransformConst> || HasEnumTransformFn> || - (enum_name_transform_v != EnumNameTransform::none); + (_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>> @@ -258,9 +288,9 @@ get_enum_overrides() { } } -template > -inline std::string resolve_enum_wire_name(const E _val, - const std::string_view _raw_name) { +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) { @@ -271,15 +301,20 @@ inline std::string resolve_enum_wire_name(const E _val, return std::string(EnumNames::transform(_raw_name)); } else if constexpr (HasEnumTransformConst) { return apply_enum_name_transform(_raw_name, EnumNames::transform); - } else if constexpr (enum_name_transform_v != - EnumNameTransform::none) { - return apply_enum_name_transform(_raw_name, - enum_name_transform_v); + } 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 diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index d604797ff..49a5b65be 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -1,8 +1,11 @@ #ifndef RFL_ENUMS_HPP_ #define RFL_ENUMS_HPP_ +#include #include #include +#include +#include #include "EnumNames.hpp" #include "Result.hpp" @@ -53,20 +56,23 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// 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) { +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 (internal::has_custom_enum_names_v) { + if constexpr (has_custom_enum_names_for_transform_v) { for (const auto& [raw_name, val] : get_enumerator_array()) { if (val == _e) { - return internal::resolve_enum_wire_name( + 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] : internal::get_enum_overrides()) { + for (const auto& [val, wire] : get_enum_overrides()) { if (val == _e) { return std::string(wire); } @@ -100,22 +106,20 @@ std::string enum_to_string(const EnumType _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() { +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( - internal::resolve_enum_wire_name(val, + resolve_enum_wire_name_for_transform(val, raw_name), val); } - if constexpr (internal::has_custom_enum_names_v) { - for (const auto& [val, wire] : internal::get_enum_overrides()) { + 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) { @@ -131,37 +135,35 @@ std::vector> get_enum_wire_names() { return out; } -// 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_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 = ""; - if constexpr (internal::has_custom_enum_names_v) { - std::vector seen; + if constexpr (has_custom_enum_names_for_transform_v) { for (const auto& [wire, _v] : - get_enum_wire_names()) { - bool dup = false; - for (const auto& prev : seen) { - if (prev == wire) { - dup = true; - break; - } - } - if (dup) { - continue; - } - seen.push_back(wire); + get_unique_enum_wire_names_with_transform()) { msg += sep; msg += wire; sep = ", "; @@ -179,14 +181,9 @@ Result string_to_enum(const std::string& _str) { const auto cast_numbers_or_names = [&](const std::string& name) -> Result { - if constexpr (internal::has_custom_enum_names_v) { - for (const auto& [raw_name, val] : get_enumerator_array()) { - if (internal::resolve_enum_wire_name( - val, raw_name) == name) { - return val; - } - } - for (const auto& [val, wire] : internal::get_enum_overrides()) { + 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; } @@ -227,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 d99b9b4f9..787595f66 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -60,12 +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( - [](const std::string& _s) { - return rfl::string_to_enum< - T, internal::enum_names_only_v, - ProcessorsType>(_s); - }); + &internal::string_to_enum_with_transform_noexcept< + T, enum_names_only, transform>); } } @@ -87,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); } } @@ -121,19 +125,12 @@ 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{}; for (const auto& [wire, value] : - get_enum_wire_names()) { - bool dup = false; - for (const auto& existing : described.values_) { - if (existing.value_ == wire) { - dup = true; - break; - } - } - if (dup) { - continue; - } + internal::get_unique_enum_wire_names_with_transform()) { auto desc = config::enum_descriptions::get(value); described.values_.push_back( Type::DescribedLiteral::ValueWithDescription{ @@ -141,18 +138,13 @@ struct ParserEnum { } 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 (const auto& [wire, _v] : get_enum_wire_names()) { - bool dup = false; - for (const auto& existing : vals) { - if (existing == wire) { - dup = true; - break; - } - } - if (!dup) { - vals.push_back(wire); - } + 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 { diff --git a/tests/json/test_enum_names.cpp b/tests/json/test_enum_names.cpp index dad2e01e1..85cf42c54 100644 --- a/tests/json/test_enum_names.cpp +++ b/tests/json/test_enum_names.cpp @@ -1,9 +1,12 @@ #include #include +#include #include #include #include +#include +#include #include #include #include @@ -28,6 +31,58 @@ enum class CustomPrefixEnum { 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; @@ -48,6 +103,10 @@ 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; @@ -73,7 +132,7 @@ struct EnumNames { }}; }; -// Custom transform function. +// Custom transform function returning std::string. template <> struct EnumNames { static std::string transform(const std::string_view _raw) { @@ -81,6 +140,49 @@ struct EnumNames { } }; +// 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 { @@ -91,6 +193,24 @@ struct EnumNames { }}; }; +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 { @@ -105,17 +225,66 @@ TEST(json, test_enum_names_trait_overrides_and_transform) { OptimizationLevel::no_opt); ASSERT_EQ(*rfl::string_to_enum("c++20"), OptimizationLevel::cxx_standard); - // Raw C++ identifier should no longer match when transformed. + // 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. + // 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) { +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, @@ -135,7 +304,17 @@ TEST(json, test_enum_names_processor_transforms) { EXPECT_EQ(parsed->output, OutputMode::json_pretty); EXPECT_EQ(parsed->mode, CustomPrefixEnum::slow_path); - // CamelCase and UpperCase processors. + // 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; @@ -147,9 +326,18 @@ TEST(json, test_enum_names_processor_transforms) { 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) { +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"])"), @@ -161,6 +349,66 @@ TEST(json, test_enum_names_json_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) {