From c8c49734202da86587c40a88bc512506f439da10 Mon Sep 17 00:00:00 2001 From: Denis Popov Date: Sun, 29 Nov 2026 10:33:30 -0800 Subject: [PATCH] feat(enums): add rfl::TransformEnumNames processors (#731) Adds opt-in whole-enum wire-name casing transform processors (`rfl::TransformEnumNames<...>` plus aliases `EnumSnakeCaseToKebabCase`, `EnumSnakeCaseToCamelCase`, `EnumSnakeCaseToPascalCase`, `EnumCamelCaseToSnakeCase`, `EnumToLowerCase`, `EnumToUpperCase`) across read, write, `rfl::enum_to_string`, `rfl::string_to_enum`, and JSON Schema generation. Resolved wire-name tables are cached once per `(EnumType, EnumNameTransform)`. Parent: depends on `feat(enums): accept std::string_view in rfl::string_to_enum (#565)` (open upstream PR #802). Per-enum overrides/trait (`rfl::EnumNames`, #106) is split into a separate child commit on top of this processor seam. Judge polish applied: - Moves non-template `apply_enum_name_transform` out-of-line into `src/rfl/TransformEnumNames.cpp` (`RFL_API`, wired via `src/reflectcpp.cpp`). - Places `enum_name_transform_v` in `include/rfl/internal/enum_name_transform_v.hpp` (mirroring `enum_names_only_v.hpp` with `std::remove_pointer_t`). - Adds `EnumCamelCaseToSnakeCase` for parity with `rfl::CamelCaseToSnakeCase` (#588). - Accepts variadic `class... Ps` on `rfl::enum_to_string` and `rfl::string_to_enum`, strips `std::remove_cvref_t`, and guards `config::enum_descriptions` so untransformed enums avoid static heap caches. Refs: https://github.com/munich-data-engineering/reflect-cpp/issues/731 (Maintainer: "My first instinct would be a processor, but I need to give it some thought.") Downstream receipts: - NVIDIA/cuda-quantum maintains 4 hand-written `rfl::Reflector` switch tables for `snake_case` -> `kebab-case` YAML enums: https://github.com/NVIDIA/cuda-quantum/blob/81ef20d9d4a1e0912a6dbc68637ece017e8fd324/cudaq/lib/Target/Yaml/TargetConfigYamlAdapters.h#L27-L75 https://github.com/NVIDIA/cuda-quantum/blob/81ef20d9d4a1e0912a6dbc68637ece017e8fd324/cudaq/lib/Target/Yaml/v2/QuakeUnmappedProfileYaml.h#L16-L53 - openmoq/moqx duplicates `enum class QuicStack` as `rfl::Literal` + switch mapper: https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/src/config/loader/ParsedConfig.h#L291 - munich-data-engineering/sqlgen post-processes `enum_to_string` across all 4 SQL backends: https://github.com/munich-data-engineering/sqlgen/blob/265b0a174b661c5905b874f97b064aecb4cded70/src/sqlgen/sqlite/to_sql.cpp#L338-L340 - games-on-whales/wolf lowercases `enum_to_string`: https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/src/moonlight-server/api/openapi.cpp#L92 --- docs/content/processors.md | 23 +++ include/rfl.hpp | 1 + include/rfl/TransformEnumNames.hpp | 54 +++++ include/rfl/enums.hpp | 193 +++++++++++++++--- .../rfl/internal/enum_name_transform_v.hpp | 49 +++++ include/rfl/parsing/ParserEnum.hpp | 53 ++++- src/reflectcpp.cpp | 1 + src/rfl/TransformEnumNames.cpp | 118 +++++++++++ 8 files changed, 450 insertions(+), 42 deletions(-) create mode 100644 include/rfl/TransformEnumNames.hpp create mode 100644 include/rfl/internal/enum_name_transform_v.hpp create mode 100644 src/rfl/TransformEnumNames.cpp diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..01f14d72e 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -549,6 +549,29 @@ The resulting JSON string looks like this: {"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} ``` +## `rfl::TransformEnumNames` (`EnumSnakeCaseToKebabCase`, etc.) + +Applies a whole-enum wire-name casing transform to enum fields during reading, +writing, and JSON Schema generation. Resolved wire-name tables are cached once +per `(EnumType, EnumNameTransform)` pair. + +Built-in aliases: +- `rfl::EnumSnakeCaseToKebabCase` +- `rfl::EnumSnakeCaseToCamelCase` +- `rfl::EnumSnakeCaseToPascalCase` +- `rfl::EnumCamelCaseToSnakeCase` +- `rfl::EnumToLowerCase` +- `rfl::EnumToUpperCase` + +```cpp +enum class CostModel { t_count, two_qubit_gate_count, gate_count }; +struct Config { CostModel cost_model; }; + +const auto json_str = rfl::json::write( + Config{.cost_model = CostModel::two_qubit_gate_count}); +// {"cost_model":"two-qubit-gate-count"} +``` + ## Writing your own processors In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter. diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..7599c1611 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -54,6 +54,7 @@ #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" +#include "rfl/TransformEnumNames.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" #include "rfl/Variant.hpp" diff --git a/include/rfl/TransformEnumNames.hpp b/include/rfl/TransformEnumNames.hpp new file mode 100644 index 000000000..7aeb6d397 --- /dev/null +++ b/include/rfl/TransformEnumNames.hpp @@ -0,0 +1,54 @@ +#ifndef RFL_TRANSFORMENUMNAMES_HPP_ +#define RFL_TRANSFORMENUMNAMES_HPP_ + +#include +#include +#include + +#include "common.hpp" + +namespace rfl { + +/// Built-in wire-name transforms applicable to C++ enum enumerator names via +/// `rfl::TransformEnumNames<...>` processors. +enum class EnumNameTransform : std::uint8_t { + none = 0, + snake_to_kebab, + snake_to_camel, + snake_to_pascal, + camel_to_snake, + to_lower, + to_upper, +}; + +/// Applies a built-in ASCII `EnumNameTransform` to an enumerator identifier. +RFL_API std::string apply_enum_name_transform(std::string_view _name, + EnumNameTransform _transform); + +/// Processor that applies a whole-enum wire-name transform across read, write, +/// and schema generation. Resolved wire-name tables are cached once per +/// `(EnumType, EnumNameTransform)` pair. +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 EnumCamelCaseToSnakeCase = + TransformEnumNames; +using EnumToLowerCase = TransformEnumNames; +using EnumToUpperCase = TransformEnumNames; + +} // namespace rfl + +#endif // RFL_TRANSFORMENUMNAMES_HPP_ diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 133791b2f..2d674f8a3 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -2,13 +2,17 @@ #define RFL_ENUMS_HPP_ #include +#include #include #include #include #include #include +#include "Processors.hpp" #include "Result.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" #include "internal/enums/get_enum_range.hpp" @@ -56,63 +60,148 @@ 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) { - if constexpr (internal::enums::is_flag_enum) { +namespace internal { + +template +inline constexpr bool has_custom_enum_names_for_transform_v = + (_transform != EnumNameTransform::none); + +template +inline constexpr bool has_custom_enum_names_v = + has_custom_enum_names_for_transform_v< + std::remove_cvref_t, enum_name_transform_v>; + +template +std::vector>> +build_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back(apply_enum_name_transform(raw_name, _transform), val); + } + return out; +} + +template +const std::vector>>& +get_cached_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kTable = build_enum_wire_names_with_transform(); + return kTable; +} + +template +const std::vector>>& +get_cached_unique_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kUnique = []() { + std::vector> out; + const auto& all = get_cached_enum_wire_names_with_transform(); + out.reserve(all.size()); + for (const auto& entry : all) { + bool dup = false; + for (const auto& existing : out) { + if (existing.first == entry.first) { + dup = true; + break; + } + } + if (!dup) { + out.push_back(entry); + } + } + return out; + }(); + return kUnique; +} + +template +std::string enum_to_single_wire_name(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (val == _enum) { + return wire; + } + } + return std::to_string(static_cast>(_enum)); + } else { + return internal::enums::to_string(_enum); + } +} + +template +std::string enum_to_string_with_transform(const EnumType _enum) { + using E = std::remove_cvref_t; + 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; + using T = std::underlying_type_t; auto val = static_cast(_enum); int i = 0; std::vector flags; 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)); + auto str = enum_to_single_wire_name( + static_cast(static_cast(1) << i)); flags.emplace_back(std::move(str)); } ++i; val >>= 1; } if (flags.empty()) { - return internal::enums::to_string(static_cast(0)); + return enum_to_single_wire_name(static_cast(0)); } return internal::strings::join("|", flags); } else { - return internal::enums::to_string(_enum); + return enum_to_single_wire_name(_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_view _str) { +template +Result> string_to_enum_with_transform( + const std::string_view _str) { + using E = std::remove_cvref_t; const auto make_error_msg = [](const std::string_view 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& p : + get_cached_unique_enum_wire_names_with_transform()) { + msg += sep; + msg += p.first; + sep = ", "; + } + } else { + for (const auto& p : get_enumerator_array()) { + msg += sep; + msg += p.first; + sep = ", "; + } } msg += "]."; return error(msg); }; const auto cast_numbers_or_names = - [&](const std::string_view name) -> Result { - const auto r = internal::enums::from_string(name); - if (r) { - return *r; + [&](const std::string_view name) -> Result { + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_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); @@ -120,7 +209,7 @@ Result string_to_enum(const std::string_view _str) { if (name.empty()) { return make_error_msg(name); } - using Underlying = std::underlying_type_t; + using Underlying = std::underlying_type_t; using ParseType = std::conditional_t< (sizeof(Underlying) < sizeof(int)), int, std::conditional_t< @@ -139,14 +228,14 @@ Result string_to_enum(const std::string_view _str) { const auto* end = begin + name.size(); const auto [ptr, ec] = std::from_chars(begin, end, val); if (ec == std::errc{} && ptr == end) { - return static_cast(val); + return static_cast(val); } return make_error_msg(name); } }; - if constexpr (internal::enums::is_flag_enum) { - using T = std::underlying_type_t; + if constexpr (internal::enums::is_flag_enum) { + using T = std::underlying_type_t; auto res = static_cast(0); std::string_view remaining = _str; while (true) { @@ -162,12 +251,52 @@ Result string_to_enum(const std::string_view _str) { } remaining.remove_prefix(pos + 1); } - return static_cast(res); + return static_cast(res); } else { return cast_numbers_or_names(_str); } } +template +Result> string_to_enum_with_transform_noexcept( + const std::string_view _str) noexcept { + try { + return string_to_enum_with_transform( + _str); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception thrown while parsing enum value."); + } +} + +} // namespace internal + +// Converts an enum value to its wire string representation, honoring any +// `rfl::TransformEnumNames<...>` processor passed in `Ps...`. +template +std::string enum_to_string(const EnumType _enum) { + return internal::enum_to_string_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(_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_view _str) noexcept { + return internal::string_to_enum_with_transform_noexcept< + std::remove_cvref_t, enum_names_only, + internal::enum_name_transform_v>>(_str); +} + } // namespace rfl #endif // RFL_ENUMS_HPP_ diff --git a/include/rfl/internal/enum_name_transform_v.hpp b/include/rfl/internal/enum_name_transform_v.hpp new file mode 100644 index 000000000..7c4249bdd --- /dev/null +++ b/include/rfl/internal/enum_name_transform_v.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ +#define RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ + +#include + +#include "../Processors.hpp" +#include "../TransformEnumNames.hpp" + +namespace rfl::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< + std::remove_cvref_t>>::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 +inline constexpr EnumNameTransform enum_name_transform_v = + enum_name_transform_from_processors< + std::remove_cvref_t>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ diff --git a/include/rfl/parsing/ParserEnum.hpp b/include/rfl/parsing/ParserEnum.hpp index 4a216f434..4dd5f6977 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -7,6 +7,7 @@ #include "../Result.hpp" #include "../config.hpp" #include "../enums.hpp" +#include "../internal/enum_name_transform_v.hpp" #include "../internal/enum_names_only_v.hpp" #include "../internal/enums/is_flag_enum.hpp" #include "../internal/enums/is_scoped_enum.hpp" @@ -60,9 +61,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 +89,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); } } @@ -119,15 +127,40 @@ 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) { - auto desc = config::enum_descriptions::get(value); - described.values_.push_back( - Type::DescribedLiteral::ValueWithDescription{ - .value_ = std::string(name), - .description_ = std::string(desc)}); + if constexpr (internal::has_custom_enum_names_v) { + constexpr auto transform = + internal::enum_name_transform_v; + for (const auto& [wire, value] : + internal::get_cached_unique_enum_wire_names_with_transform< + U, transform>()) { + auto desc = config::enum_descriptions::get(value); + described.values_.push_back( + Type::DescribedLiteral::ValueWithDescription{ + .value_ = wire, .description_ = std::string(desc)}); + } + } else { + constexpr auto enumerators = get_enumerator_array(); + for (const auto& [name, value] : enumerators) { + auto desc = config::enum_descriptions::get(value); + described.values_.push_back( + Type::DescribedLiteral::ValueWithDescription{ + .value_ = std::string(name), + .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; + const auto& entries = + internal::get_cached_unique_enum_wire_names_with_transform< + U, transform>(); + std::vector vals; + vals.reserve(entries.size()); + for (const auto& entry : entries) { + vals.push_back(entry.first); + } + return Type{Type::Literal{.values_ = std::move(vals)}}; } else { return Parser< R, W, diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index ea76c27ca..d0f6de31b 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -30,6 +30,7 @@ SOFTWARE. // compilation. #include "rfl/Generic.cpp" +#include "rfl/TransformEnumNames.cpp" #include "rfl/env/Writer.cpp" #include "rfl/generic/Writer.cpp" #include "rfl/internal/strings/strings.cpp" diff --git a/src/rfl/TransformEnumNames.cpp b/src/rfl/TransformEnumNames.cpp new file mode 100644 index 000000000..1bbc1f0ae --- /dev/null +++ b/src/rfl/TransformEnumNames.cpp @@ -0,0 +1,118 @@ +#include "rfl/TransformEnumNames.hpp" + +#include +#include +#include + +namespace rfl { +namespace { + +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; +} + +constexpr bool ascii_is_upper(const char _ch) noexcept { + return _ch >= 'A' && _ch <= 'Z'; +} + +constexpr bool ascii_is_lower(const char _ch) noexcept { + return _ch >= 'a' && _ch <= 'z'; +} + +} // namespace + +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(ascii_to_lower(ch)); + } else if (cap_next) { + out.push_back(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(ascii_to_upper(ch)); + cap_next = false; + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::camel_to_snake: { + std::string out; + out.reserve(_name.size() + 4); + for (std::size_t i = 0; i < _name.size(); ++i) { + const char ch = _name[i]; + if (ascii_is_upper(ch)) { + if (i > 0 && _name[i - 1] != '_' && + (ascii_is_lower(_name[i - 1]) || + (i + 1 < _name.size() && ascii_is_lower(_name[i + 1])))) { + out.push_back('_'); + } + out.push_back(ascii_to_lower(ch)); + } 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(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(ascii_to_upper(ch)); + } + return out; + } + } + return std::string(_name); +} + +} // namespace rfl