Repository navigation
Upstream PR Queue (sorted by mergeability score) - #209
clockblocker wants to merge 63 commits into
Conversation
…name_str_view Fixes a v0.26.1 regression (433795b) where `rfl::internal::get_type_name_str_view<T>()` returned a `std::string_view` pointing into a destroyed temporary `StringLiteral<N>`, failing constant evaluation on every call. Dispatches directly to `cpp20::get_type_name_str_view<T>()` and `cpp26::get_type_name_str_view<T>()`. Upstream PR: munich-data-engineering#804 (176/176 CI green) Downstream receipts: - NVIDIA/cuda-quantum calls `rfl::internal::get_type_name_str_view<T>()` in a constexpr context: https://github.com/NVIDIA/cuda-quantum/blob/81ef20d9d4a1e0912a6dbc68637ece017e8fd324/cudaq/lib/Target/Reflection.h#L27-L31 - munich-data-engineering/sqlgen carries its own copy to avoid the dangling view: https://github.com/munich-data-engineering/sqlgen/blob/265b0a174b661c5905b874f97b064aecb4cded70/include/sqlgen/internal/get_type_name.hpp#L13-L44
PR Descriptions (Part 1/2)Tier 1 (Ranks 1–15) — Bug Fixes, Warning Cleanups & Thin-Header Wins1. fix(validation): fix rfl::OneOf broken .and_then().or_else() composition (#211)Problem
As a result, inputs matching an earlier branch were rejected, overlapping matches could slip through, and work grew exponentially ($O(2^N)$). using Age = rfl::Validator<
unsigned int,
rfl::OneOf<rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<10>>,
rfl::AllOf<rfl::Minimum<40>, rfl::Maximum<130>>>>;
using Overlap = rfl::Validator<int, rfl::OneOf<rfl::Minimum<0>, rfl::Maximum<10>>>;
// Before: Age(5) failed ("Expected 1 of 2... but 1 did"); Overlap(5) could pass
// After: succeeds iff exactly one branch matches
auto ok = Age::from_value(5); // ok (first branch matches)
auto bad = Overlap::from_value(5); // error (both branches match)Summary
2. fix(headers): replace remaining std::invoke_result with decltype for MSVC 14.52 (#805) (#210) (upstream #806)ProblemMSVC 14.52 rejects basic Upstream PR #794 replaced the struct Obj {
std::string a;
std::string b;
long c;
};
// Before (MSVC 14.52): C3539 in field_names_t.hpp
// After: compiles cleanly with direct decltype(...)
rfl::Result result = rfl::json::read<Obj>(R"({"a":"x","b":"y","c":10})");Summary
3. fix(json): reject uint64 > INT64_MAX instead of silently wrapping into signed integers (#132)ProblemThe JSON reader checked Any integer in struct Signed64 { int64_t value; };
// Before: silently wrapped to -1 (or INT64_MIN for INT64_MAX + 1)
// After: returns an explicit out-of-range rfl::Error
auto bad = rfl::json::read<Signed64>(R"({"value":18446744073709551615})"); // error
auto ok = rfl::json::read<Signed64>(R"({"value":9223372036854775807})"); // INT64_MAXSummary
Consumer Impact
4. feat(json-schema): emit oneOf for rfl::TaggedUnion in JSON Schema (#375) (#212)ProblemEvery Emitting JSON Schema struct Circle { double radius; };
struct Square { double width; };
auto schema = rfl::json::to_schema<rfl::TaggedUnion<"shape", Circle, Square>>();
// Before: {"anyOf":[{"$ref":"#/$defs/Circle__tagged"},{"$ref":"#/$defs/Square__tagged"}],...}
// After: {"oneOf":[{"$ref":"#/$defs/Circle__tagged"},{"$ref":"#/$defs/Square__tagged"}],...}Summary
Consumer Impact
5. fix(headers): eliminate -Wextra, -Wextra-semi, -Wsign-conversion, and -Wunused-parameter warnings (#55) (upstream #803)ProblemPublic headers currently emit Consumers building with Summary
Consumer Impact
6. fix(parsing): gate <expected> include behind <version> feature test to avoid MSVC STL4038 (#213)Problem
Under MSVC // Trigger: MSVC 19.44 /std:c++20 /WX with #include <rfl.hpp>
// Before: warning STL4038: The contents of <expected> are available only with C++23 or later.
// After:
#include <version>
#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L && \
__has_include(<expected>)
#include <expected>
#endifSummary
7. feat(enums): accept std::string_view in rfl::string_to_enum (#565) (#76) (upstream #802)Problem
Its numeric fallback also relied on using namespace std::string_view_literals;
enum class Color { red = 1, green = 2, blue = 3 };
enum class Flags64 : uint64_t { flag_a = 1ULL << 0 };
auto c = rfl::string_to_enum<Color>("green"sv); // ok: 0 allocs
auto f = rfl::string_to_enum<Flags64>("flag_a|1099511627776"sv); // ok: 64-bit flag
auto x = rfl::string_to_enum<Color>("1abc"sv); // error: trailing junkSummary
Consumer Impact
8. perf(headers): trim <functional>, <sstream>, and unused <map> from thin headers (#135)ProblemThin schema headers transitively pulled in That added ~40,000 preprocessed lines (~350 ms cold compile time per TU) to translation units that deliberately avoid pulling in format parsers. // Trigger: thin schema header (no <rfl/json.hpp>)
#include <rfl/Result.hpp>
#include <rfl/comparisons.hpp>
#include <rfl/PatternValidator.hpp>
#include <rfl/Size.hpp>
// Impact: ~40,000 fewer preprocessed lines (~350 ms cold compile time per TU)Summary
Consumer Impact
9. fix(capnproto): support rfl::Vectorstring in struct fields and unions (#214)ProblemCap'n Proto already supported Any struct field or union branch carrying struct Packet {
rfl::Vectorstring payload;
rfl::Variant<int, rfl::Vectorstring> body;
};
// Before: compile error in Writer::add_value_to_object / add_value_to_union
// After: serializes as capnp::Data::Reader and round-trips identically to rfl::Bytestring
const auto bytes = rfl::capnproto::write(Packet{...});Summary
10. perf(parsing): use emplace_hint(end()) for ordered maps in MapReader (#215)Problem
Ordered // Before: O(log N) tree search on every entry of a sorted std::map payload
map_->emplace(std::move(*res));
// After: O(1) amortized insertion via emplace_hint(end()) for ordered maps (key_compare)
if constexpr (requires(MapType& _map, std::pair<KeyType, ValueType>&& _pair) {
typename MapType::key_compare;
_map.emplace_hint(_map.end(), std::move(_pair));
}) {
map_->emplace_hint(map_->end(), std::move(*res));
} else {
map_->emplace(std::move(*res));
}Summary
11. perf(capnproto): typed capnp::List<T> fast path for numeric vectors and arrays (#216)ProblemReading and writing Per-element boxing and struct SensorPacket {
std::vector<int32_t> samples;
std::array<float, 9> covariance;
};
// Before: per-element DynamicList -> DynamicValue boxing + Result wrapping
// After: schema-checked capnp::List<T> typed fast path (falls back on width mismatch)
const auto bytes = rfl::capnproto::write(packet);
const auto parsed = rfl::capnproto::read<SensorPacket>(bytes);Summary
12. fix(yaml): guard rfl::yaml::Reader against recursive aliases and out-of-bounds literal marks (#72) (upstream #801)ProblemCyclic YAML anchors ( Separately, literal-block detection indexed # Before: stack-overflow crash on cyclic alias
# After: returns rfl::Error ("Recursive YAML alias detected.") at path ["child"]
&self
name: loop
child: *selfSummary
Consumer Impact
13. fix(yaml): reject negative-to-unsigned wraparound, narrow integer overflow, and uint64_t write wraparound (#217)ProblemYAML reads parsed every integer as Negatives silently wrapped into unsigned fields, oversized numbers truncated in narrow types, and struct Config { uint8_t port; uint64_t id; };
// Before:
rfl::yaml::read<Config>("port: -1\nid: 0\n"); // Ok: port == 255
rfl::yaml::read<Config>("port: 300\nid: 0\n"); // Ok: port == 44
rfl::yaml::write(Config{80, UINT64_MAX}); // emits "id: -1"
// After:
rfl::yaml::read<Config>("port: -1\nid: 0\n"); // Error: Could not cast to uint.
rfl::yaml::read<Config>("port: 300\nid: 0\n"); // Error: Integer is out of range for the target type.
rfl::yaml::write(Config{80, UINT64_MAX}); // emits "id: 18446744073709551615"Summary
Consumer Impact
14. fix(xml): fix get_field_from_array index increment and write() indent forwarding (#71) (upstream #800)ProblemReading any XML array element past index Separately, // XML: <root><item>a</item><item>b</item><item>c</item></root>
// Before:
reader.get_field_from_array(1, arr); // Error: "Index 1 of of bounds."
rfl::xml::write(person, " "); // ignores " "; always uses default 4-space indent
// After:
reader.get_field_from_array(1, arr); // Ok: "b" (index 3 -> "Index 3 out of bounds.")
rfl::xml::write(person, " "); // indents with 2 spaces ("" produces compact XML)Summary
15. fix(env): use getenv_s and _dupenv_s under _MSC_VER in rfl::env::Reader (#218)Problem
On Windows MSVC and Summary
Tier 2 (Ranks 16–35) — Correctness Fixes, Algorithmic Wins, Licensing Docs & CLI/JSON Helpers16. fix(yaml): return error on non-scalar mapping keys instead of silently skipping (#219)ProblemReading a YAML mapping caught key-conversion exceptions with That caused silent data loss in maps and struct Config { std::string name; };
// Before: silently skips "[1, 2]: foo" even under NoExtraFields
rfl::yaml::read<Config, rfl::NoExtraFields>("name: ok\n[1, 2]: foo\n"); // Ok: {name: "ok"}
// After: rejects non-scalar keys with an explicit error (and path when nested)
rfl::yaml::read<Config, rfl::NoExtraFields>("name: ok\n[1, 2]: foo\n");
// Error: YAML mapping key must be a scalar.Summary
Consumer Impact
17. fix(parsing): prevent std::terminate() at noexcept validation, map-key, and default boundaries (#220)ProblemSeveral A throwing custom validator worked alone, but aborted via struct RejectNeg {
static rfl::Result<int> validate(int v) {
if (v < 0) throw std::runtime_error("negative value rejected");
return v;
}
};
struct S { rfl::Validator<int, RejectNeg, OtherValidator> value; };
// Before: AllOf::validate_impl is noexcept with no try/catch
rfl::json::read<S>(R"({"value":-1})"); // std::terminate()!
// After: returns rfl::Error cleanly (including non-std::exception throws)
rfl::json::read<S>(R"({"value":-1})"); // Error: "negative value rejected"Summary
18. fix(parsing): capture input keys matching ExtraFields member name (#221)ProblemStruct deserialization matched incoming keys against every C++ member, including the As a result, a payload key literally named after that member (like struct Payload {
int a = 0;
rfl::ExtraFields<rfl::Generic> extra_fields;
};
// Before: "extra_fields" collides with the C++ member name and fails to parse
rfl::json::read<Payload>(R"({"a":42,"extra_fields":"literal_value","other":9})"); // Error!
// After: captured into extra_fields alongside other dynamic keys
// parsed.extra_fields.at("extra_fields") == "literal_value"
// parsed.extra_fields.at("other") == 9Summary
19. perf(strings): fix O(N^2) replace_all and split and empty-needle infinite loops (#222)ProblemInternal string helpers Both helpers also entered an infinite loop until OOM whenever given an empty pattern or delimiter. // Before: O(N^2) tail shifts on every match; empty needle loops forever
while ((pos = str.find(_from, pos)) != std::string::npos) {
str.replace(pos, _from.length(), _to);
pos += _to.length();
}
// After: O(N) forward-cursor slices into a reserved buffer; empty needle guarded
if (_from.empty() || _from == _to) return _str;
// ... result.append(_str, pos, found - pos); result.append(_to);Summary
20. perf(capnproto): positional DynamicStruct writes, hoisted map handles, and length-aware Text (#223)Problem
It also passed Summary
21. fix(capnproto): return rfl::Error on Cap'n Proto reader exceptions (#224)Problem
Because one const std::vector<char> truncated = {0x01, 0x02, 0x03};
// Before: uncaught kj::Exception (or std::terminate() on the noexcept container+schema overload)
// After: returns rfl::Error with the KJ exception description
const rfl::Result<Person> res = rfl::capnproto::read<Person>(truncated);Summary
22. docs(licensing): add THIRD_PARTY_NOTICES for vendored dependencies (#225)Problem
Enterprise consumers have to scrape individual headers and
Summary
OSS consumers
23. fix(enums): backport enchantum MSVC 64-bit enum cast suffix fix (#226)ProblemOn MSVC, Vendored enum class Signed64NoZero : int64_t { alpha = 1, beta = 2 };
// Before (Windows MSVC 19.44, default bundled dependencies):
rfl::enum_to_string(Signed64NoZero::alpha); // "lpha" (silent wire-format corruption!)
rfl::string_to_enum<Signed64NoZero>("alpha"); // Error!
// After:
rfl::enum_to_string(Signed64NoZero::alpha); // "alpha"
rfl::string_to_enum<Signed64NoZero>("alpha"); // Ok: Signed64NoZero::alphaSummary
24. fix(json-schema): flatten nested anyOf for optional variants and rfl::Generic (#227)ProblemOptional variants ( That redundant wrapper clutters generated specs and trips up editor and OpenAPI tooling. // Before (std::optional<std::variant<int, std::string>>):
{ "anyOf": [{ "anyOf": [{ "type": "integer" }, { "type": "string" }] }, { "type": "null" }] }
// After:
{ "anyOf": [{ "type": "integer" }, { "type": "string" }, { "type": "null" }] }Summary
OSS consumers
25. feat(cli): add rfl::cli::usage to generate usage and help text (#692) (#23)Problem
As structs evolve, documented flag names, short aliases, and required arguments drift out of sync with the actual parser. enum class LogLevel { debug, info, warn };
struct Config {
rfl::Positional<rfl::Description<"Input path", std::string>> input_file;
rfl::Short<"p", rfl::Description<"Listen port", int>> port;
rfl::Description<"Minimum log level", std::optional<LogLevel>> log_level;
};
const std::string help = rfl::cli::usage<Config>("app", true).value();Summary
26. feat(json): add first-class rfl::json read and write flag constants (#80)Problem
Callers needing JSONC comments, trailing commas, two-space indentation, or trailing newlines had to leak raw // Before
auto cfg = rfl::json::read<Config>(text, YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS);
auto out = rfl::json::write(cfg.value(), rfl::json::pretty | YYJSON_WRITE_PRETTY_TWO_SPACES);
// After
auto cfg = rfl::json::read<Config>(text, rfl::json::jsonc);
auto out = rfl::json::write(cfg.value(), rfl::json::pretty_two_spaces | rfl::json::newline_at_end);Summary
OSS consumers
27. perf(parsing): isolate per-field helpers in NamedTupleParser, destructors, and flatten (#228)ProblemPer-field write, schema, missing-field, and destructor helpers lived inside templates parameterized on the entire struct field pack. An Summary
28. perf(tuple): replace O(N^2) calculate_positions fold and per-index Tuple lambdas (#229)ProblemEvery It also gave trivially destructible views (including // Before: O(N^2) recursive operator+ fold + 5 per-index lambdas + non-trivial ~Tuple()
return (Positions<0>{} + ... + PositionWrapper<Types>{}).to_array();
// After: O(N) consteval offset array + lockstep pack folds + trivial ~Tuple()
~Tuple() requires(std::is_trivially_destructible_v<Types> && ...) = default;Summary
OSS consumers
29. feat(capnproto): add capnp::ReaderOptions overloads and unpacked flat-array read/write (#230)Problem
It also exposed only packed wire serialization ( // Custom traversal/nesting limits on any read or read_unpacked overload:
capnp::ReaderOptions opts;
opts.traversalLimitInWords = 64ULL * 1024 * 1024; // 512 MiB
const auto large = rfl::capnproto::read<Payload>(bytes, opts);
// Unpacked flat-array round-trip (skips byte packing/unpacking):
const kj::Array<capnp::word> words = rfl::capnproto::write_unpacked(payload);
const auto unpacked = rfl::capnproto::read_unpacked<Payload>(words, opts);Summary
30. perf(internal): add apply_to_fields and avoid NamedTuple in HasDefaultVal (#126)ProblemChecking whether an aggregate struct contains an The trait only inspects field types and never uses field names, so all of that template work is wasted on every reflected aggregate. Summary
31. fix(error): preserve structured Error::details() paths in FieldVariantReader and ParserTaggedUnion (#231)ProblemAfter structured error paths landed in PR #766, two variant parsers still dropped path segments. Externally-tagged field variants discarded nested field paths when wrapping inner errors, and // 1. Externally-tagged field variant: {"circle":{"radius":-5}}
// Before: err.details()[0].path == {} (nested path lost)
// After: err.details()[0].path == {"circle", "radius"}
// 2. Tagged union with unknown or missing tag: {"shape":"Triangle","radius":1}
// Before: err.details()[0].path == {} (discriminator omitted)
// After: err.details()[0].path == {"shape"}Summary
32. perf(generic): eliminate O(N*D) subtree deep copies in Generic construction, write, and is_empty (#232)ProblemConstructing, checking That triggered cascading deep copies across the subtree, turning linear tree operations into // Before: O(N*D) — deep-copies the full subtree at every nesting level
Parser<R, W, Generic::ReflectionType, P>::write(w, node.reflection(), parent);
// After: O(1) node.is_null() + zero-copy const-ref write + rvalue move ctors
ParserGeneric<R, W, P>::write(w, node, parent); // visits node.variant() by const&Summary
OSS consumers
33. perf(internal): use O(log N) exponential + binary search in cpp20::num_fields (#233)ProblemIn C++20 mode, On wide structs (20–36+ fields) or translation units reflecting hundreds of structs, linear SFINAE recursion inflates template depth and compile time. Summary
OSS consumers
34. perf(parsing): isolate per-field helpers in ViewReader and ViewReaderWithDefault (#234)Problem
Because every field's mangled symbol repeated the entire enclosing struct, wide structs suffered Summary
35. feat(enums): add rfl::TransformEnumNames processors (#731) (#235)Problem
Codebases with enum class CostModel { t_count, two_qubit_gate_count, gate_count };
struct Config { CostModel cost_model; };
const auto json = rfl::json::write<rfl::EnumSnakeCaseToKebabCase>(
Config{.cost_model = CostModel::two_qubit_gate_count});
// {"cost_model":"two-qubit-gate-count"}
const auto cfg = rfl::json::read<Config, rfl::EnumSnakeCaseToKebabCase>(json).value();Summary
OSS consumers
|
PR Descriptions (Part 2/2)Tier 3 (Ranks 36–62) — Algorithmic Optimizations, Reflection APIs, Schema Processors & CMake Packaging36. feat(reflection): add public rfl::type_name<T>() and rfl::type_name_v<T> (#236)Problem
Callers needing a zero-allocation #include <rfl/type_name.hpp>
struct SampleStruct { int a; double b; };
constexpr std::string_view v = rfl::type_name_v<SampleStruct>;
constexpr std::string_view f = rfl::type_name<SampleStruct>();
static_assert(f == v && f.find("SampleStruct") != std::string_view::npos);Summary
OSS consumers
37. perf(schema): fast-path scalar defaults in NamedTupleParser::to_schema (#237)ProblemEvery That pulled in heavy template instantiations just to convert trivial scalar defaults into struct Config {
rfl::DefaultVal<bool> enabled = true;
rfl::DefaultVal<int> retries = 3;
rfl::DefaultVal<std::optional<double>> timeout = 1.5;
rfl::DefaultVal<std::string> host = "localhost";
};
// Before: instantiates rfl::to_generic<ProcessorsType> + generic::Writer per field
// After: constructs rfl::Generic directly for scalars and std::optional<Scalar>Summary
38. perf(cli): lower_bound prefix skipping in cli::Reader, O(F) usage positionals, and O(F) option/usage symbols (#238)Problem
Meanwhile, option and usage collection instantiated per-field helpers carrying the full // Before: linear prefix scans + per-field templates coupled to the full NamedTuple
std::set<std::string> visited; // rescans every descendant key at each depth
// After: lower_bound subtree jumps + constexpr descriptor tables decoupled from NamedTuple
sub_prefix.back() = after_separator; // '.' + 1 == '/'
it = _obj.args->lower_bound(sub_prefix);Summary
39. perf(named-tuple): O(1)-instantiation find_index, non-recursive find_extra_fields, and fold-based struct traits (#239)ProblemCore On wide aggregates, that template explosion drove significant compile latency and peak RSS across downstream builds. // Before: O(N^2) FieldWrapper operator| folds + recursive find_extra_fields + ptr_tuple_t
find_matching_field(FieldWrapper<tuple_element_t<_is, Fields>, _field_name, _is>{}...)
// After: single FindIndexImpl consteval scan + fold-based traits via apply_to_fields
FindIndexImpl<std::remove_cvref_t<Fields>>::find(_field_name.string_view());Summary
OSS consumers
40. perf(processors): eliminate redundant Tuple round-trip copies in case-transform processors (#240)ProblemAll five field-casing processors rebuilt a That triggered redundant copies and moves on every field and blocked move-only fields altogether. // Before (16-field rvalue): 32 copies + 80 moves via .transform() -> fields() -> make_from_tuple
return _named_tuple.transform([](const auto& _f) { return handle_one_field(_f); });
// After (16-field rvalue): 0 copies + 16 moves, constructing directly from values()
return NewNamedTuple(from_values_tuple, std::move(_named_tuple.values()));Summary
OSS consumers
41. perf(parsing): peel transparent metadata wrappers before Parser read, write, and to_schema (#260)ProblemEvery distinct string literal inside // Before (N distinct documentation strings -> N separate Parser::read/write/to_schema instantiations):
struct Config {
rfl::Description<"Max worker threads", int> threads; // Parser<..., Description<"Max worker...", int>>
rfl::Description<"RPC timeout in ms", int> timeout_ms; // Parser<..., Description<"RPC timeout...", int>>
};
// After (metadata peeled at the field boundary -> 1 shared Parser<..., int> instantiation):
// - read: parses CoreType (int), then wraps into Description/Deprecated/Rename/Short at slot assignment
// - write: unwraps to const CoreType& before calling Parser<..., CoreType>::write
// - to_schema: builds CoreType schema once, then attaches runtime Type::Description / Type::Deprecated nodes
Summary
42. feat(json-schema): add rfl::IntegerBounds opt-in processor (#683) (#241)ProblemJSON Schema emits bare Editors and validators then accept negative or out-of-range values for fields like struct NetConfig { uint16_t port; };
// Before: "port": {"type":"integer"}
auto s = rfl::json::to_schema<NetConfig, rfl::IntegerBounds>();
// After: "port": {"type":"integer","minimum":0,"maximum":65535}Summary
OSS consumers
43. fix(schema): cast char to unsigned char for std::isalnum and add missing includes in make_type_name.hpp (#242)Problem
On platforms where // Before (include/rfl/parsing/make_type_name.hpp, missing <cctype> & <string>):
for (auto& ch : _str) {
ch = std::isalnum(ch) ? ch : '_'; // UB / MSVC Debug CRT assert when ch < 0
}
// After:
for (auto& ch : _str) {
ch = std::isalnum(static_cast<unsigned char>(ch)) ? ch : '_';
}Summary
44. feat(reflection): expose public rfl::StringLiteral header and constexpr helpers (#243)Problem
Because the header lived under #include <rfl/StringLiteral.hpp>
constexpr auto kDesc = rfl::StringLiteral("Display ") + rfl::StringLiteral("name");
struct User {
rfl::Rename<rfl::StringLiteral("user_") + rfl::StringLiteral("name"),
rfl::Description<kDesc, std::string>> name;
};
static_assert(rfl::Literal<"v1">::name_view() == "v1");Summary
OSS consumers
45. perf(literal): O(1) name lookup, O(log N) string lookup, and O(1)-instantiation contains_any/all in rfl::Literal (#244)Problem
On wide literal sets and // Before: O(N) linear folds + O(N*M) set-op template folds + Tuple.hpp include
// After: O(1) kNames[value_] + O(log N) constexpr-sorted binary search (N > 8)
// + O(1)-instantiation consteval set ops; drops Tuple.hpp includeSummary
OSS consumers
46. perf(formats): O(1) Cap'n Proto union discriminant, O(log M) flexbuf/cbor/ubjson object lookup, and O(D) BSON Writer stack (#245)ProblemFour binary format backends had linear lookup bottlenecks: Cap'n Proto scanned union fields linearly, while FlexBuffers, CBOR, and UBJSON scanned object keys linearly on every lookup. In addition, // Before: O(A) Cap'n Proto scan, O(M) FlexBuffers/CBOR/UBJSON key loops, O(N) BSON Box vector
for (auto field : _union.val_.getSchema().getFields()) { if (_union.val_.has(field)) ... }
// After: O(1) which()+getIndex(), O(log M) binary search / find(), O(D) deque stack popped on end_object
KJ_IF_MAYBE(field, _union.val_.which()) { return std::make_pair(*field, size_t(field->getIndex())); }Summary
47. perf(internal): O(1) nth_element/nth_element_t, single-bind C++20 get_field_names, and guaranteed O(N log N) no_duplicate_field_names (#246)ProblemC++20 struct reflection ran On wide aggregates, that redundant work inflated both compile time and peak RSS. Summary
OSS consumers
48. feat(json-schema): add rfl::VariantsAsOneOf opt-in processor (#375) (#247)ProblemUntagged Consumers with mutually exclusive variants have no way to opt into stricter // Default: {"anyOf":[{"type":"integer"},{"type":"string"}]}
auto s = rfl::json::to_schema<rfl::Variant<int, std::string>, rfl::VariantsAsOneOf>();
// After: {"$schema":"...","oneOf":[{"type":"integer"},{"type":"string"}],"$defs":{}}Summary
OSS consumers
49. perf(parsing): short-circuit dispatch and symbol isolation for ParserVariant, ParserRflVariant, and schemaful::VariantReader (#248)ProblemUntagged Field-variant writes also round-trip through a temporary pointer variant, and Summary
OSS consumers
50. perf(parsing): add FieldNameLookup cursor-hint and binary-search field dispatch (#249)ProblemDeserializing structs with more than four fields expands a linear fold that compares every field name in sequence. That lookup code is duplicated across every format, processor, and field wrapper combination, bloating object files and compile times. Summary
51. perf(parsing): O(log K) lookup and symbol isolation for FieldVariantReader, FieldVariantParser, and ParserTaggedUnion (#250)ProblemField-variant and tagged-union parsers scan all They also check duplicate tags via Summary
OSS consumers
52. perf(parsing): O(1) TupleReader dispatch, strip-name/destructor symbol isolation, stack found_ in ViewReaderWithDefault, and O(1) VectorParser::write size (#251)ProblemTuple reads dispatch elements via an Stripped-field readers and destructors also emit Summary
OSS consumers
53. fix(schema): unwrap Type::Description and Type::Deprecated in Avro and Cap'n Proto helpers (#252)ProblemWhen a custom type wraps its Three Avro and Cap'n Proto helper predicates fail to unwrap those nodes, misclassifying named records and literal enums during schema generation. struct DescribedRetries {
using Inner = rfl::NamedTuple<rfl::Field<"retries", int>>;
using ReflectionType = rfl::Description<"Nested retry settings", Inner>;
};
struct DescribedColor {
using ReflectionType = rfl::Description<"Primary color", rfl::Literal<"red", "blue">>;
};
// Before: Avro emits anonymous "unnamed_0" records; Cap'n Proto emits invalid Map(Enum)
// After: Avro emits named "DescribedRetries"; Cap'n Proto emits ScalarMapSummary
54. feat(enums): add rfl::EnumNames<E> per-enum wire-name trait (#106) (#253)ProblemWhole-enum casing processors cannot express non-identifier wire strings like Consumers end up maintaining boilerplate enum class OptLevel { no_opt, cxx_standard };
template <>
struct rfl::EnumNames<OptLevel> {
static constexpr auto transform = rfl::EnumNameTransform::snake_to_kebab;
static constexpr std::array<rfl::EnumOverride<OptLevel>, 1> overrides = {{
{OptLevel::cxx_standard, "c++20"},
}};
};
// no_opt -> "no-opt", cxx_standard -> "c++20" across JSON, YAML, XML, CLI, and JSON Schema
auto names = rfl::get_enum_wire_names<OptLevel>();Summary
OSS consumers
55. feat(json): add rfl::json::Raw for passthrough raw JSON values (#368) (#67)ProblemPassing an opaque JSON subtree through a reflected struct forces a bad trade-off between
struct RpcRequest {
std::string method;
rfl::json::Raw params;
};
auto req = rfl::json::read<RpcRequest>(R"({"method":"hover","params":{"line":10}})").value();
auto raw = req.params.str(); // R"({"line":10})"
auto out = rfl::json::write(req); // emitted verbatim, not escaped
auto v = rfl::json::Raw::from_string(R"({"ok":true})").value();
auto pre = rfl::json::Raw::from_trusted_string(rfl::json::write(obj));Summary
OSS consumers
56. perf(variant): inline switch-based Variant::visit, O(1) get_if/element_index, and O(K) TaggedUnion::operator== (#254)Problem
Meanwhile, Summary
OSS consumers
57. build(tests): respect CMAKE_BUILD_TYPE flags, expand format PCHs, and clean unity builds (#261)Problem
Meanwhile, # Standard CMake flags now work as expected (zero new project options):
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DREFLECTCPP_BUILD_TESTS=ON
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON \
-DCMAKE_UNITY_BUILD=ON -DCMAKE_UNITY_BUILD_BATCH_SIZE=16
Summary
58. perf(tuple): single-pass O(N) tuple_cat, move_from_tuple fast path, wrap_in_fields, and concat_literals (#255)Problem
Meanwhile, Summary
OSS consumers
59. build(cmake): subproject ergonomics, CMake 3.20 support, warning/linter isolation, and FetchContent docs (#256)ProblemEmbedding It also requires CMake 3.23+ (breaking RHEL 8, Ubuntu 22.04, and ROS 2 Humble) and trips strict parent # Works out of the box on CMake >= 3.20 (Linux, macOS, Windows MSVC / clang-cl)
# without setting REFLECTCPP_USE_VCPKG=OFF, REFLECTCPP_INSTALL=OFF, or global -w:
FetchContent_Declare(reflectcpp
GIT_REPOSITORY https://github.com/munich-data-engineering/reflect-cpp.git
GIT_TAG v0.26.1
GIT_SUBMODULES "")
FetchContent_MakeAvailable(reflectcpp)
target_link_libraries(my_app PRIVATE reflectcpp::reflectcpp)Summary
OSS consumers
60. perf(schema): eliminate O(N^2) Object::operator[] schema insertions and unnecessary schema AST copies (#257)ProblemSchema builders insert fields via In addition, Summary
OSS consumers
61. build(cmake): isolate bundled yyjson visibility, support external yyjson, and add reflectcpp::headers target (#258)ProblemLinking static Header-only and # 1. Reuse an existing external yyjson target without disabling bundled ctre/enchantum
set(REFLECTCPP_USE_BUNDLED_YYJSON OFF)
set(REFLECTCPP_YYJSON_TARGET my::yyjson)
set(REFLECTCPP_HIDDEN_VISIBILITY ON) # optional: also hide static rfl:: symbols
add_subdirectory(reflect-cpp)
# 2. Header-only / OBJECT libraries consume headers without linking compiled objects
target_link_libraries(my_obj_lib PUBLIC reflectcpp::headers)
target_link_libraries(my_plugin PRIVATE my_obj_lib reflectcpp::reflectcpp) # 0 leaked yyjson_* in nm -DSummary
OSS consumers
62. perf(internal): O(N) remove_fields and balanced define_* type builders (#259)ProblemThe That Summary
OSS consumers
|
For Agents — Queue Scoring, Commit Metadata & Verification
1. Mergeability Scoring Rubric (0–100, Cutline
|
| Axis | Points | Criteria |
|---|---|---|
| S — Size & Blast Radius | 0–30 | Prod LOC, file count, header/core coupling, isolation from unrelated subsystems. |
| M — Maintainer Buy-In | 0–30 | Open upstream issue/endorsement, direct precedent PRs, alignment with maintainer priorities (compile time, zero-throw Result, backwards compat, one problem per PR). |
| D — Downstream Pain / Evidence | 0–25 | Verified real-world consumer workarounds, live bugs, or measured N=3 interleaved A/B compile-time / runtime wins. |
| R — API & Maintenance Risk | 0–15 | Backwards compatibility, header hygiene (CHECK_HEADERS), strict-warning cleanliness, future maintenance footprint. |
2. Full Queue Index (Bottom → Top)
3. Open Follow-Ups
- None.
4. Parked discuss/ssot Scores (Below < 65 Cutline)
| Item | Score | Why Parked on discuss/ssot |
|---|---|---|
rfl::DefaultTag<Discriminator, Tag> |
60 | No upstream issue; #455 precedent preferred std::variant<TaggedUnion<...>, Fallback>; global discriminator collision & cli/env/msgpack contract gaps. |
rfl::Int64AsString |
58 | Design questions: processor-wide vs per-field wrapper, strict bare-number rejection, LP64 vs LLP64 sizeof(long) >= 8 portability trap, validator schema interaction. |
rfl::NoDuplicateKeys |
55 | No upstream issue; 77-line hand-rolled FNV-1a table in json/Reader.hpp, unapproved Reader-vs-ObjectReader contract, toml++ mismatch. (Standalone YAML non-scalar key bugfix from #160 extracted into 6fc44d73.) |
rfl::AddNullFields |
52 | Overlaps existing rfl::NoOptionals (write-side explicit nulls) and rfl::Nullable<T>; undocumented in processors.md. |
rfl::ErrorKind + Error::code() |
50 | 41 + 18 files, enum taxonomy & 28 hardcoded wire codes, implicit static V::code opt-in, changes ErrorDetail::operator==. (Standalone OneOf, noexcept, and Error::details() bugfixes extracted into 91de7aa3, 610ead4c, 7caae912.) |
<rfl/nlohmann.hpp> |
50 | Second JSON backend adding third-party dependency across CMake/vcpkg/Conan/CI matrices. |
rfl::MaxDepth<N> |
50 | thread_local global counter (DLL/coroutine/nested-read hazards), NTTP template bloat, silent non-enforcement on recursive 3P parsers (yaml-cpp, pugixml, toml++). |
Remove dev-only vcpkg git submodule (#139) |
49 | Repo/CI workflow policy change (deletes .gitmodules + vcpkg gitlink, modifies .github/workflows/* & setup-vcpkg, introduces vcpkg-configuration.json) requiring upstream maintainer sign-off; FetchContent consumers already have GIT_SUBMODULES "" documented in f93d1a18. |
rfl::Metadata<T> + SchemaName<T> / SchemaExtension<T> |
45 | Three out-of-band specialization traits, silent typo misses, new shared schema IR node (Annotated), ExtraFields on every JSON schema subtype. (Standalone isalnum UB & Avro/Cap'n Proto unwrap bugfixes extracted into d240a041, 8f506eaf.) |
rfl::Alias |
45 | 31 files across case-transform processors & C++20/C++26 reflection; wrapper vs trait/processor design needs sign-off. |
DefaultIfMissing schema defaults (#396) |
41 | Maintainer flagged #396 as "tricky" and suggested rfl::Generic on #680; 971-LOC dual wrapper-walking traits + breaking output change on DefaultIfMissing. |
rfl::Nullable<T> / rfl::TriState<T> |
40 | 435-LOC new vocabulary wrappers overlapping std::optional / NoOptionals / AddNullFields. |
rfl::DefaultIfNull (#796) |
33 | Zero maintainer comments on #796, 19 prod files, 3rd wrapper-walking trait (is_nullable.hpp), #786-class sibling-field behavior cliff. |
is_safe_default_constructible |
32 | 481-line zero-caller wrapper walker + 10 public wrapper default-ctor template rewrites. |
5. CI & Sanitizer Checks
Full compile-time & runtime benchmark receipts live in the PR description above and refl-cpp-workbench#34 (#44–#50).
upstream-queue @ 3d33e721 — 61 active + 1 merged (d1f84224) = 62 commits on branch.
| Check | Scope | Result |
|---|---|---|
| Windows standalone & multi-format matrix | VS 2022 MSVC 19.44 + clang-cl 19.1.5, 6 configs + 9-format static + 8-format shared |
607/607 standalone, 1,038/1,038 static, 980/980 shared PASS, 0 warnings. |
Windows queue-tests/ + CMake + 4 OSS consumers |
Ninja MSVC & clang-cl, CMake 3.22 / 4.4 |
231/231 PASS each, install/B1–B5 PASS, sqlgen 96/96, cppcheck PASS, ccache 297/297, slang-server 557/563 (baseline parity). |
Linux queue-tests/ (12 formats) & header checks |
Clang 23.1.6 & GCC 13.4.0, -Werror |
234/234 PASS on both, 463/463 CHECK_HEADERS + 288/288 strict modified headers PASS. |
macOS arm64 suite & queue-tests/ |
Apple M1, macOS 27.2.1, Apple Clang 17 & GCC 16.2 (2026-12-06) |
722/722 reflect-cpp tests (0 warnings), 174/174 Clang / 172/172 GCC queue-tests/ PASS. |
ASan + UBSan + cuda_quantum_canary |
Clang 23.1.6 & GCC 13.4.0, 10 formats | 1,217/1,217 valid tests PASS, 0 rfl errors/leaks, 0 leaked yyjson_* symbols in libcudaq_canary_plugin.so. |
| Tracked A/B (macOS arm64, AppleClang 17.0.0, Release) | Apple M1, macOS 27.2.1, 290bdb24 → 3d33e721, 2026-12-06 |
5/5 consumers PASS, 0 regressions — rollup · synthetic, reflect-cpp-self, sqlgen, fanuc-libs, slang-server |
Merged Upstream (Ex-Queue PRs)
|
04e6f0a to
7bfe63c
Compare
Replaces the chained `.and_then(...).or_else(...)` recursion in `rfl::OneOf::validate_impl` with an explicit check so each branch is evaluated exactly once. Previously: 1. When any non-last branch passed and a later branch failed, the inner error fell into the outer `.or_else()` handler, rejecting valid values (even printing "Expected exactly 1 out of 2 validations to pass, but 1 of them did"). 2. When multiple branches passed simultaneously, the terminal failure fell into the outer `.or_else()`, appending to a moved-from `_errors` vector and wrongly accepting invalid inputs. 3. Passing `std::move(_errors)` into `.and_then()` and then mutating `_errors` in `.or_else()` caused use-after-move and O(2^N) re-evaluation. Also removes a stray inline review comment left in `OneOf.hpp` and adds regression tests for first-branch match, multi-branch overlap, and zero-branch failure in `tests/json/test_one_of.cpp`.
…o signed integers In yyjson, non-negative integers in [0, UINT64_MAX] have subtype `YYJSON_SUBTYPE_UINT` (`uni.u64`), yet `yyjson_is_int()` matches both `UINT` and `SINT` and `yyjson_get_sint()` reads `uni.i64` directly. Values in `(INT64_MAX, UINT64_MAX]` therefore read an inactive union member and silently wrapped to negative `int64_t` (e.g. `UINT64_MAX` became `-1`), bypassing the narrow integer range check added in munich-data-engineering#746 and corrupting `rfl::Generic`. Check `yyjson_is_uint()` first with an unsigned upper-bound comparison against `std::numeric_limits<Target>::max()` before checking `yyjson_is_sint()`. Follow-up to: munich-data-engineering#746 Downstream context: mixed signed/unsigned 64-bit JSON schemas in - hudson-trading/slang-server: https://github.com/hudson-trading/slang-server/blob/1b413a4655877a55b3f8a450c23e4ba6c2bf4267/include/Config.h#L59-L60 - openmoq/moqx: https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/src/config/loader/ParsedConfig.h
…nich-data-engineering#375) Alternatives of an `rfl::TaggedUnion` carry mutually exclusive discriminator tags, so a valid document can match at most one branch. Marks the internal `schema::Type::AnyOf` node with a defaulted `mutually_exclusive_ = false` flag and emits `oneOf` in `src/rfl/json/to_schema.cpp` for `rfl::TaggedUnion` (including under `rfl::AddTagsToVariants`). Untagged `rfl::Variant`, `std::variant`, `std::optional`, Avro, and Cap'n Proto schemas remain unchanged. Refs: munich-data-engineering#375 (Maintainer: "you are right that oneOf is more accurate. We should change it.") Downstream receipt: - games-on-whales/wolf defines `RunnerTypes = rfl::TaggedUnion<"type", AppCMD, AppDocker>` (https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/src/moonlight-server/events/events.hpp#L46) and its committed OpenAPI 3.1 spec currently emits inaccurate `anyOf` at 4 sites: https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/docs/modules/dev/partials/spec.json#L939-L948
… -Wunused-parameter warnings Cleans compiler warnings across 14 public headers (+22/-18 LOC) using unnamed unused parameters (matching munich-data-engineering#582) with zero API or behavioral changes so consumers building with strict flags (`-Wall -Wextra -Werror -pedantic -Wconversion -Wsign-conversion -Wextra-semi`) get clean builds. Upstream PR: munich-data-engineering#803 Downstream receipts: - hudson-trading/slang-server suppresses reflect-cpp warnings in 4 places: https://github.com/hudson-trading/slang-server/blob/1b413a4655877a55b3f8a450c23e4ba6c2bf4267/CMakeLists.txt#L317-L321 - games-on-whales/wolf wraps FetchContent(reflect-cpp) with `add_compile_options(-w)`: https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/src/moonlight-server/CMakeLists.txt#L38-L45 - munich-data-engineering/sqlgen, openmoq/moqx, and FANUC-CORPORATION/fanuc_driver all compile with `-Wall -Wextra -Wpedantic`.
…o avoid MSVC STL4038
On MSVC in C++20 mode (/std:c++20), <expected> exists on disk so bare
`#if __has_include(<expected>)` evaluates true and emits warning
STL4038 ("The contents of <expected> are available only with C++23 or
later.") on every translation unit.
Include the C++20 standard <version> header and check
`defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L` before
including <expected>. Unlike a raw `__cplusplus >= 202302L` check,
this avoids STL4038 under MSVC C++20 while still enabling std::expected
on GCC 13 -std=c++23 (which defines __cplusplus == 202100L) and MSVC
/std:c++latest / /std:c++23preview.
…ata-engineering#565) Updates `rfl::string_to_enum` and `rfl::internal::enums::from_string` (C++20 and C++26) to accept `std::string_view` instead of `const std::string&`, replaces the exception-throwing `std::stoi` numeric fallback with allocation-free `std::from_chars` enforcing full-string consumption, and drops unused `<sstream>`. Upstream PR: munich-data-engineering#802 Closes: munich-data-engineering#565 Downstream receipts: - NVIDIA/cuda-quantum hand-loops `rfl::get_enumerator_array<E>()` just to parse a `std::string_view`: https://github.com/NVIDIA/cuda-quantum/blob/81ef20d9d4a1e0912a6dbc68637ece017e8fd324/cudaq/lib/Target/Reflection.h#L61-L65 - munich-data-engineering/sqlgen calls `rfl::string_to_enum` directly: https://github.com/munich-data-engineering/sqlgen/blob/265b0a174b661c5905b874f97b064aecb4cded70/include/sqlgen/parsing/Parser_default.hpp#L52-L57
…in headers Cuts ~40k preprocessed lines (~350 ms cold compile time per TU) from thin schema/wrapper headers without any public API changes: - Remove `<functional>` from `include/rfl/internal/cpp20/Result.hpp`. - Remove `<sstream>` from `comparisons.hpp`, `AnyOf.hpp`, `OneOf.hpp`, and `PatternValidator.hpp` (using `std::snprintf` / `std::to_string`; note that `signed char`/`unsigned char` (`int8_t`/`uint8_t`) comparison errors now format as decimal integers rather than raw ASCII characters, while plain `char` stays formatted as a character). - Remove unused `<map>` from `include/rfl/Size.hpp` and add explicit `<cstddef>`. Downstream receipts: - hudson-trading/slang-server intentionally isolates thin rfl headers in `include/Config.h` (included across 13 TUs without `<rfl/json.hpp>`): https://github.com/hudson-trading/slang-server/blob/1b413a4655877a55b3f8a450c23e4ba6c2bf4267/include/Config.h#L9-L16 - munich-data-engineering/sqlgen includes thin headers like `<rfl/Result.hpp>` and `<rfl/PatternValidator.hpp>`: https://github.com/munich-data-engineering/sqlgen/blob/265b0a174b661c5905b874f97b064aecb4cded70/include/sqlgen/Result.hpp
…of-bounds literal marks Tracks active ancestor YAML nodes via a thread-local RAII guard across `read_object` and `read_array` so cyclic YAML aliases return an `rfl::Error` instead of overflowing the stack (while preserving non-cyclic DAG aliases and `const Reader` thread safety), and bounds-checks `YAML::Mark::pos` before indexing `_yaml_str`. Upstream PR: munich-data-engineering#801 Downstream receipts: - openmoq/moqx explicitly documents self-referencing YAML alias infinite recursion and tests adversarial cyclic YAML configs: https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/src/config/YamlDuplicateKeys.cpp#L23-L24 https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/test/config/LoaderTest.cpp#L605-L625 - FANUC-CORPORATION/fanuc_driver parses YAML configs via `rfl::yaml::load`: https://github.com/FANUC-CORPORATION/fanuc_driver/blob/da5db3f611cdc9dffe687e056c4e79bea584bf5c/fanuc_libs/gpio_config/src/gpio_config.cpp#L18
…rflow, and uint64_t write wraparound `rfl::yaml::Reader::to_basic_type` previously parsed every integral type via `node.as<int64_t>()` followed by an unchecked `static_cast<T>`, and `rfl::yaml::Writer::insert_value` cast every integral type via `static_cast<int64_t>(_var)`, causing four bugs: 1. Negative YAML values silently wrapped into unsigned integers (e.g. `-1` became `UINT64_MAX` / `255`). 2. Out-of-range values silently truncated when narrowed into `int8_t`, `uint8_t`, `int16_t`, `uint16_t`, `int32_t`, or `uint32_t`. 3. Valid `uint64_t` values above `INT64_MAX` (up to `UINT64_MAX`) failed `as<int64_t>()` on read. 4. Writing `uint64_t` values above `INT64_MAX` wrapped to negative YAML scalars (e.g. `UINT64_MAX` emitted `-1`), breaking round-trips once the reader rejects negative-to-unsigned wraparound. Bring `rfl::yaml::Reader` and `rfl::yaml::Writer` into parity with `rfl::json` (following munich-data-engineering#746): - In `rfl::yaml::Reader::to_basic_type`, dispatch unsigned and signed integral targets separately: verify `IsScalar()`, reject leading `'-'` for unsigned targets, parse via `as<uint64_t>()` / `as<int64_t>()`, and range-check against `std::numeric_limits<Target>`. - In both `rfl::yaml::Writer::insert_value` overloads, emit unsigned integrals via `static_cast<uint64_t>(_var)`. Eliminates a documented downstream workaround in `openmoq/moqx` (`test/config/LoaderTest.cpp:331-359`, `src/config/ConfigResolver.cpp:1386-1390`).
…_field_names, and guaranteed O(N log N) no_duplicate_field_names Eliminate quadratic template instantiation and worst-case compile-time blowups across internal pack indexing, C++20 field-name extraction, and duplicate field-name validation: 1. nth_element_t.hpp: - Prefer C++26 pack indexing (Ts...[N]) when __cpp_pack_indexing >= 202311L in C++26+ mode (guarded against -Wc++26-extensions on Clang in C++20/23 mode). - Guard __type_pack_element with __has_builtin(__type_pack_element) instead of __clang__ so GCC 14+ also uses the O(1) builtin. - Replace the O(N) fallback for GCC <= 13 / MSVC with a shared multiple-inheritance IndexedPack<std::index_sequence<Is...>, Ts...> instantiated once per pack and queried in O(1) via ADL-suppressed select_indexed_type<I> (including <utility> only in this fallback branch). Handles cv-qualified, reference, pointer, array, void, function, incomplete, and duplicate types. 2. nth_element.hpp: - Prefer C++26 pack indexing (`_ts...[N]`) when `__cpp_pack_indexing >= 202311L` in C++26+ mode, and otherwise replace the per-target ElementWrapper<T, N, i> + operator| fold (Theta(N^2) instantiations across 0..N-1) with a shared IndexedValuePack<std::index_sequence<Is...>, Ts...> constructed via make_indexed_value_pack (keyed only by Ts...) and selected in O(1) via select_indexed_value<N>. - Preserve decayed value-return semantics (`constexpr auto nth_element(Ts&&... _ts)` without unconditional `noexcept`): non-selected arguments are bound by reference only and never copied or moved, only the selected N-th argument is copied/moved into the prvalue return (supporting move-only rvalues and safe temporary lifetime extension via `const auto&`). 3. cpp20/get_ith_field_from_fake_object.hpp & cpp20/get_field_names.hpp: - Add single-bind field_extractor<T, n>::get_ptrs / get_field_ptrs_from_fake_object returning a flat multiple-inheritance FieldPtrPack, and refactor cpp20::get_field_names to bind the fake object once per struct instead of N separate structured bindings + N nth_element calls. - Guard select_field_ptr in field_extractor<T, n>::get_ptr with `if constexpr (_i >= 0 && static_cast<std::size_t>(_i) < n)` for clean out-of-bounds static_assert diagnostics. - Preserve exact source_location/__PRETTY_FUNCTION__/__FUNCSIG__ formatting across Clang, GCC, and MSVC, handle empty structs without instantiating field_extractor<T, 0>, and keep get_ith_field_from_fake_object / get_ith_field_ptr / ith_field_is_const intact and O(1) per lookup. 4. no_duplicate_field_names.hpp: - Pattern-match TupleLike<FieldTypes...> directly (zero tuple_element_t or index_sequence instantiations, trivial O(1) specializations for 0 and 1 fields) and replace gap /= 2 Shellsort (Theta(N^2) worst case) with a self-contained constexpr heapsort (guaranteed O(N log N) worst case, shared per arity N).
…data-engineering#375) Adds opt-in `rfl::VariantsAsOneOf` so `rfl::json::to_schema` emits `oneOf` instead of `anyOf` for `rfl::Variant`, `std::variant`, and `FieldVariantParser` while preserving the backwards-compatible `anyOf` default (for overlapping alternatives) and keeping `std::optional` and `rfl::Generic` as `anyOf`. (Note: `std::expected` delegates schema generation to `rfl::Variant`, so it also emits `oneOf` under `VariantsAsOneOf`.) Parent: depends on `feat(json-schema): emit oneOf for rfl::TaggedUnion in JSON Schema (munich-data-engineering#375)` for `schema::Type::AnyOf::mutually_exclusive_` and `OneOf` emission in `src/rfl/json/to_schema.cpp`. Judge polish applied: - Replaces post-hoc `_definitions` AST mutation for `rfl::Generic` with `internal::remove_variants_as_one_of_t<ProcessorsType>`, delegating cleanly to `Parser<R, W, Generic, ...>::to_schema`. - Adds direct `<rfl/Generic.hpp>` and `<rfl/internal/variants_as_one_of_v.hpp>` includes in `Parser_default.hpp` plus multi-processor composition tests. Refs: munich-data-engineering#375 Downstream receipt: - openmoq/moqx defines 5 mutually-exclusive `rfl::Variant` config schemas currently forced to emit `anyOf` in committed `config.schema.json`: https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/config.schema.json#L510-L557 https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/config.schema.json#L1188-L1203 https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/config.schema.json#L1977-L2001
…Variant, ParserRflVariant, and schemaful::VariantReader Eliminates O(K^2) member/lambda symbol instantiations, non-short-circuiting scans, intermediate pointer-variant round-trips, and unconditional happy-path error allocations across untagged variant and schemaful union parsers: - `variant_alternative_helpers.hpp`: introduces namespace-scope helpers (`record_variant_alternative_error`, `try_read_variant_alternative`, `VariantAlternativeWriter`, `VariantFieldWriter`, `SchemafulVariantAlternativeWriter`, and `variant_alternative_to_schema`) parameterized only by the active alternative type — never the enclosing `AlternativeTypes...` pack — and shared across `std::variant` and `rfl::Variant`. - `ParserVariant.hpp` & `ParserRflVariant.hpp`: switches untagged variant reads to a short-circuit `||` fold (using `std::in_place_index` for `std::variant`), dispatches writes and schema generation through the isolated namespace-scope helpers, removes the intermediate double-pointer `rfl::Variant` round-trip in `ParserVariant::write` for `rfl::Field` variants via `VariantFieldWriter`, and preserves sequential error aggregation and `VariantsAsOneOf`. - `schemaful/VariantReader.hpp`: adds an early out-of-bounds check (eliminating the unconditional 44-byte heap error string allocation on every happy-path union read), dispatches via short-circuit `||` fold, and isolates `read_union_alternative` at namespace scope. - `tests/json/test_variant_parser_dispatch.cpp`: adds focused correctness and scale tests for 16-alternative `std::variant` / `rfl::Variant` (round-trip, `std::variant<rfl::Field<...>>` write path, error aggregation, `VariantsAsOneOf`) and 16-alternative `schemaful::VariantReader` (valid indices 0..15, out-of-bounds, inner error, and empty reader). Verified: - Standalone self-containment checks on all 4 touched/added headers on Clang 23.1.6 and GCC 13.4.0 (`-std=c++20 -Wall -Wextra -Wextra-semi -Werror`, default and `-DREFLECTCPP_C_ARRAYS_OR_INHERITANCE`). - `tests/json/test_variant_parser_dispatch.cpp` compiled with `-std=c++20 -O2 -Wall -Wextra -Wextra-semi -Werror` and passed (2/2 tests) on both Clang 23.1.6 and GCC 13.4.0.
…d dispatch Parent: `perf(parsing): isolate per-field helpers in ViewReader and ViewReaderWithDefault` Adds `rfl::parsing::FieldNameLookup<rfl::Literal<_names...>>` in `include/rfl/parsing/find_field_index.hpp` and wires it into `ViewReader` and `ViewReaderWithDefault` for structs with > 4 fields: - Lookup tables are keyed solely on `ViewType::Names` (`rfl::Literal<...>`), so field wrappers like `rfl::Description` or different formats/processors share the same lookup table without duplicating instantiations. - Sequential-key cursor hint (`find_with_hint`) hits O(1) when keys arrive in declaration order; `RFL_COLD` fallback uses a linear scan for <= 8 fields and a constexpr-heapsorted binary search for > 8 fields (avoiding reliance on constexpr `std::sort` in older libc++ releases). - Keeps the small-struct (<= 4 fields) inline fold path and positional compile-time index path unchanged, and preserves exact `ExtraFields` / `NoExtraFields` / duplicate-key semantics with zero `[[maybe_unused]]` annotations. - Adds focused tests in `tests/json/test_field_name_lookup.cpp` covering small, medium (5..8), wide (> 8), out-of-order, duplicate-key, varied key lengths, and empty `Literal<>` instantiations. Benchmarks (N=3 interleaved Wave 1 vs upstream/main, Clang 23.1.6 / GCC 13.4.0): - Synthetic wide structs (`compile_stress_wide.cpp`, 32/64/128 fields): -17.0% wall / -14.9% RSS / -32.4% .o (Clang Debug); -20.0% wall / -13.0% RSS / -74.8% .o (Clang Release); -9.2% wall / -26.2% .o (GCC Debug); -7.7% wall / -31.4% .o (GCC Release). - Real OSS consumers: `slang-server` `SlangServer.cpp` -6.1% wall / -15.0% .o (Clang Debug), -8.6% wall / -8.0% RSS (GCC Release), `Config.cpp` -46.1% .o (Clang Release); `moqx` `Loader.cpp` -17.5% .o (Clang Debug), -5.4% wall (GCC Release); `fanuc-libs` `serialization.cpp` -9.9% wall / -27.1% .o (Clang Debug); `wolf` `unix_socket_server.cpp` -19.4% .o (Clang Release). - Runtime parity (`reflect-cpp-bench-json` Release): `BM_licenses` -11.1% faster GCC (+0.9% Clang), `Record2` +22.8% faster GCC (-2.3% Clang), `Record16` +11.0% faster GCC (-1.8% Clang / +0.1% FailFast), `BM_person_read` -2.5% faster Clang (+0.7% GCC).
…eader, FieldVariantParser, and ParserTaggedUnion Eliminates O(K) non-short-circuiting linear scans, O(K^2) member/lambda symbol instantiations, and `define_literal` O(K^2) template peeling across externally tagged (`FieldVariantReader`/`FieldVariantParser`) and internally tagged (`ParserTaggedUnion`) union parsers: - `find_field_index.hpp`: adds `find_in_field_name_table` (linear scan with `field_name_equals` for <= 8 entries, binary search for > 8) and non-cold `FieldNameLookup::find_direct` while keeping `FieldNameLookup::find` marked `RFL_COLD` for `ViewReader`'s out-of-order fallback. - `FieldVariantReader.hpp` & `FieldVariantParser.hpp`: dispatches field names via `FieldNameLookup::find_direct` in O(log K), short-circuits via `||` fold over lockstep `(_is, FieldTypes)...`, and isolates per-alternative read, write (`FieldVariantWriter`), and schema (`field_variant_alternative_to_schema`) helpers at namespace scope without repeating `FieldTypes...`. Preserves exact duplicate/unknown/empty error messages and nested `Error::details()` paths. - `ParserTaggedUnion.hpp`: adds `TaggedUnionTagLookup` built directly from `internal::tag_t<_discriminator, AlternativeTypes>...` (supporting single- and multi-value `rfl::Literal` tags), checks duplicate tags on the constexpr-sorted table in O(M) without `define_literal` peeling, looks up discriminators in O(log M), and isolates discriminator extraction, read, write (`TaggedUnionWriter`), and schema helpers at namespace scope. Preserves zero-copy writing when the discriminator is already a struct field, declaration-order allowed-tag lists, `NoFieldNames` handling, and nested `Error::details()` paths. - `tests/json/test_tagged_and_field_variant_dispatch.cpp`: adds focused correctness and scale tests for 24-alternative `TaggedUnion` (including multi-value `rfl::Literal` tags, `NoFieldNames`, `Error::details()`, and schema) and 24-alternative `FieldVariantReader`/`FieldVariantParser`. Verified: - Standalone self-containment checks on all 4 touched headers on Clang 23.1.6 and GCC 13.4.0 (`-std=c++20 -Wall -Wextra -Wextra-semi -Werror`, default and `-DREFLECTCPP_C_ARRAYS_OR_INHERITANCE`). - `tests/json/test_tagged_and_field_variant_dispatch.cpp` compiled with `-std=c++20 -O2 -Wall -Wextra -Wextra-semi -Werror` and passed (2/2 tests) on both Clang 23.1.6 and GCC 13.4.0.
…l isolation, stack found_ in ViewReaderWithDefault, and O(1) VectorParser::write size
Eliminates quadratic runtime/symbol scaling and per-read heap allocations across
tuple, stripped-field-name, default-value, destructor, and container parsing paths:
- TupleReader & TupleParser & call_destructors_on_tuple_where_necessary:
Replace TupleReader's non-short-circuiting comma fold over TupleType-scoped
`read_impl<0..N-1>` with a short-circuiting `||` fold over `assign_by_index`
calling namespace-scope free helpers (`read_tuple_element[_inline]`,
`placement_move_tuple_element`, `handle_missing_tuple_element`) parameterized
only on each element's type (never `TupleType`), with explicit `#include <new>`
for placement `new`. GCC 13 and Clang 23 `-O2` now lower 16-tuple dispatch to
an O(1) jump table (`notrack jmp *%rax` / `jmpq *%rdx`, single bounds check)
instead of O(N) checks per element. Also remove `TupleType`-scoped
`add_to_array`/`add_to_schema` helpers in `TupleParser` (reserving schema
vector capacity), isolate tuple element destruction into
`destroy_tuple_element_if_set<ElemType>`, and short-circuit all-trivial/empty
tuples.
- ViewReaderWithDefault:
Replace `rfl::Ref<std::array<bool, size_>> found_` (which allocated via
`std::make_shared` on every read of a `DefaultIfMissing` or `rfl::DefaultVal`
struct) with stack-allocated `mutable std::array<bool, size_> found_{}`.
Delete copy construction and copy assignment so callers cannot accidentally
copy `ViewReaderWithDefault` by value and split `found_` state. Preserves
`found()`'s `const std::array<bool, size_>&` signature, duplicate-key
tracking, and `ViewReader::assign_by_index`'s existing short-circuit `||` fold.
- ViewReaderWithStrippedFieldNames & ViewReaderWithDefaultAndStrippedFieldNames:
Remove the N-element static array of `ViewType`-scoped lambdas, member
`assign_if_field_is_field_i<0..N-1>`, and duplicated `move_to` helpers.
Reuse the isolated namespace-scope `assign_uninitialized_view_field[_inline]`
and `assign_default_view_field[_inline]` helpers from `ViewReader.hpp` /
`ViewReaderWithDefault.hpp` with short-circuiting `||` index dispatch (lowers
to O(1) jump table at `-O2`, cutting `-O0` symbols from 59 -> 6 each).
- call_destructors_where_necessary:
Remove the nested per-index inner lambda (which emitted N closure types
carrying the full `NamedTuple` at `-O0`) and fold directly over
`_view->values()` via `destroy_view_values_where_necessary`, short-circuiting
all-trivial/empty views and fixing `const` array element destruction.
- VectorParser::write:
Use O(1) `_vec.size()` when available (`std::list`, `std::set`, `std::multimap`,
`std::unordered_*`, etc.) instead of unconditionally traversing the container
with `std::distance(_vec.begin(), _vec.end())`, falling back to `std::distance`
for `std::forward_list`.
Note: `include/rfl/parsing/tabular/ArrowReader.hpp` was left untouched because
Apache Arrow headers (`<arrow/api.h>`) are not installed in this environment to
compile-test it; it still benefits automatically from `call_destructors_where_necessary`.
Empirical verification (GCC 13.4.0 & Clang 23.1.6):
- 16-tuple / 16-field scratch TU: `-O2` `.o` 386,872 -> 242,232 bytes (-37.4%);
`-O0` `.o` 2,318,024 -> 1,797,824 bytes (-22.4%); `TupleReader` `-O0` symbols
46 -> 9; `ViewReaderWithStrippedFieldNames` 59 -> 6;
`ViewReaderWithDefaultAndStrippedFieldNames` 59 -> 6;
`call_destructors_where_necessary` 35 -> 5 (1 carrying `NamedTuple`).
- Direct 16-tuple `TupleReader::read`: GCC 13 `-O2` emits `notrack jmp *%rax`
(indirect_jmps=1); Clang 23 `-O2` `assign_by_index` emits `cmpl $15` + `jmpq *%rdx`
(cmps=1, calls=0, indirect_jmps=1).
- `ViewReaderWithDefault`: `_Znwm` calls in `read_object_or_array_with_default`
dropped from 1 -> 0 for both `DefaultIfMissing` and `DefaultVal`.
- `VectorParser::write` on `std::set<int>`: extra `_Rb_tree_increment` pass
before `array_as_root` eliminated.
- Full test suite (`-DREFLECTCPP_STRICT_WARNINGS=ON`): Clang 23.1.6 776 passed /
1 expected locale skip (777 total, 0 warnings); GCC 13.4.0 776 passed / 1
expected locale skip (777 total, 0 warnings); all 8 headers pass 32/32
standalone checks on both compilers with and without
`-DREFLECT_CPP_C_ARRAYS_OR_INHERITANCE`.
…d Cap'n Proto helpers When a custom type exposes a `ReflectionType` (or `rfl::Reflector<T>::ReflType`) wrapped in `rfl::Description` or `rfl::Deprecated`, `Parser_default::make_reference` stores `Type::Description` or `Type::Deprecated` directly in `_definitions[name]`. While `type_to_avro_schema_type` and `type_to_capnproto_schema_type` already unwrapped both wrappers, three schema helper predicates did not: - `rfl::avro::is_named_type` (`src/rfl/avro/to_schema.cpp`): failed to recognize wrapped records/enums as named types, emitting duplicated anonymous `unnamed_N` definitions instead of named references. - `rfl::capnproto::is_named_type` (`include/rfl/capnproto/is_named_type.hpp`): failed to recognize wrapped structs/enums/unions/maps as named types (and was missing `#include <type_traits>` for standalone compilation). - `rfl::capnproto::string_map_to_capnproto_schema_type` (`src/rfl/capnproto/to_schema.cpp`): failed to detect wrapped `Type::Literal` values via `is_literal_type`, emitting invalid generic `Map(Enum)` instead of `ScalarMap`. Adds focused Avro and Cap'n Proto regression tests for `Description`- and `Deprecated`-wrapped custom `ReflectionType` definitions.
Parent: `feat(enums): add rfl::TransformEnumNames processors (munich-data-engineering#731)` Adds the opt-in `rfl::EnumNames<E>` specialization trait and `rfl::get_enum_wire_names<E, Ps...>()` utility so enums with non-identifier wire strings (e.g., `"c++20"`, `"nvq++"`, `"*"`), C++ keyword clashes, or enumerators outside the default reflected range can declare custom wire names across JSON, CLI, YAML, XML, Generic, and JSON Schema without duplicating enumerators as `rfl::Literal<...>`: - Supports static `overrides` (array or borrowed `overrides()` returning `std::span`, with `static_assert` rejecting dangling by-value containers) and per-enum `transform` (`EnumNameTransform` constant or custom callable). - `overrides` takes precedence over `transform`; when only `overrides` is specified, non-overridden enumerators still inherit any `rfl::TransformEnumNames<...>` processor passed to `read`/`write`/`to_schema`. - Zero-overhead `if constexpr` fast path when neither `EnumNames<E>` nor `TransformEnumNames` is active; resolved tables are cached per `(EnumType, EnumNameTransform)`. - Public `rfl::get_enum_wire_names<E, Ps...>()` accepts variadic processors, and throwing custom `transform` callbacks are caught into `rfl::Error` across both `ParserEnum::read` and direct `rfl::string_to_enum`. Open design question for upstream review: whether the trait should live at `rfl::EnumNames<E>` (matching `rfl::Reflector<T>`) or `rfl::config::enum_names<E>` (matching `rfl::config::enum_range<E>` / `rfl::config::enum_descriptions<E>`). Refs: munich-data-engineering#106 (Maintainer: "something along these lines is possible") Downstream receipts: - NVIDIA/cuda-quantum hand-written Reflector tables for non-identifier wire strings (e.g., `c++20`, `nvq++`): 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/QuakeReferenceSemanticsProfileYaml.h#L16-L32 - openmoq/moqx custom action wire strings (`"*"` / domain verbs) & config enums: https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/src/auth/Action.h#L24-L102 https://github.com/openmoq/moqx/blob/60bab7f13925acbaf578670223e660d71e891547/src/config/ConfigResolver.cpp#L35-L48
…h-data-engineering#368) Adds `rfl::json::Raw` so JSON subtrees can be read and written verbatim without materializing intermediate `rfl::Generic` C++ ASTs or touching core parser headers: - Out-of-line `RFL_API` implementation in `src/rfl/json/Raw.cpp` (wired via `src/reflectcpp_json.cpp`) plus additive raw-emission methods on `rfl::json::Writer` (`yyjson_mut_rawncpy`). - `Parser<generic::Reader, generic::Writer, json::Raw>` bridging so `rfl::DefaultVal<rfl::json::Raw>`, `rfl::to_generic`, `rfl::from_generic`, and `rfl::json::to_schema` work seamlessly. - Non-JSON formats fail cleanly at compile time via `static_assert`. Judge polish applied: - Tightened unchecked string constructors to private; `Raw::from_string()` (strict RFC 8259 validated, returning `Result<Raw>`) is the safe default, with explicit `Raw::from_trusted_string()` opt-in for pre-serialized JSON. - Added standard const-only reflect-cpp accessors `get()`, `operator*()`, and `operator()()`. - Switched `Raw::from_json_obj` to `yyjson_val_write_opts(..., &err)` so serialization failures (e.g., `NaN`/`Infinity`) include `err.msg`. - Handled empty/moved-from `value_` in `Raw::to_generic()` (returning null `Generic`) and added `catch (...)` in `noexcept` `Raw::from_generic()`. - Updated `static_assert` message to mention both `rfl::json` and `rfl::Generic`. Refs: munich-data-engineering#368 Downstream receipts: - hudson-trading/slang-server double-reflects JSON-RPC params via `rfl::Generic`: https://github.com/hudson-trading/slang-server/blob/1b413a4655877a55b3f8a450c23e4ba6c2bf4267/include/lsp/JsonRpc.h#L23-L43 https://github.com/hudson-trading/slang-server/blob/1b413a4655877a55b3f8a450c23e4ba6c2bf4267/include/lsp/JsonRpcServer.h#L53-L132 - games-on-whales/wolf stores raw Docker JSON as escaped `std::string` and re-parses `to_schema` output into `rfl::Object<rfl::Generic>`: https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/src/moonlight-server/state/serialised_config.hpp#L98 https://github.com/games-on-whales/wolf/blob/ac2461f68feda41fdc7a7c8e812b9ab4b80520b7/src/moonlight-server/api/openapi.cpp#L17-L69
…t_index, and O(K) TaggedUnion::operator==
Replace quadratic/cubic template-fold dispatch in rfl::Variant and
rfl::TaggedUnion with inline multi-way switch dispatch and consteval
index/size loops (zero function-pointer trampoline tables or extra
symbols):
- include/rfl/internal/element_index.hpp: compute the first matching
cvref-stripped alternative index via a single consteval loop over
std::array<bool, sizeof...(AlternativeTypes)>.
- include/rfl/internal/variant/find_max_size.hpp: replace SizeWrapper
operator| fold instantiations with a consteval std::size_t loop over
sizeof(Types)..., handling empty packs cleanly.
- include/rfl/internal/variant/dispatch.hpp,
include/rfl/internal/variant/result_t.hpp & include/rfl/Variant.hpp:
- Replace the 12 do_visit_* non-short-circuiting fold overloads and
std::optional return boxing with SwitchDispatch (inline 1/2/3/4/8/16-way
switch specialization chain with RFL_ALWAYS_INLINE on Clang/GCC and
plain inline on MSVC to avoid C4714 under /W4 /WX, O(K/16)
instantiations, zero nth_element_t, zero address-taken trampolines).
LLVM/GCC merge the switches into a single flat jump/lookup table and
inline/constant-fold identically to baseline without emitting trampoline
symbols on small variants.
- Keep baseline non-ref-qualified Variant::visit(F&&) and
Variant::visit(F&&) const overloads (preserving lvalue-reference
forwarding for temporary/rvalue Variants and TaggedUnions) with SFINAE
invocability constraints (visit_invocable / visit_const_invocable) that
reject non-invocable, partial, mismatched-return, and value-category-
mismatched visitors cleanly without breaking mutating generic lambdas,
const-only visitors, or void/reference/non-movable return types.
- Implement rfl::get_if<T> and rfl::get_if<_i> directly via
internal::variant::Access in O(1) runtime and compile time without
visit(), with cv-exact matching first (e.g. Variant<int, const int> and
Variant<const int, int>) and safe qualification-adding fallback (e.g.
get_if<const T> on Variant<T, ...> or const Variant<T, ...>), handling
nullptr, absent types, and duplicate alternatives.
- Replace visit()+element_index in copy_from_other, move_from_other,
and destroy_if_necessary with SwitchDispatch (skipping destruction
when all alternatives are trivially destructible).
- Fix copy_from_type exception propagation (not noexcept), constrain
Variant(T&&) and operator=(T&&) with !is_lvalue_reference_v<T> &&
!is_const_v<T> so lvalues/const values use copy-and-swap
operator=(const T&), keep Variant(T&&) conditionally noexcept while
keeping Variant::operator=(T&&) noexcept, and destroy *this before
moving in Variant::swap.
- include/rfl/TaggedUnion.hpp: restore SFINAE constraints on
TaggedUnion::visit (both mutable and const overloads) and replace nested
lhs.visit(rhs.visit(...)) in TaggedUnion::operator== with an index check +
inline SwitchDispatch via Access::equals (O(K) compile time, zero extra
symbols, 5.8x faster at K=64).
- tests/generic/test_rfl_variant.cpp: cover element_index, find_max_size,
value categories (including rvalue Variant/TaggedUnion lvalue-ref source
compat), return types, SFINAE detectability & mutating generic lambdas,
move-only/non-default types, exception safety, get_if edge cases (nullptr,
duplicates, cv-exact Variant<int, const int> / Variant<const int, int> /
const Variant), 16/32-alt scale, and TaggedUnion::operator==.
…rap_in_fields, and concat_literals
Replace quadratic/cubic compile-time and runtime folds across tuple
concatenation, tuple-to-struct reconstruction, field wrapping, and
compile-time literal concatenation with single-pass O(N) algorithms:
- `internal/tuple/concat.hpp`: replace the left-fold of pairwise
`concat_two` calls (Theta(N^3) compile-time, Theta(N^2) runtime moves)
with a consteval `(outer, inner)` index table and flat indexed
reference table (`TupleRefs`), constructing the result `rfl::Tuple` in
one pack expansion with zero intermediate tuples and strictly one
move (rvalue) or one copy (all-lvalue) per element. Qualify internal
helper calls (`rfl::internal::tuple::get_ref`, `extract_concat_element`,
`concat_impl`) to prevent C++20 ADL hijacking by user element
namespaces. Also fixes the latent `const Head&` overload bug that
previously returned `TupleWrapper` instead of `rfl::Tuple`, and
handles 0/1/empty/mixed lvalue+rvalue/move-only tuples cleanly.
- `internal/move_from_tuple.hpp`: guard `unflatten_ptr_tuple` with
`has_flatten_fields<ptr_tuple_t<T>>()` and `flatten_c_arrays` with
`has_arrays<TupleType>()`, fast-pathing plain structs directly into
aggregate initialization `T{std::move(rfl::get<I>(_t))...}` without
pointer tuples or `tuple_cat`. Replace the O(N^2) `IndptrHelper` fold
with a consteval prefix-sum `std::array`, fix nested `rfl::Flatten`
pointer unwrapping in `calc_flattened_size`, and recurse
`flatten_c_arrays` into nested `rfl::Flatten` pointer tuples (covering
C-style arrays inside `rfl::Flatten` and C-arrays declared after
`rfl::Flatten`; note that the pre-existing `move_from_pointers`
limitation remains when a C-array precedes an `rfl::Flatten` field in
the same struct, as expanding a preceding C-array shifts indices in
`Pointers` relative to `ptr_tuple_t<T>`).
- `internal/wrap_in_fields.hpp` + `internal/calc_flattened_size.hpp`:
replace recursive parameter-pack peeling and `flattened_ptr_tuple_t`
materialization with a consteval `name_offsets` array and a single
non-recursive `index_sequence` expansion.
- `internal/concat_literals.hpp`: preserve the 0/1/all-single fast paths
and replace the general left-fold (which instantiated O(N)
intermediate `rfl::Literal` types with O(N^2) NTTP args on structs
containing `rfl::Flatten`) with a single-pass `(outer, inner)` index
table over flat `LiteralTypeTable` base packs, with qualified
`rfl::internal::get_indexed_literal_type` lookups to prevent ADL
hijacking.
Verified standalone header self-containment (20/20 passed, standard and
`-DREFLECT_CPP_C_ARRAYS_OR_INHERITANCE`) and full CTest suite on both
Clang 23.1.6 and GCC 13.4.0 with `-DREFLECTCPP_STRICT_WARNINGS=ON`
(0 warnings, 782 passed / 1 expected locale skip out of 783).
…er isolation, and FetchContent docs Make reflect-cpp work out of the box as a CMake subproject (FetchContent / add_subdirectory) across Linux, macOS, and Windows (VS 2022 MSBuild, Ninja MSVC, Ninja clang-cl) without mutating parent project state or tripping consumer warning/linter policies: - **Target-scoped C++ standard & top-level scoping (#157):** Compute `_REFLECTCPP_IS_TOP_LEVEL` (`CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR`), scope global `CMAKE_CXX_STANDARD` / `CMAKE_CXX_STANDARD_REQUIRED` / `CMAKE_EXPORT_COMPILE_COMMANDS` defaults, `ament_cmake` / `ament_package()`, and `CPack` to top-level builds, and declare target-scoped `target_compile_features` (`cxx_std_20` / `cxx_std_23` / `cxx_std_26` guarded on CMake >= 3.30 with `CXX_STANDARD 26` fallback on 3.25-3.29) + `CXX_STANDARD_REQUIRED ON`. - **CMake 3.20 minimum with 3.23 FILE_SET fallback (#156):** Lower `cmake_minimum_required` from 3.23 to 3.20 (supporting RHEL 8 / Ubuntu 22.04 / ROS 2 Humble), replace `PROJECT_IS_TOP_LEVEL` with `_REFLECTCPP_IS_TOP_LEVEL`, gate `FILE_SET reflectcpp_headers` on CMake >= 3.23 with an `install(DIRECTORY ...)` fallback, fix `${INCLUDE_INSTALL_DIR}` to `${CMAKE_INSTALL_INCLUDEDIR}`, and guard `$<LINK_LIBRARY:WHOLE_ARCHIVE,...>` on CMake >= 3.24 with `/WHOLEARCHIVE:` fallback. - **Subproject vcpkg/install defaults & config ordering (#142):** Default `REFLECTCPP_INSTALL` and `REFLECTCPP_USE_VCPKG` to `${_REFLECTCPP_IS_TOP_LEVEL}` (removing the unconditional top-level `REFLECTCPP_INSTALL=ON` override), preserve pre-set `CMAKE_TOOLCHAIN_FILE` (preferring explicit `-DVCPKG_ROOT`, then local `./vcpkg` submodule, then `$ENV{VCPKG_ROOT}`), replace directory-level `include_directories(PUBLIC ${jsoncons_INCLUDE_DIRS})` with target-scoped `SYSTEM PUBLIC $<BUILD_INTERFACE:...>`, and order `reflectcpp-exports.cmake` after all `find_dependency()` calls in `reflectcpp-config.cmake.in`. Keep default library naming untouched for Conan (`conanfile.py`) and existing Windows Debug consumers, documenting `-DCMAKE_DEBUG_POSTFIX=d` for multi-config single-prefix Windows installs. - **SYSTEM interface includes & warning/linter isolation (#140 Part 1):** Mark subproject consumer interface includes `SYSTEM` (unless top-level or `REFLECTCPP_STRICT_WARNINGS=ON`), propagate subproject `pugixml` includes onto `reflectcpp`'s own `SYSTEM PUBLIC $<BUILD_INTERFACE:...>` without mutating parent targets, mark bundled thirdparty & YAS includes `SYSTEM`, silence vendored `src/yyjson.c` warnings cleanly (`-w` on GNU/Clang, `/W0` under MSVC `REFLECTCPP_STRICT_WARNINGS`), clear inherited `CLANG_TIDY`/`CPPCHECK`/`IWYU` and `COMPILE_WARNING_AS_ERROR` on subproject `reflectcpp`, strip inherited MSVC `/W*`/`-W*`/`/WX*`/`-WX*` flags cleanly in local scope to eliminate D9025 spam (restoring `/W3` for `tests/` and `benchmarks/` under top-level `REFLECTCPP_STRICT_WARNINGS=ON`), use `/W4` instead of `-Wall` under `REFLECTCPP_STRICT_WARNINGS` on MSVC/clang-cl, remove redundant Release `-DNDEBUG` injection, and fix compiled-source warnings in `src/rfl/env/Writer.cpp`, `include/rfl/parsing/schema/Type.hpp`/`.cpp` (explicit out-of-line copy/move special members for C5267), and `src/rfl/json/to_schema.cpp` (C4459/C4702). - **CXX-only & MSVC-safe test/benchmark subprojects:** Add `LANGUAGES CXX` to all `tests/*/CMakeLists.txt` and `benchmarks/*/CMakeLists.txt` so `-DCMAKE_CXX_COMPILER=clang-cl` does not probe a C compiler, and guard GCC-only `-Wall -O2` `CMAKE_C_FLAGS` with `if (NOT MSVC)`. - **FetchContent quickstart & install docs:** Fix broken links and Option 5 option ordering in `README.md` and `docs/content/install.md`, and add JSON-only (`GIT_SUBMODULES ""`) and YAML FetchContent quickstart snippets. Addresses #140, #142, #156, #157 and clockblocker/refl-cpp-workbench#23.
…nd unnecessary schema AST copies
Rebased onto `upstream-queue` (`9b382c62`), which already includes explicit
out-of-line Rule-of-Five copy/move special members on `rfl::parsing::schema::Type`
and warning fixes in `src/rfl/json/to_schema.cpp` (`b6407224`). This commit
completes the schema move and O(N) insertion optimizations:
- `parsing::schema::Type` (`Type.hpp` / `Type.cpp`): adds out-of-line
`Type(VariantType&& _variant) noexcept` alongside the existing Rule-of-Five
special members so temporary `Type{std::move(...)}` construction moves
instead of deep-copying the underlying variant.
- `rfl::Object` (`Object.hpp`): adds `reserve(std::size_t)` to preallocate
backing storage without changing `sizeof(rfl::Object<T>)` or wire formats.
- O(N) unique-key schema insertions: switches `NamedTupleParser::to_schema`,
`src/rfl/json/to_schema.cpp` (`Type::Object`), and
`src/rfl/parsing/schemaful/tuple_to_object.cpp` from quadratic
`Object::operator[]` scans to `reserve(...)` + O(1) `insert(...)`, preserving
exact declaration order byte-for-byte. `NamedTupleParser::to_schema` computes
the exact non-skipped, non-`ExtraFields` count at compile time.
- Move & in-place lowering (`make.hpp`, `NamedTupleParser.hpp`,
`src/rfl/json/to_schema.cpp`): switches `parsing::schema::make`,
`NamedTupleParser::to_schema`, and JSON Schema lowering (`DefaultVal`,
`Deprecated`, `Description`, `Optional`, `Tuple`, `Object`,
`DescribedLiteral`, validation combinators, and final `JSONSchema`) to
in-place annotation mutation, `std::move`, vector `reserve`, and sorted
`emplace_hint(definitions.end(), ...)`, while preserving `b6407224`'s
shadowing and unreachable-code warning fixes.
- `tests/json/test_schema_scale.cpp`: adds scale and trait tests covering
`Object::reserve`, `parsing::schema::Type` noexcept move/constructibility,
`tuple_to_object`, wide 64-field structs, and nested variant/tagged-union/
tuple JSON schemas.
Verified:
- Standalone self-containment checks on all 4 touched headers on Clang 23.1.6
and GCC 13.4.0 (`-std=c++20 -Wall -Wextra -Wextra-semi -Werror`, default and
`-DREFLECTCPP_C_ARRAYS_OR_INHERITANCE`).
- `src/rfl/parsing/schema/Type.cpp`, `src/rfl/json/to_schema.cpp`, and
`src/rfl/parsing/schemaful/tuple_to_object.cpp` compiled cleanly on Clang
23.1.6 (`-Wall -Wextra -Wshadow -Wextra-semi -Werror`) and GCC 13.4.0
(`-Wall -Wextra -Wextra-semi -Werror`, plus `-Wshadow` clean in all touched
sources/headers).
- `tests/json/test_schema_scale.cpp` compiled with
`-std=c++20 -O2 -Wall -Wextra -Wextra-semi -Werror` and passed (5/5 tests)
on both Clang 23.1.6 and GCC 13.4.0.
…son, and add reflectcpp::headers target Improve library packaging and embedding hygiene for static/shared consumers and header-only / OBJECT-library builds: - **Bundled yyjson hidden visibility & external yyjson target (#140 Part 2):** Default-hide bundled `yyjson` symbols on static non-Windows builds (`yyjson_api=__attribute__((visibility("hidden")))` + `-fvisibility=hidden` on `src/yyjson.c`) so consumer DSOs never export `yyjson_*` symbols even with `REFLECTCPP_HIDDEN_VISIBILITY=OFF`, while keeping shared and Windows static builds untouched. Add `REFLECTCPP_USE_BUNDLED_YYJSON` and `REFLECTCPP_YYJSON_TARGET` (preserving parent normal variables under CMP0126 OLD and failing fast on misconfiguration or missing targets, including alias targets), gate `include/rfl/thirdparty` on both `REFLECTCPP_USE_BUNDLED_YYJSON` and `_REFLECTCPP_NEEDS_JSON_IMPL` so JSON-disabled builds never receive thirdparty includes, enable `POSITION_INDEPENDENT_CODE ON` by default for static subprojects when unset, and add opt-in `REFLECTCPP_HIDDEN_VISIBILITY`. - **Header-only `reflectcpp::headers` interface target (#141):** Add and export `INTERFACE` target `reflectcpp_headers` (`reflectcpp::headers`) mirroring `reflectcpp`'s C++ standard compile features, public compile definitions, SYSTEM/non-SYSTEM include directories, and conditional bundled/external dependency headers (without CMake 3.20-3.25 directory-scope `TARGET_PROPERTY` failures) without linking compiled objects, and document usage in `docs/content/install.md`. Depends on CMake PR 1 (subproject ergonomics & CMake 3.20 support). Addresses #140 and #141.
Replace superlinear recursive template instantiation chains across
remove_fields and the define_{named_tuple,literal,variant,tagged_union}
type-level builders:
- internal/IndexedTypeMap.hpp: add a collision-free O(1)-lookup indexed
type map (IndexedTypeMapEntry + select_indexed_type_map_entry) for flat
pack indexing without linear recursive peeling.
- internal/remove_fields.hpp: replace O(K * N^2) recursive field removal
with a single consteval KeepFieldsPlan and flat IndexedTypeMap expansion
(O(N)), handling 0 names, empty NamedTuple<>, unknown/duplicate names,
all-removed, and cvref-qualified NamedTuple inputs. Guard non-NamedTuple
inputs with an immediate static_assert instead of deep recursion.
- internal/define_{named_tuple,literal,variant,tagged_union}.hpp: replace
left-fold 1-by-1 peeling (O(N^2)) with O(1) fast paths (all plain Fields,
single-tag Literals, plain variant alternatives, all NamedTuples) and
4-way balanced divide-and-conquer via IndexedTypeMap (O(F log M)),
preserving exact order, duplicates, 1-level nesting, and discriminator
constraints.
Verification:
- 44/44 standalone header self-containment checks pass on Clang 23.1.6 and
GCC 13.4.0 (default & -DREFLECTCPP_C_ARRAYS_OR_INHERITANCE, -Wall -Wextra
-Wextra-semi -Werror).
- Compile-fail checks confirm immediate static_assert on non-NamedTuple
inputs to remove_fields_t (int, NamedTuple*) and discriminator mismatch
rejection in define_tagged_union_t on both Clang 23.1.6 and GCC 13.4.0.
- Full CTest suite with -DREFLECTCPP_STRICT_WARNINGS=ON: 773 passed, 1
skipped (cli locale), 0 warnings on both Clang 23.1.6 and GCC 13.4.0.
- 32-element builders + remove_fields (-fsyntax-only): GCC 2.51s / 422 MB
-> 0.91s / 177 MB (-63.7% time, -58.0% RSS); Clang 0.70s / 149 MB ->
0.65s / 124 MB (-16.6% RSS).
…, and length-aware Text
…-array read/write
…MSVC 14.52 (munich-data-engineering#805) Follow-up to upstream PR munich-data-engineering#794, which converted std::invoke_result_t sites to direct decltype expressions to work around MSVC 14.52 C3539 ('type': a template-argument cannot be a type that contains 'auto'), but missed the remaining typename std::invoke_result<...>::type sites. - Convert field_names_t.hpp (directly hit by rfl::json::read<T> in munich-data-engineering#805) and drop its unused <functional> include. - Convert internal/field_tuple_t.hpp, internal/Field.hpp, internal/flattened_ptr_tuple_t.hpp, and internal/move_from_named_tuple.hpp (also resolving the overloaded nt_to_ptr_named_tuple<T>(std::declval<T&>()) call). - Convert the remaining 3 std::invoke_result<F, T>::type sites in internal/cpp20/Result.hpp and harmonize transform && to decltype(_f(...)) so all 4 monadic overloads match the actual call expression and const&/&& value category.
… write, and to_schema
… clean unity builds
Upstream PR Queue (
upstream-queue)Single-branch queue of self-contained, reviewable PRs for
munich-data-engineering/reflect-cpp, drip-fed 1–2 PRs at a time ontoupstream/mainin easiest-first, dependency-safe order. The queue shrinks as PRs merge upstream and grows as standalone fixes are added.Speculative proposals stay on
discuss/ssot(stacked onupstream-queue); standalone bugfixes found there drop into this queue. Landable CMake onboarding PRs live here; dev-onlyvcpkgsubmodule removal stays parked ondiscuss/ssot.Highlights
Compile-time, binary size & runtime
Pinned comparison of the full 62-commit queue (
290bdb24b7d6→3d33e7218cca: 61 queued + 1 merged) vs.main— 0 regressions across all verified platforms:ccache=off, quiet host)reflect-cpp-self, compile stress, JSON / scale / Cap'n Proto runtime (refl-cpp-workbench#34, #44, #45)2026-12-06)N=3interleaved surgical TUs (rollup #34, #46–#50)clang-cl19.1.5 (MSBuild & Ninja)queue-tests/across 9 formats, CMake subprojects, 4 OSS consumersReal OSS consumer builds — Linux x86_64 (
Clang 23.1.6 Release, refl-cpp-workbench#34)1. Targeted
reflect-cpp-heavy TUs (N=3interleaved; control TUs within±1.35%wall,0.00%.o):.o/ Archive Δopenmoq/moqxLoader.cpp(184 rfl wrappers; 1 of 203 TUs)slang-serverConfig.cpp(29 rfl wrappers)slang-serverSlangServer.cppcuda-quantumTargetConfigSchema.cpp(YAML)wolfunix_socket_server.cppfanuc-libsserialization.cpplibreflectcpp.a2. Whole-project end-to-end impact (cold clean builds,
ccache=off):End-to-end impact of those reductions across each full repository build (including all non-
reflect-cppTUs):.oA → B (Δ)sqlgensqlgen-sqlite-tests-14.4%;libsqlgen.a-5.1%cuda-quantum(Target)libCUDAQTargetCatalog.a-16.8%slang-serverslang-server-4.8%;server_unittests-3.4%openmoq/moqx(203 TUs)moqx-2.5%;moqx_config_test-8.0%wolfwolftests-5.1%;wolf_runner-2.9%fanuc-libsrmi-5.1%;gpio_config+17.8%reflect-cpp-selfreflect-cpp-json-tests-7.8%;libreflectcpp.a-15.9%*
moqx(218/220) reflects 2 intentional upstream bugfix diffs: negative-to-unsigned YAML rejection andTaggedUniononeOf/ flattenedanyOfJSON Schema. †reflect-cpp-selfskips 1 locale test on bothAandBand adds 1 regression test.Real OSS & synthetic builds — macOS arm64 verification (
290bdb24b7d6→3d33e7218cca, 2026-12-06)Measured on Apple M1 (8 cores, 16 GiB RAM), macOS 27.2.1 (26B131) arm64 with
Apple clang version 17.0.0 (clang-1700.0.13.5), CMake4.4.4, Ninja1.13.2,Release(ccache=off) — rollup receipt.1. Targeted
reflect-cpp-heavy TUs (N=3interleaved;control_noop.cppnoise floor ±1.65% wall, 0.00%.o):.o/ Archive Δsyntheticcompile_stress_large.cppsyntheticcompile_stress_wide.cppsyntheticcitm_bench.cppfanuc-libsserialization.cppslang-serverConfig.cppslang-serverSlangServer.cpplibreflectcpp2. Whole-project end-to-end impact (cold clean builds,
ccache=off):.oA → B (Δ)syntheticwb_compile_stress_wide-82.8%reflect-cpp-selfreflect-cpp-json-tests-4.8%sqlgensqlgen-sqlite-tests-16.2%fanuc-libsrmi-6.6%slang-serverslang-server-5.3%Compile stress & header bloat
N=3interleaved single-TU compiles (control_noop.cppdrift-0.97%Clang /+0.48%GCC):.o/ Code Size A → B (Δ)compile_stress_wide.cpp(32–128f).o, -77.6% bin)compile_stress_wide.cpp(32–128f).o)-O2.o, -51.1%.text)-O0 -g.o, -10.5 MB)-O2.o, -52.4%.text)clang++ -E): -13.8k to -19.0k fewer preprocessed lines (-18.6% to -23.1%) acrossResult.hpp,comparisons.hpp,AnyOf.hpp,OneOf.hpp, andSize.hpp.Runtime & algorithmic speedups
End-to-end & format runtime (
-O3,N=3–N=5):Record2/Record16/citm_read)citm_read+2.4%,BM_canada-7.0% lat.write_unpacked(vs. packed)List<T>(100k/SensorStream)MapReader(10k JSON / Cap'n Proto)Algorithmic scale (
Clang 23 -O3, receipt):json::write/read(rfl::Generic)strings::replace_all/splitTaggedUnion::operator==/readTupleReader/json::to_schema/bson::writeNew features & ergonomics
rfl::json::Raw): read/emit raw JSON subtrees withoutrfl::Generictrees or double-escaping.rfl::cli::usage): generate--helptext directly from anyrfl::cli::readstruct.rfl::TransformEnumNames), per-enum overrides (rfl::EnumNames<E>), and zero-allocationstd::string_viewinrfl::string_to_enum.rfl::type_name<T>andrfl::StringLiteral(with+andLiteral::name_view()), avoidingrfl::internal::.rfl::json::read_*/write_*constants replacingYYJSON_*macros.oneOfforrfl::TaggedUnion, flattenedanyOffor optional variants, plusrfl::IntegerBoundsandrfl::VariantsAsOneOf.ReaderOptions& unpacked I/O: configurable traversal/nesting limits across allrfl::capnproto::readoverloads (withkj::Exception→rfl::Errorsafety) plus zero-packwrite_unpacked/read_unpacked.CMake & packaging
SYSTEMincludes, and isolated warnings, linters, install, and CPack underFetchContent/add_subdirectory.yyjsonin static builds (0leakedyyjson_*in consumer DSOs), supports externalyyjson, exportsreflectcpp::headers, and shipsTHIRD_PARTY_NOTICES.md.-Wall -Wextra -Werror -Wsign-conversion -Wextra-semi, plus MSVC/std:c++20(STL4038),C4996,C3546,C4714, and MSVC 14.52 (C3539) fixes verified across VS 2022 MSBuild, Ninja MSVC, Ninjaclang-cl, 9 formats, and 4 Windows OSS consumers.Parked Work
14 design-heavy proposals needing upstream maintainer sign-off remain restacked on
discuss/ssot— see#208(Discussion Queue Overview (discuss/ssot)) and the For Agents comment below.