miniextendr_api/markers.rs
1//! Marker traits for proc-macro derived types.
2//!
3//! These marker traits identify types that have been derived with specific proc-macros.
4//! They enable compile-time type checking and blanket implementations.
5//!
6//! # Pattern
7//!
8//! Each derive macro generates an impl of its corresponding marker trait:
9//!
10//! | Derive Macro | Marker Trait |
11//! |--------------|--------------|
12//! | `#[derive(DataFrameRow)]` | [`DataFrameRow`] |
13//!
14//! The `Prefer*` derives (`PreferList`, `PreferExternalPtr`, `PreferRNativeType`,
15//! and the feature-gated `PreferVctrs`) emit their `IntoR` impl directly and carry
16//! **no** companion marker trait. A type's representation default is its `IntoR`
17//! impl; multiple marker-keyed blankets would overlap under coherence.
18
19/// Marker trait for types generated by `#[derive(DataFrameRow)]`.
20///
21/// Automatically implemented by the `DataFrameRow` derive macro. The derive
22/// macro emits a compile-time assertion against this trait for every struct-typed
23/// variant field, giving users a clear error when the inner type is missing the
24/// derive.
25///
26/// This trait has no supertrait — the actual data-frame conversion contract is on the
27/// generated companion `{Name}DataFrame` struct (which implements `ColumnSource`).
28/// The marker is used solely for compile-time assertions via
29/// `_assert_inner_is_dataframe_row::<T>()` generated by the outer derive.
30///
31/// You should not implement this trait manually.
32#[diagnostic::on_unimplemented(
33 message = "the trait `DataFrameRow` is not implemented for `{Self}`",
34 label = "add `#[derive(DataFrameRow)]` to `{Self}`, annotate the field \
35 with `#[dataframe(as_list)]` to keep it as an opaque list-column \
36 if `{Self}` implements `IntoList`, or annotate with \
37 `#[dataframe(as_factor)]` for unit-only enums",
38 note = "struct- and enum-typed variant fields are flattened by default into prefixed \
39 columns; the inner type must implement `DataFrameRow` for this to work",
40 note = "a `jiff` or `time` datetime field is one column when its type is spelled by \
41 its crate path (`jiff::Timestamp`, `time::Date`, …); a bare imported name is \
42 flattened like a struct"
43)]
44pub trait DataFrameRow {}
45
46/// The datetime types `#[derive(DataFrameRow)]` stores as one column (`T`) or
47/// one NA-able column (`Option<T>`) when a field spells them by crate path
48/// (`jiff::Timestamp`, `time::Date`, …).
49///
50/// The derive asserts this trait for each such field, so a field whose
51/// miniextendr-api feature is off names the feature to enable instead of a
52/// missing `IntoR` impl. Implemented for exactly the types with `IntoR` and
53/// `TryFromSexp` for `Vec<T>` and `Vec<Option<T>>`.
54///
55/// You should not implement this trait manually.
56#[diagnostic::on_unimplemented(
57 message = "`{Self}` is not a datetime column type here",
58 label = "a column of this type needs miniextendr-api's `jiff` or `time` feature",
59 note = "enable the `jiff` feature of miniextendr-api for `jiff::Timestamp`, `jiff::Zoned`, \
60 `jiff::SignedDuration` and `jiff::civil::Date`, or its `time` feature for \
61 `time::OffsetDateTime` and `time::Date`",
62 note = "a local module named `jiff` or `time` hides the crate: spell a local type \
63 `self::time::Date` (or `crate::…`) to flatten it as a struct"
64)]
65pub trait DataFrameDateTime {}
66
67#[cfg(feature = "jiff")]
68impl DataFrameDateTime for jiff::Timestamp {}
69#[cfg(feature = "jiff")]
70impl DataFrameDateTime for jiff::Zoned {}
71#[cfg(feature = "jiff")]
72impl DataFrameDateTime for jiff::SignedDuration {}
73#[cfg(feature = "jiff")]
74impl DataFrameDateTime for jiff::civil::Date {}
75#[cfg(feature = "time")]
76impl DataFrameDateTime for time::OffsetDateTime {}
77#[cfg(feature = "time")]
78impl DataFrameDateTime for time::Date {}
79
80/// Reflection trait for `#[derive(DataFrameRow)]` types, used for compile-time
81/// collision detection in outer `DataFrameRow` enums.
82///
83/// Automatically emitted by the `DataFrameRow` derive macro alongside `DataFrameRow`.
84/// The outer enum's codegen generates a `const _: ()` assertion that calls
85/// [`assert_no_payload_field_collision`] using these associated constants, producing
86/// a clear compile error when an inner payload field name (after outer prefix expansion)
87/// would produce the same R column as the outer discriminant column.
88///
89/// # Constants
90///
91/// - `FIELDS`: the resolved column names (after `#[dataframe(rename = "...")]`) that
92/// this type contributes directly. For structs: each column name. For enums: every
93/// payload field name across all variants (deduplicated).
94/// - `TAG`: the value of `#[dataframe(tag = "...")]` on this type, or `""` if absent.
95/// The outer macro uses this as the discriminant suffix for inner-enum nested fields.
96///
97/// You should not implement this trait manually.
98#[doc(hidden)]
99pub trait DataFramePayloadFields {
100 /// Resolved column names contributed by this type (post-rename, pre-prefix).
101 const FIELDS: &'static [&'static str];
102 /// Value of `#[dataframe(tag = "...")]` on this type, or `""` if absent.
103 const TAG: &'static str;
104}
105
106// region: const-eval collision helper
107
108/// Const-eval equality check for two `&str` values (stable since Rust 1.46).
109///
110/// Used by [`assert_no_payload_field_collision`] inside a `const {}` block.
111const fn const_str_eq(a: &str, b: &str) -> bool {
112 let a = a.as_bytes();
113 let b = b.as_bytes();
114 if a.len() != b.len() {
115 return false;
116 }
117 let mut i = 0;
118 while i < a.len() {
119 if a[i] != b[i] {
120 return false;
121 }
122 i += 1;
123 }
124 true
125}
126
127/// Compile-time assertion: no element of `fields` equals `discriminant_suffix`
128/// (the inner-enum's `#[dataframe(tag)]` value).
129///
130/// Called from `const _: ()` blocks emitted by the outer `DataFrameRow` derive for
131/// every `EnumResolvedField::Struct` nested-enum field:
132///
133/// ```rust,ignore
134/// const _: () = ::miniextendr_api::markers::assert_no_payload_field_collision(
135/// <Inner as ::miniextendr_api::markers::DataFramePayloadFields>::FIELDS,
136/// <Inner as ::miniextendr_api::markers::DataFramePayloadFields>::TAG,
137/// );
138/// ```
139///
140/// `fields` contains the resolved column names the inner type emits directly (not prefixed).
141/// `discriminant_suffix` is the inner enum's tag value (e.g. `"variant"`).
142///
143/// If any field name equals the discriminant suffix, the const evaluation panics with a
144/// message explaining the collision and suggesting a rename.
145#[doc(hidden)]
146pub const fn assert_no_payload_field_collision(fields: &[&str], discriminant_suffix: &str) {
147 let mut i = 0;
148 while i < fields.len() {
149 if const_str_eq(fields[i], discriminant_suffix) {
150 panic!(
151 "DataFrameRow inner-payload field collision: an inner enum payload field \
152 has the same name as the inner enum's discriminant tag. After outer prefix \
153 expansion this produces two columns with identical names, causing silent \
154 data corruption. Rename the inner payload field or add \
155 `#[dataframe(rename = \"...\")]` on it to use a different column name."
156 );
157 }
158 i += 1;
159 }
160}
161
162/// Compile-time assertion: no element of `sibling_cols` matches `concat!(base, "_", tag)`.
163///
164/// Called from `const _: ()` blocks emitted by the outer `DataFrameRow` derive for every
165/// nested-enum struct field, complementing the parse-time B1 check in `enum_expansion.rs`
166/// (which is hardcoded to the default tag `"variant"`). This assertion catches the
167/// non-default-tag case at compile time.
168///
169/// `sibling_cols` is a slice of all flat column names produced by non-Struct sibling fields
170/// in the same outer enum. `base` is the outer field name (e.g. `"kind"`). `tag` is the
171/// inner enum's `#[dataframe(tag = "...")]` value, retrieved via
172/// `<Inner as DataFramePayloadFields>::TAG`.
173///
174/// If `tag` is empty (structs emit no discriminant column), returns immediately as a no-op.
175///
176/// # Call site (emitted by proc-macro)
177///
178/// ```rust,ignore
179/// const _: () = ::miniextendr_api::markers::assert_no_sibling_field_collision(
180/// &["id", "other_col", /* … */],
181/// "kind",
182/// <Inner as ::miniextendr_api::markers::DataFramePayloadFields>::TAG,
183/// );
184/// ```
185#[doc(hidden)]
186pub const fn assert_no_sibling_field_collision(sibling_cols: &[&str], base: &str, tag: &str) {
187 // Structs don't emit a discriminant column, so tag == "" → no-op.
188 if tag.is_empty() {
189 return;
190 }
191 let expected_len = base.len() + 1 + tag.len();
192 let base_bytes = base.as_bytes();
193 let tag_bytes = tag.as_bytes();
194 let mut i = 0;
195 while i < sibling_cols.len() {
196 let col = sibling_cols[i].as_bytes();
197 if col.len() == expected_len {
198 // Check base prefix byte-by-byte.
199 let mut j = 0;
200 let mut base_match = true;
201 while j < base_bytes.len() {
202 if col[j] != base_bytes[j] {
203 base_match = false;
204 break;
205 }
206 j += 1;
207 }
208 // Check separator '_'.
209 let sep_match = col[base_bytes.len()] == b'_';
210 // Check tag suffix byte-by-byte.
211 let mut k = 0;
212 let mut tag_match = true;
213 let offset = base_bytes.len() + 1;
214 while k < tag_bytes.len() {
215 if col[offset + k] != tag_bytes[k] {
216 tag_match = false;
217 break;
218 }
219 k += 1;
220 }
221 if base_match && sep_match && tag_match {
222 panic!(
223 "DataFrameRow B1 sibling-collision: a sibling field in the outer enum \
224 produces a column name that collides with the discriminant column emitted \
225 by a nested inner enum. Rename the sibling field or use \
226 `#[dataframe(tag = \"...\")]` on the inner enum to choose a different \
227 discriminant column name."
228 );
229 }
230 }
231 i += 1;
232 }
233}
234// endregion
235
236// region: Coercion marker traits
237
238/// Marker trait for types that can widen to `i32` without loss.
239///
240/// Manually implemented for specific types to avoid conflicts with identity/
241/// special-case conversions. Used by blanket Coerce implementations.
242pub trait WidensToI32: Into<i32> + Copy {}
243
244/// Marker trait for types that can widen to `f64` without loss.
245///
246/// Manually implemented for specific types to avoid conflicts with identity/
247/// special-case conversions. Used by blanket Coerce implementations.
248pub trait WidensToF64: Into<f64> + Copy {}
249
250// Explicit marker impls for widening conversions (no blanket impl to avoid conflicts)
251impl WidensToI32 for i8 {}
252impl WidensToI32 for i16 {}
253impl WidensToI32 for u8 {}
254impl WidensToI32 for u16 {}
255
256impl WidensToF64 for f32 {}
257impl WidensToF64 for i8 {}
258impl WidensToF64 for i16 {}
259impl WidensToF64 for i32 {}
260impl WidensToF64 for u8 {}
261impl WidensToF64 for u16 {}
262impl WidensToF64 for u32 {}
263// endregion