photon-ring-derive 3.0.0

Derive macro for photon-ring's Pod trait
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Copyright 2026 Photon Ring Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Derive macros for `photon_ring::Pod` and `photon_ring::Message`.
//!
//! ## `Pod` derive
//!
//! ```ignore
//! #[repr(C)]
//! #[derive(photon_ring::Pod)]
//! struct Quote {
//!     price: f64,
//!     volume: u32,
//! }
//! ```
//!
//! This generates compile-time assertions that every field implements `Pod`,
//! plus `unsafe impl photon_ring::Pod for Quote {}`.
//!
//! **Note:** The macro does *not* add `#[repr(C)]` or `Clone`/`Copy` derives.
//! You must add those yourself for the `Pod` contract to hold.
//!
//! ## `Message` derive
//!
//! ```ignore
//! #[derive(photon_ring::Message)]
//! struct Order {
//!     price: f64,
//!     qty: u32,
//!     #[photon(as_enum)]
//!     side: Side,        // any #[repr(u8)] enum — requires #[photon(as_enum)]
//!     filled: bool,
//!     tag: Option<u32>,
//! }
//! ```
//!
//! Generates a Pod-compatible wire struct (`OrderWire`), a `From<Order> for
//! OrderWire`, and a back-conversion: a safe `From<OrderWire> for Order` for
//! enum-free structs, or an `unsafe OrderWire::into_domain()` method when
//! `#[photon(as_enum)]` fields are present. See [`derive_message`] for details.

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{
    parse_macro_input, Data, DeriveInput, Fields, GenericArgument, Meta, PathArguments, Type,
};

/// Derive `Pod` for a struct.
///
/// Requirements:
/// - Must be a struct (not enum or union).
/// - All fields must implement `Pod`.
/// - The user must add `#[repr(C)]`, `Clone`, and `Copy` themselves;
///   the macro only emits field assertions and `unsafe impl Pod`.
///
/// # Example
///
/// ```ignore
/// #[repr(C)]
/// #[derive(photon_ring::Pod)]
/// struct Tick {
///     price: f64,
///     volume: u32,
///     _pad: u32,
/// }
/// ```
#[proc_macro_derive(Pod)]
pub fn derive_pod(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    // Verify #[repr(C)] is present
    let has_repr_c = input.attrs.iter().any(|attr| {
        if !attr.path().is_ident("repr") {
            return false;
        }
        let mut found = false;
        if let Meta::List(list) = &attr.meta {
            let _ = list.parse_nested_meta(|nested| {
                if nested.path.is_ident("C") {
                    found = true;
                }
                Ok(())
            });
        }
        found
    });
    if !has_repr_c {
        return syn::Error::new_spanned(
            &input.ident,
            "Pod can only be derived for #[repr(C)] structs",
        )
        .to_compile_error()
        .into();
    }

    // Only structs are supported
    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => f.named.iter().collect::<Vec<_>>(),
            Fields::Unnamed(f) => f.unnamed.iter().collect::<Vec<_>>(),
            Fields::Unit => vec![],
        },
        _ => {
            return syn::Error::new_spanned(&input.ident, "Pod can only be derived for structs")
                .to_compile_error()
                .into();
        }
    };

    // Generate compile-time assertions that every field is Pod
    let field_assertions = fields.iter().map(|f| {
        let ty = &f.ty;
        quote! {
            const _: () = {
                fn _assert_pod<T: photon_ring::Pod>() {}
                fn _check() { _assert_pod::<#ty>(); }
            };
        }
    });

    let field_types: Vec<_> = fields.iter().map(|f| &f.ty).collect();

    let expanded = quote! {
        // Compile-time field checks
        #(#field_assertions)*

        // `Pod` forbids padding: an implicit gap is uninitialised memory, and the
        // `atomic-slots` payload copy reads the value as integer chunks. Proving
        // the size equals the sum of the field sizes is exactly the no-padding
        // condition, and it fails the build rather than the run.
        const _: () = {
            let sum = 0usize #( + core::mem::size_of::<#field_types>() )*;
            assert!(
                core::mem::size_of::<#name>() == sum,
                "Pod cannot be derived for a type with padding: add explicit \
                 padding fields, or reorder fields so none is inserted",
            );
        };

        // Safety: every field is Pod (asserted above), the type is #[repr(C)],
        // and it carries no padding, so every byte is initialised and every bit
        // pattern is a valid value.
        unsafe impl #impl_generics photon_ring::Pod for #name #ty_generics #where_clause {}
    };

    TokenStream::from(expanded)
}

