Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/content/flatten_structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,7 @@ This flattens all fields into a single JSON object:
## API convenience

`rfl::Flatten` behaves like a thin wrapper around the underlying type. You can access the underlying value using `.get()`, `.value()`, `operator()()`, `operator*()`, or `operator->()` (const and non-const overloads).

## Flattening `rfl::TaggedUnion`

`rfl::Flatten` also supports `rfl::TaggedUnion` by value (with or without sibling fields, and nested across multiple levels) for schemaless formats. Raw pointers (`rfl::Flatten<MyTU*>`), schemaful formats, `rfl::to_named_tuple`/`rfl::from_named_tuple`, and `rfl::cli::read` are rejected at compile time. See [variants and tagged unions](variants_and_tagged_unions.md#nested-and-flattened-rfltaggedunion) for details.
59 changes: 59 additions & 0 deletions docs/content/variants_and_tagged_unions.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,65 @@ Also note that this is exactly how tagged unions work in Pydantic. When you
use the `rfl::NoFieldNames` processor, the tag MUST always be the first entry
of the array.

### Nested and flattened `rfl::TaggedUnion`

You can nest `rfl::TaggedUnion`s inside a single flat object using `rfl::Flatten` (or by deriving from `rfl::TaggedUnion` with a `Tag`). This is useful for protocols that perform multi-level dispatch on different discriminator fields within the same object (for example, dispatching first on `"type"` and then on `"event"`):

```cpp
struct WaveformsLoaded {
using Tag = rfl::Literal<"waveforms_loaded">;
std::string source;
};

struct GotoDeclaration {
using Tag = rfl::Literal<"goto_declaration">;
std::string variable;
};

using S2CEvent = rfl::TaggedUnion<"event", WaveformsLoaded, GotoDeclaration>;

struct Response {
using Tag = rfl::Literal<"response">;
std::string command;
};

struct Event {
using Tag = rfl::Literal<"event">;
rfl::Flatten<S2CEvent> payload;
};

using S2CMessage = rfl::TaggedUnion<"type", Response, Event>;

const S2CMessage msg =
Event{.payload = S2CEvent(WaveformsLoaded{.source = "foo.vcd"})};

const auto json_string = rfl::json::write(msg);
// {"type":"event","event":"waveforms_loaded","source":"foo.vcd"}

const auto parsed = rfl::json::read<S2CMessage, rfl::NoExtraFields>(json_string);
```

You can also flatten a `rfl::TaggedUnion` alongside sibling fields in a plain struct, nest to arbitrary depth (2-level, 3-level, etc.), or derive directly from `rfl::TaggedUnion`:

```cpp
struct DirectEvent
: rfl::TaggedUnion<"event", WaveformsLoaded, GotoDeclaration> {
using Tag = rfl::Literal<"event">;
using TaggedUnion::TaggedUnion;
};

using DirectS2CMessage = rfl::TaggedUnion<"type", Response, DirectEvent>;
```

Key guarantees:
- **Single-pass reading and writing**: all levels serialize into and deserialize from a single flat object.
- **`rfl::NoExtraFields` and `rfl::ExtraFields`**: outer and inner discriminators and fields are validated together, so outer fields do not trigger false extra-field errors in the inner union while truly unknown fields are rejected (or captured by `rfl::ExtraFields`).
- **JSON Schema (`rfl::json::to_schema`)**: expands flattened tagged unions into `anyOf` branches containing the merged flat object schemas.
- **Compile-time collision checking**: duplicate discriminators (e.g. an outer and inner `rfl::TaggedUnion` both using `"type"`) or duplicate field names across flattened levels fail at compile time with a `static_assert`.
- **Constraints**:
- Use value semantics (`rfl::Flatten<MyTaggedUnion>`, not raw pointers `rfl::Flatten<MyTaggedUnion*>`).
- Flattened `rfl::TaggedUnion` is supported for schemaless formats (JSON, YAML, TOML, Generic, etc.), and is rejected at compile time for schemaful formats (Avro, Cap'n Proto, Parquet, SQLite) as well as `rfl::to_named_tuple`, `rfl::from_named_tuple`, and `rfl::cli::read`.

## `std::variant` or `rfl::Variant` (externally tagged)

Another approach is to add external tags.
Expand Down
5 changes: 5 additions & 0 deletions include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "../Tuple.hpp"
#include "../internal/StringLiteral.hpp"
#include "../internal/field_aliases.hpp"
#include "../internal/has_flattened_tagged_union.hpp"
#include "../internal/has_reflection_type_v.hpp"
#include "../internal/has_reflector.hpp"
#include "../internal/is_alias.hpp"
Expand Down Expand Up @@ -316,6 +317,10 @@ void add_option_for_field(Options* _options) {
/// Adds the options of the top-level fields of T.
template <class T, class ProcessorsType>
void collect_options(Options* _options) {
static_assert(
!rfl::internal::has_flattened_tagged_union_v<T>,
"rfl::cli::read is not supported for structs containing "
"rfl::Flatten<rfl::TaggedUnion<...>>.");
using NT = option_fields_t<T, ProcessorsType>;
static_assert(
rfl::internal::no_alias_collisions<typename NT::Fields>(),
Expand Down
9 changes: 9 additions & 0 deletions include/rfl/from_named_tuple.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "internal/copy_from_named_tuple.hpp"
#include "internal/copy_from_tuple.hpp"
#include "internal/has_fields.hpp"
#include "internal/has_flattened_tagged_union.hpp"
#include "internal/move_from_named_tuple.hpp"
#include "internal/move_from_tuple.hpp"
#include "named_tuple_t.hpp"
Expand All @@ -23,6 +24,10 @@ namespace rfl {
/// @return An instance of struct T
template <class T, class NamedTupleType>
auto from_named_tuple(NamedTupleType&& _n) {
static_assert(
!internal::has_flattened_tagged_union_v<T>,
"rfl::from_named_tuple is not supported for structs containing "
"rfl::Flatten<rfl::TaggedUnion<...>>.");
using RequiredType = std::remove_cvref_t<rfl::named_tuple_t<T>>;
if constexpr (!std::is_same<std::remove_cvref_t<NamedTupleType>,
RequiredType>()) {
Expand Down Expand Up @@ -52,6 +57,10 @@ auto from_named_tuple(NamedTupleType&& _n) {
/// @return An instance of struct T
template <class T, class NamedTupleType>
auto from_named_tuple(const NamedTupleType& _n) {
static_assert(
!internal::has_flattened_tagged_union_v<T>,
"rfl::from_named_tuple is not supported for structs containing "
"rfl::Flatten<rfl::TaggedUnion<...>>.");
using RequiredType = std::remove_cvref_t<rfl::named_tuple_t<T>>;
if constexpr (!std::is_same<std::remove_cvref_t<NamedTupleType>,
RequiredType>()) {
Expand Down
8 changes: 7 additions & 1 deletion include/rfl/internal/cpp20/get_field_names.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "../is_alias.hpp"
#include "../is_flatten_field.hpp"
#include "../is_rename.hpp"
#include "../is_tagged_union.hpp"
#include "get_ith_field_from_fake_object.hpp"
#include "num_fields.hpp"

Expand Down Expand Up @@ -94,7 +95,12 @@ consteval auto get_field_name() {
using Name = typename UnwrappedType::Name;
return Name();
} else if constexpr (is_flatten_field_v<Type>) {
return get_field_names<std::remove_cvref_t<typename Type::Type>>();
using Inner = remove_all_ptrs_t<typename Type::Type>;
if constexpr (is_tagged_union_based<Inner>) {
return rfl::Literal<>();
} else {
return get_field_names<std::remove_cvref_t<typename Type::Type>>();
}
} else {
return rfl::Literal<get_field_name_str_lit<T, ptr>()>();
}
Expand Down
8 changes: 7 additions & 1 deletion include/rfl/internal/cpp26/get_field_names.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "../is_alias.hpp"
#include "../is_flatten_field.hpp"
#include "../is_rename.hpp"
#include "../is_tagged_union.hpp"
#include "bind_to_tuple.hpp"
#include "get_members.hpp"

Expand All @@ -32,7 +33,12 @@ consteval auto get_field_names_impl() {
using Name = typename UnwrappedType::Name;
return Name();
} else if constexpr (is_flatten_field_v<Type>) {
return get_field_names<std::remove_cvref_t<typename Type::Type>>();
using Inner = remove_all_ptrs_t<typename Type::Type>;
if constexpr (is_tagged_union_based<Inner>) {
return rfl::Literal<>();
} else {
return get_field_names<std::remove_cvref_t<typename Type::Type>>();
}
} else {
return FieldName();
}
Expand Down
4 changes: 3 additions & 1 deletion include/rfl/internal/has_default_val_v.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "../NamedTuple.hpp"
#include "../named_tuple_t.hpp"
#include "is_default_val_v.hpp"
#include "is_tagged_union.hpp"

namespace rfl::internal {

Expand All @@ -27,7 +28,8 @@ struct HasDefaultVal<NamedTuple<Fields...>> {
};

template <class T>
requires(std::is_class_v<T> && std::is_aggregate_v<T>)
requires(std::is_class_v<T> && std::is_aggregate_v<T> &&
!is_tagged_union_based<T>)
struct HasDefaultVal<T> : HasDefaultVal<named_tuple_t<T>> {};

template <class T, size_t N>
Expand Down
34 changes: 27 additions & 7 deletions include/rfl/internal/has_fields.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@

#include "../Tuple.hpp"
//#include "all_fields.hpp"
#include "has_reflection_type_v.hpp"
#include "has_reflector.hpp"
#include "is_field.hpp"
#include "is_flatten_field.hpp"
#include "ptr_tuple_t.hpp"
#include "is_named_tuple.hpp"
#include "is_tagged_union.hpp"
#include "ptr_tuple_t.hpp"


namespace rfl {
Expand All @@ -21,8 +24,12 @@ constexpr bool all_fields_or_flatten() {
[]<int _i>(std::integral_constant<int, _i>) -> bool {
using T = std::remove_cvref_t<tuple_element_t<_i, TupleType>>;
if constexpr (is_flatten_field_v<T>) {
return all_fields_or_flatten<
ptr_tuple_t<typename std::remove_pointer_t<T>::Type>>();
using Inner = remove_all_ptrs_t<typename std::remove_pointer_t<T>::Type>;
if constexpr (is_tagged_union_based<Inner> || is_named_tuple_v<Inner>) {
return true;
} else {
return all_fields_or_flatten<ptr_tuple_t<Inner>>();
}
} else {
return is_field_v<T>;
}
Expand All @@ -40,8 +47,14 @@ constexpr bool some_fields_or_flatten() {
[]<int _i>(std::integral_constant<int, _i>) -> bool {
using T = std::remove_cvref_t<tuple_element_t<_i, TupleType>>;
if constexpr (is_flatten_field_v<T>) {
return some_fields_or_flatten<
ptr_tuple_t<typename std::remove_pointer_t<T>::Type>>();
using Inner = remove_all_ptrs_t<typename std::remove_pointer_t<T>::Type>;
if constexpr (is_tagged_union_based<Inner>) {
return false;
} else if constexpr (is_named_tuple_v<Inner>) {
return true;
} else {
return some_fields_or_flatten<ptr_tuple_t<Inner>>();
}
} else {
return is_field_v<T>;
}
Expand All @@ -56,10 +69,17 @@ constexpr bool some_fields_or_flatten() {

template <class T>
constexpr bool has_fields() {
if constexpr (is_named_tuple_v<T>) {
using U = remove_all_ptrs_t<T>;
if constexpr (is_tagged_union_based<U>) {
return false;
} else if constexpr (has_reflection_type_v<U>) {
return has_fields<std::remove_cvref_t<typename U::ReflectionType>>();
} else if constexpr (has_read_reflector<U> || has_write_reflector<U>) {
return has_fields<std::remove_cvref_t<typename Reflector<U>::ReflType>>();
} else if constexpr (is_named_tuple_v<U>) {
return true;
} else {
using TupleType = ptr_tuple_t<T>;
using TupleType = ptr_tuple_t<U>;
if constexpr (some_fields_or_flatten<TupleType>()) {
static_assert(
all_fields_or_flatten<TupleType>(),
Expand Down
Loading
Loading