// ---------------------------------------------------------------------------
// Message derive
// ---------------------------------------------------------------------------

/// Classification of a field type for wire conversion.
enum FieldKind {
    /// Numeric or array — passes through unchanged.
    Passthrough,
    /// `bool` → `u8`.
    Bool,
    /// `usize` → `u64`.
    Usize,
    /// `isize` → `i64`.
    Isize,
    /// `Option<T>` for a supported inner type. The wire struct gets a
    /// `X_value: <wire_ty>` field plus a `X_has: u8` presence flag. The two
    /// conversion snippets carry the per-type detail: `to_value` maps the
    /// unwrapped `v` to the wire integer, `from_value` maps the loaded `raw`
    /// wire integer back to the inner type.
    Option {
        wire_ty: proc_macro2::TokenStream,
        to_value: proc_macro2::TokenStream,
        from_value: proc_macro2::TokenStream,
        /// `usize`/`isize` inner types need the 64-bit-fit compile assertion.
        is_usize_isize: bool,
    },
    /// A `#[repr(u8)]` enum, explicitly marked with `#[photon(as_enum)]` → `u8`.
    Enum,
    /// Unrecognized type — will emit a compile error.
    Unsupported,
    /// Unsupported `Option<T>` inner type — will emit a compile error.
    UnsupportedOption(String),
}

/// Returns the type name string for a simple path type, or `None`.
fn type_name(ty: &Type) -> Option<String> {
    if let Type::Path(p) = ty {
        if let Some(seg) = p.path.segments.last() {
            return Some(seg.ident.to_string());
        }
    }
    None
}

/// Width rank for layout ordering: lower sorts earlier, so wider first. Types
/// the macro cannot size (arrays, user aliases) rank widest, since placing them
/// first cannot introduce a gap ahead of a narrower field.
fn align_rank(ty: &Type) -> u8 {
    // An array's alignment is its element's, so rank it that way; ranking it
    // widest would place `[u8; 3]` ahead of a `u64` and open an internal gap.
    if let Type::Array(a) = ty {
        return align_rank(&a.elem);
    }
    match type_name(ty).as_deref() {
        Some("u128") | Some("i128") => 0,
        Some("u64") | Some("i64") | Some("f64") | Some("usize") | Some("isize") => 1,
        Some("u32") | Some("f32") => 2,
        Some("u16") => 3,
        Some("u8") => 4,
        _ => 0,
    }
}

/// Classify a field's type into a [`FieldKind`].
fn classify(ty: &Type) -> FieldKind {
    match ty {
        // Arrays `[T; N]` — passthrough (must be Pod).
        Type::Array(_) => FieldKind::Passthrough,

        Type::Path(p) => {
            let seg = match p.path.segments.last() {
                Some(s) => s,
                None => return FieldKind::Unsupported,
            };
            let id = seg.ident.to_string();

            match id.as_str() {
                // Numerics — passthrough
                "u8" | "u16" | "u32" | "u64" | "u128" | "i8" | "i16" | "i32" | "i64" | "i128"
                | "f32" | "f64" => FieldKind::Passthrough,

                "bool" => FieldKind::Bool,
                "usize" => FieldKind::Usize,
                "isize" => FieldKind::Isize,

                "Option" => {
                    // Extract inner type from Option<T>
                    if let PathArguments::AngleBracketed(args) = &seg.arguments {
                        if let Some(GenericArgument::Type(inner)) = args.args.first() {
                            let name = type_name(inner).unwrap_or_default();
                            let opt =
                                |wire_ty, to_value, from_value, is_usize_isize| FieldKind::Option {
                                    wire_ty,
                                    to_value,
                                    from_value,
                                    is_usize_isize,
                                };
                            return match name.as_str() {
                                "bool" => opt(
                                    quote!(u8),
                                    quote!(if v { 1 } else { 0 }),
                                    quote!(raw != 0),
                                    false,
                                ),
                                "f32" => opt(
                                    quote!(u32),
                                    quote!(v.to_bits()),
                                    quote!(f32::from_bits(raw)),
                                    false,
                                ),
                                "f64" => opt(
                                    quote!(u64),
                                    quote!(v.to_bits()),
                                    quote!(f64::from_bits(raw)),
                                    false,
                                ),
                                "u128" => opt(quote!(u128), quote!(v), quote!(raw), false),
                                "i128" => {
                                    opt(quote!(u128), quote!(v as u128), quote!(raw as i128), false)
                                }
                                "usize" => {
                                    opt(quote!(u64), quote!(v as u64), quote!(raw as usize), true)
                                }
                                "isize" => {
                                    opt(quote!(i64), quote!(v as i64), quote!(raw as isize), true)
                                }
                                "u8" | "u16" | "u32" | "u64" => {
                                    opt(quote!(u64), quote!(v as u64), quote!(raw as #inner), false)
                                }
                                "i8" | "i16" | "i32" | "i64" => {
                                    opt(quote!(i64), quote!(v as i64), quote!(raw as #inner), false)
                                }
                                _ => FieldKind::UnsupportedOption(name),
                            };
                        }
                    }
                    FieldKind::UnsupportedOption(String::new())
                }

                // Anything else — unrecognized, require explicit attribute
                _ => FieldKind::Unsupported,
            }
        }

        _ => FieldKind::Unsupported,
    }
}

/// Derive a Pod-compatible wire struct with `From` conversions.
///
/// Given a struct with fields that may include `bool`, `Option<numeric>`,
/// `usize`/`isize`, and `#[repr(u8)]` enums, generates:
///
/// 1. **`{Name}Wire`** — a `#[repr(C)] Clone + Copy` struct with all fields
///    converted to Pod-safe types, plus `unsafe impl Pod`.
/// 2. **`From<Name> for {Name}Wire`** — converts the domain struct to wire.
/// 3. **`{Name}Wire::into_domain(self) -> Name`** — converts the wire struct
///    back. This is an `unsafe` method for structs containing enum fields
///    (since the enum discriminant is not validated), or a safe `From` impl
///    for structs without enum fields.
///
/// # Field type mappings
///
/// | Source type | Wire type | To wire | From wire |
/// |---|---|---|---|
/// | `f32`, `f64`, `u8`..`u128`, `i8`..`i128` | same | passthrough | passthrough |
/// | `usize` | `u64` | `as u64` | `as usize` |
/// | `isize` | `i64` | `as i64` | `as isize` |
/// | `bool` | `u8` | `if v { 1 } else { 0 }` | `v != 0` |
/// | `Option<T>` (T: unsigned ≤64-bit) | `X_value: u64, X_has: u8` | `Some(v) => (v as u64, 1), None => (0, 0)` | `has != 0 => Some(value as T), else None` |
/// | `Option<T>` (T: signed ≤64-bit) | `X_value: i64, X_has: u8` | `Some(v) => (v as i64, 1), None => (0, 0)` | `has != 0 => Some(value as T), else None` |
/// | `Option<u128>` | `X_value: u128, X_has: u8` | `Some(v) => (v, 1), None => (0, 0)` | `has != 0 => Some(value), else None` |
/// | `Option<i128>` | `X_value: u128, X_has: u8` | `Some(v) => (v as u128, 1), None => (0, 0)` | `has != 0 => Some(value as i128), else None` |
/// | `Option<usize>` | `X_value: u64, X_has: u8` | `Some(v) => (v as u64, 1), None => (0, 0)` | `has != 0 => Some(value as usize), else None` |
/// | `Option<isize>` | `X_value: i64, X_has: u8` | `Some(v) => (v as i64, 1), None => (0, 0)` | `has != 0 => Some(value as isize), else None` |
/// | `Option<f32>` | `X_value: u32, X_has: u8` | `Some(v) => (v.to_bits(), 1), None => (0, 0)` | `has != 0 => Some(f32::from_bits(value)), else None` |
/// | `Option<f64>` | `X_value: u64, X_has: u8` | `Some(v) => (v.to_bits(), 1), None => (0, 0)` | `has != 0 => Some(f64::from_bits(value)), else None` |
/// | `[T; N]` (T: Pod) | same | passthrough | passthrough |
/// | `#[photon(as_enum)] field: E` | `u8` | `v as u8` | `transmute(v)` (unsafe) |
///
/// # Enum fields
///
/// Enum fields **must** be annotated with `#[photon(as_enum)]` to opt in
/// to the `u8` wire encoding. Without this attribute, unrecognized types
/// produce a compile error. The enum must have `#[repr(u8)]` — the macro
/// emits a compile-time `size_of` check to enforce this.
///
/// Enum fields are stored as raw `u8` on the wire. Converting back requires
/// that the byte holds a valid discriminant. Because the macro cannot verify
/// enum variants at compile time, structs with enum fields generate an
/// `unsafe fn into_domain(self) -> DomainType` method on the wire struct
/// instead of a safe `From` impl. Callers must ensure enum fields contain
/// valid discriminants (which is always the case when the wire data was
/// produced by a valid domain value via `From<Domain> for Wire`).
///
/// # Example
///
/// ```ignore
/// #[repr(u8)]
/// #[derive(Clone, Copy)]
/// enum Side { Buy = 0, Sell = 1 }
///
/// #[derive(photon_ring::Message)]
/// struct Order {
///     price: f64,
///     qty: u32,
///     #[photon(as_enum)]
///     side: Side,
///     filled: bool,
///     tag: Option<u32>,
/// }
/// // Generates: OrderWire, From<Order> for OrderWire,
/// //            OrderWire::into_domain (unsafe, due to enum field)
/// ```
#[proc_macro_derive(Message, attributes(photon))]
pub fn derive_message(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let wire_name = format_ident!("{}Wire", name);

    // Only named structs are supported
    let fields = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => f.named.iter().collect::<Vec<_>>(),
            _ => {
                return syn::Error::new_spanned(
                    &input.ident,
                    "Message can only be derived for structs with named fields",
                )
                .to_compile_error()
                .into();
            }
        },
        _ => {
            return syn::Error::new_spanned(
                &input.ident,
                "Message can only be derived for structs",
            )
            .to_compile_error()
            .into();
        }
    };

    let mut wire_fields = Vec::new();
    let mut wire_types: Vec<proc_macro2::TokenStream> = Vec::new();
    // Rank by width so fields can be emitted widest-first: no internal padding.
    let mut wire_ranks: Vec<u8> = Vec::new();
    let mut to_wire = Vec::new();
    let mut from_wire = Vec::new();
    let mut assertions = Vec::new();
    let mut has_enum_fields = false;
    let mut has_usize_isize = false;

    for field in &fields {
        let fname = field.ident.as_ref().unwrap();
        let fty = &field.ty;

        // Check for #[photon(as_enum)] attribute
        let is_explicit_enum = field.attrs.iter().any(|attr| {
            if attr.path().is_ident("photon") {
                if let Ok(meta) = attr.parse_args::<syn::Ident>() {
                    return meta == "as_enum";
                }
            }
            false
        });

        let kind = if is_explicit_enum {
            FieldKind::Enum
        } else {
            classify(fty)
        };

        match kind {
            FieldKind::Passthrough => {
                // A passthrough field lands in the wire struct unchanged, and the
                // wire struct gets `unsafe impl Pod`. Prove the field really is
                // Pod: `[bool; 2]` and an alias that merely looks like a
                // primitive would otherwise ride through on syntax alone.
                assertions.push(quote! {
                    const _: () = {
                        fn _assert_pod<T: photon_ring::Pod>() {}
                        fn _check() { _assert_pod::<#fty>(); }
                    };
                });
                wire_fields.push(quote! { pub #fname: #fty });
                wire_types.push(quote!(#fty));
                wire_ranks.push(align_rank(fty));
                to_wire.push(quote! { #fname: src.#fname });
                from_wire.push(quote! { #fname: src.#fname });
            }
            FieldKind::Bool => {
                wire_fields.push(quote! { pub #fname: u8 });
                wire_types.push(quote!(u8));
                wire_ranks.push(4);
                to_wire.push(quote! { #fname: if src.#fname { 1 } else { 0 } });
                from_wire.push(quote! { #fname: src.#fname != 0 });
            }
            FieldKind::Usize => {
                has_usize_isize = true;
                wire_fields.push(quote! { pub #fname: u64 });
                wire_types.push(quote!(u64));
                wire_ranks.push(1);
                to_wire.push(quote! { #fname: src.#fname as u64 });
                from_wire.push(quote! { #fname: src.#fname as usize });
            }
            FieldKind::Isize => {
                has_usize_isize = true;
                wire_fields.push(quote! { pub #fname: i64 });
                wire_types.push(quote!(i64));
                wire_ranks.push(1);
                to_wire.push(quote! { #fname: src.#fname as i64 });
                from_wire.push(quote! { #fname: src.#fname as isize });
            }
            FieldKind::Option {
                wire_ty,
                to_value,
                from_value,
                is_usize_isize,
            } => {
                if is_usize_isize {
                    has_usize_isize = true;
                }
                let value_field = format_ident!("{}_value", fname);
                let has_field = format_ident!("{}_has", fname);
                wire_fields.push(quote! { pub #value_field: #wire_ty });
                wire_types.push(quote!(#wire_ty));
                wire_ranks.push(match wire_ty.to_string().as_str() {
                    "u128" => 0,
                    "u32" => 2,
                    "u16" => 3,
                    "u8" => 4,
                    _ => 1,
                });
                wire_fields.push(quote! { pub #has_field: u8 });
                wire_types.push(quote!(u8));
                wire_ranks.push(4);
                to_wire.push(quote! {
                    #value_field: match src.#fname {
                        Some(v) => #to_value,
                        None => 0,
                    }
                });
                to_wire.push(quote! {
                    #has_field: if src.#fname.is_some() { 1 } else { 0 }
                });
                from_wire.push(quote! {
                    #fname: if src.#has_field != 0 {
                        let raw = src.#value_field;
                        Some(#from_value)
                    } else {
                        None
                    }
                });
            }
            FieldKind::Enum => {
                has_enum_fields = true;
                wire_fields.push(quote! { pub #fname: u8 });
                wire_types.push(quote!(u8));
                wire_ranks.push(4);
                to_wire.push(quote! { #fname: src.#fname as u8 });
                from_wire.push(quote! {
                    // SAFETY: This transmute converts a raw u8 back to the enum type.
                    // This is sound ONLY when the byte contains a valid discriminant.
                    // The wire struct should only be constructed via `From<DomainType>`,
                    // which guarantees valid discriminants. Constructing the wire struct
                    // from arbitrary bytes and calling `into_domain()` is undefined
                    // behavior if any enum field holds an invalid discriminant.
                    #fname: unsafe { core::mem::transmute::<u8, #fty>(src.#fname) }
                });
                // Compile-time assertion: enum must be 1 byte (#[repr(u8)])
                let msg = format!(
                    "Message derive: field `{}` has type `{}` which is not 1 byte. \
                     Enum fields must have #[repr(u8)].",
                    fname,
                    quote! { #fty },
                );
                let msg_lit = syn::LitStr::new(&msg, Span::call_site());
                assertions.push(quote! {
                    const _: () = {
                        assert!(
                            core::mem::size_of::<#fty>() == 1,
                            #msg_lit,
                        );
                    };
                });
            }
            FieldKind::Unsupported => {
                let msg = format!(
                    "Unsupported field type `{}`. Use #[photon(as_enum)] for #[repr(u8)] enum fields, \
                     or convert to a numeric type manually.",
                    quote!(#fty),
                );
                return syn::Error::new_spanned(fty, msg).to_compile_error().into();
            }
            FieldKind::UnsupportedOption(inner_name) => {
                let msg = format!(
                    "Message derive: field `{}` has unsupported type `Option<{}>`. \
                     Only Option<bool>, Option<integer>, Option<f32>, and Option<f64> \
                     are supported.",
                    fname, inner_name,
                );
                return syn::Error::new_spanned(fty, msg).to_compile_error().into();
            }
        }
    }

    // H5: Compile-time assertion that usize/isize fit in u64/i64 (documents
    // the 64-bit assumption and fails loudly on platforms where it does not hold).
    if has_usize_isize {
        assertions.push(quote! {
            const _: () = assert!(
                core::mem::size_of::<usize>() <= core::mem::size_of::<u64>(),
                "photon-ring Message derive requires usize to fit in u64",
            );
        });
    }

    // If the struct has enum fields, generate an unsafe `into_domain` method
    // instead of a safe `From` impl to avoid exposing transmute through safe code.
    let from_wire_impl = if has_enum_fields {
        quote! {
            impl #wire_name {
                /// Convert wire struct back to domain struct.
                ///
                /// # Safety
                ///
                /// Enum fields are stored as raw `u8` and converted back via
                /// `core::mem::transmute`. The caller **must** ensure every enum
                /// field contains a valid discriminant value. This is guaranteed
                /// when the wire struct was produced by `From<DomainType>` — but
                /// constructing the wire struct from arbitrary bytes (e.g. reading
                /// raw memory, deserialization) and calling this method is
                /// **undefined behavior** if any enum field holds an invalid
                /// discriminant.
                #[inline]
                pub unsafe fn into_domain(self) -> #name {
                    let src = self;
                    #name {
                        #(#from_wire),*
                    }
                }
            }
        }
    } else {
        quote! {
            impl From<#wire_name> for #name {
                #[inline]
                fn from(src: #wire_name) -> Self {
                    #name {
                        #(#from_wire),*
                    }
                }
            }
        }
    };

    // C3: Add a doc warning on the wire struct when it contains enum fields
    let wire_struct_doc = if has_enum_fields {
        quote! {
            /// Auto-generated Pod-compatible wire struct for the domain type.
            ///
            /// # Warning
            ///
            /// This struct contains enum fields stored as raw `u8`. Constructing
            /// it from arbitrary bytes (not via `From<DomainType>`) and then calling
            /// `into_domain()` can cause **undefined behavior** if any enum field
            /// holds an invalid discriminant value.
        }
    } else {
        quote! {
            /// Auto-generated Pod-compatible wire struct for the domain type.
        }
    };

    // Emit widest-first so the C layout cannot insert gaps between fields, then
    // pad the tail to a whole number of alignment units. Together these make the
    // generated struct padding-free, which `Pod` requires.
    let mut ordered: Vec<usize> = (0..wire_fields.len()).collect();
    ordered.sort_by_key(|&i| wire_ranks[i]);
    let wire_fields: Vec<_> = ordered.iter().map(|&i| wire_fields[i].clone()).collect();
    let wire_types: Vec<_> = ordered.iter().map(|&i| wire_types[i].clone()).collect();

    let pad_const = format_ident!("__{}_TAIL_PAD", wire_name.to_string().to_uppercase());

    let expanded = quote! {
        // Compile-time assertions
        #(#assertions)*

        #[doc(hidden)]
        const #pad_const: usize = {
            let sum = 0usize #( + core::mem::size_of::<#wire_types>() )*;
            let align = { let mut a = 1usize; #( { let f = core::mem::align_of::<#wire_types>(); if f > a { a = f; } } )* a };
            (align - sum % align) % align
        };

        #wire_struct_doc
        #[repr(C)]
        #[derive(Clone, Copy)]
        pub struct #wire_name {
            #(#wire_fields,)*
            /// Explicit tail padding. `Pod` forbids implicit padding, because an
            /// uninitialised gap is undefined to read as part of a value; making
            /// it a real field means every byte is initialised.
            pub _pad: [u8; #pad_const],
        }

        // `Pod` forbids padding, and a #[repr(C)] struct of mixed-width numerics
        // readily acquires it. An implicit gap is uninitialised memory, and the
        // `atomic-slots` payload copy reads the value as integer chunks, so a
        // padded wire struct is undefined behaviour rather than merely wasteful.
        // Size equal to the sum of the field sizes is exactly the no-padding
        // condition. If this fails, order the source struct's fields widest
        // first and the generated layout becomes padding-free.
        const _: () = {
            let sum = 0usize #( + core::mem::size_of::<#wire_types>() )* + #pad_const;
            assert!(
                core::mem::size_of::<#wire_name>() == sum,
                "photon-ring: the generated wire struct has internal padding, which \
                 is not a valid Pod. The macro orders fields by width, but cannot \
                 see through a type alias, so one of them landed out of order. \
                 Use a concrete primitive or array type for that field, or add an \
                 explicit padding field to close the gap.",
            );
        };

        // Safety: all fields of the wire struct are plain numeric types
        // (u8, u32, u64, f32, f64, etc.) where every bit pattern is valid, and
        // the assertion above establishes there is no padding between them.
        unsafe impl photon_ring::Pod for #wire_name {}

        impl From<#name> for #wire_name {
            #[inline]
            fn from(src: #name) -> Self {
                #wire_name {
                    #(#to_wire,)*
                    _pad: [0; #pad_const],
                }
            }
        }

        #from_wire_impl
    };

    TokenStream::from(expanded)
}