vexil-lang 0.5.0

Compiler library for the Vexil schema definition language — lexer, parser, IR, and type checker
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! # Stability: Tier 2
//!
//! Type checker: validates the IR and computes wire sizes.
//!
//! Detects infinite recursion, verifies encoding annotations match their
//! target types, and fills in `wire_size` / `wire_bits` / `wire_bytes`
//! fields on messages, enums, flags, and unions.

use std::collections::HashSet;

use crate::ast::{EnumBacking, PrimitiveType, SemanticType, TypeExpr};
use crate::diagnostic::{Diagnostic, ErrorClass};
use crate::ir::{
    CompiledSchema, Encoding, FieldEncoding, ResolvedType, TypeDef, TypeId, WireSize,
    POISON_TYPE_ID,
};

/// Type-check and compute wire sizes. Mutates the schema to fill in wire_size fields.
pub fn check(compiled: &mut CompiledSchema) -> Vec<Diagnostic> {
    let mut diags = Vec::new();

    // Check recursive types.
    check_recursion(compiled, &mut diags);

    let decl_ids: Vec<TypeId> = compiled.declarations.clone();

    // Pass 1: compute wire_bits for enums and wire_bytes for flags.
    // These must be set before message/union wire sizes are computed so that
    // named_type_wire_size can read the correct values for enum/flags fields.
    for &id in &decl_ids {
        match compiled.registry.get(id) {
            Some(TypeDef::Enum(en)) => {
                let wire_bits = compute_enum_wire_bits(en);
                if let Some(TypeDef::Enum(en)) = compiled.registry.get_mut(id) {
                    en.wire_bits = wire_bits;
                }
            }
            Some(TypeDef::Flags(fl)) => {
                let wire_bytes = compute_flags_wire_bytes(fl);
                if let Some(TypeDef::Flags(fl)) = compiled.registry.get_mut(id) {
                    fl.wire_bytes = wire_bytes;
                }
            }
            _ => {}
        }
    }

    // Pass 2: compute wire sizes for messages and unions.
    for &id in &decl_ids {
        if let Some(def) = compiled.registry.get(id) {
            match def {
                TypeDef::Message(_) => {
                    let mut computing = HashSet::new();
                    let ws = compute_message_wire_size(id, compiled, &mut computing);
                    if let Some(TypeDef::Message(msg)) = compiled.registry.get_mut(id) {
                        msg.wire_size = Some(ws);
                    }
                }
                TypeDef::Union(_) => {
                    let mut computing = HashSet::new();
                    let ws = compute_union_wire_size(id, compiled, &mut computing);
                    if let Some(TypeDef::Union(un)) = compiled.registry.get_mut(id) {
                        un.wire_size = Some(ws);
                    }
                }
                _ => {}
            }
        }
    }

    // Check trait conformance and portable function-body semantics.
    check_impl_conformance(compiled, &mut diags);

    diags
}

// ---------------------------------------------------------------------------
// Wire size computation
// ---------------------------------------------------------------------------

/// Sentinel returned when we detect a cycle mid-computation (valid recursive
/// types with indirection are always variable-length and unbounded).
fn cycle_wire_size() -> WireSize {
    WireSize::Variable {
        min_bits: 0,
        max_bits: None,
    }
}

fn compute_type_wire_size(
    ty: &ResolvedType,
    enc: &FieldEncoding,
    compiled: &CompiledSchema,
    computing: &mut HashSet<TypeId>,
) -> WireSize {
    match &enc.encoding {
        Encoding::Varint => varint_wire_size(ty),
        Encoding::ZigZag => zigzag_wire_size(ty),
        Encoding::Delta(inner) => {
            let inner_enc = FieldEncoding {
                encoding: *inner.clone(),
                limit: enc.limit,
            };
            compute_type_wire_size(ty, &inner_enc, compiled, computing)
        }
        Encoding::Default => compute_resolved_type_wire_size(ty, compiled, computing),
    }
}

fn compute_resolved_type_wire_size(
    ty: &ResolvedType,
    compiled: &CompiledSchema,
    computing: &mut HashSet<TypeId>,
) -> WireSize {
    match ty {
        ResolvedType::Primitive(p) => primitive_wire_size(p),
        ResolvedType::SubByte(s) => WireSize::Fixed(s.bits as u64),
        ResolvedType::Semantic(s) => semantic_wire_size(s),
        ResolvedType::Named(id) => named_type_wire_size(*id, compiled, computing),
        ResolvedType::Optional(inner) => {
            // Optional is an indirection point — contents don't recurse directly.
            // We still need the inner size for the max bound, but if it cycles we
            // just use None (unbounded).
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            match inner_ws {
                WireSize::Fixed(bits) => WireSize::Variable {
                    min_bits: 1,
                    max_bits: Some(1 + bits),
                },
                WireSize::Variable { max_bits, .. } => WireSize::Variable {
                    min_bits: 1,
                    max_bits: max_bits.map(|m| 1 + m),
                },
            }
        }
        ResolvedType::Array(_) => WireSize::Variable {
            min_bits: 8,
            max_bits: None,
        },
        ResolvedType::FixedArray(inner, size) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            match inner_ws {
                WireSize::Fixed(bits) => WireSize::Fixed(bits * size),
                WireSize::Variable { min_bits, .. } => WireSize::Variable {
                    min_bits: min_bits * size,
                    max_bits: None,
                },
            }
        }
        ResolvedType::Map(_, _) | ResolvedType::Set(_) => WireSize::Variable {
            min_bits: 8,
            max_bits: None,
        },
        ResolvedType::Result(ok, err) => {
            let ok_ws = compute_resolved_type_wire_size(ok, compiled, computing);
            let err_ws = compute_resolved_type_wire_size(err, compiled, computing);
            let min_ok = wire_size_min_bits(&ok_ws);
            let min_err = wire_size_min_bits(&err_ws);
            let min = 1 + std::cmp::min(min_ok, min_err);
            let max = match (wire_size_max_bits(&ok_ws), wire_size_max_bits(&err_ws)) {
                (Some(a), Some(b)) => Some(1 + std::cmp::max(a, b)),
                _ => None,
            };
            WireSize::Variable {
                min_bits: min,
                max_bits: max,
            }
        }
        ResolvedType::Vec2(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 2)
        }
        ResolvedType::Vec3(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 3)
        }
        ResolvedType::Vec4(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 4)
        }
        ResolvedType::Quat(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 4)
        }
        ResolvedType::Mat3(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 9)
        }
        ResolvedType::Mat4(inner) => {
            let inner_ws = compute_resolved_type_wire_size(inner, compiled, computing);
            multiply_wire_size(&inner_ws, 16)
        }
        ResolvedType::BitsInline(names) => WireSize::Fixed(names.len() as u64),
    }
}

fn primitive_wire_size(p: &PrimitiveType) -> WireSize {
    let bits = match p {
        PrimitiveType::Bool => 1,
        PrimitiveType::U8 | PrimitiveType::I8 => 8,
        PrimitiveType::U16 | PrimitiveType::I16 => 16,
        PrimitiveType::U32 | PrimitiveType::I32 | PrimitiveType::F32 | PrimitiveType::Fixed32 => 32,
        PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::F64 | PrimitiveType::Fixed64 => 64,
        PrimitiveType::Void => 0,
    };
    WireSize::Fixed(bits)
}

fn semantic_wire_size(s: &SemanticType) -> WireSize {
    match s {
        SemanticType::String | SemanticType::Bytes => WireSize::Variable {
            min_bits: 0,
            max_bits: None,
        },
        SemanticType::Rgb => WireSize::Fixed(24),
        SemanticType::Uuid => WireSize::Fixed(128),
        SemanticType::Timestamp => WireSize::Fixed(64),
        SemanticType::Hash => WireSize::Fixed(256),
    }
}

fn varint_wire_size(ty: &ResolvedType) -> WireSize {
    let max_bits = match ty {
        ResolvedType::Primitive(PrimitiveType::U16) => 24,
        ResolvedType::Primitive(PrimitiveType::U32) => 40,
        ResolvedType::Primitive(PrimitiveType::U64) => 80,
        _ => 80,
    };
    WireSize::Variable {
        min_bits: 8,
        max_bits: Some(max_bits),
    }
}

fn zigzag_wire_size(ty: &ResolvedType) -> WireSize {
    let max_bits = match ty {
        ResolvedType::Primitive(PrimitiveType::I16) => 24,
        ResolvedType::Primitive(PrimitiveType::I32) => 40,
        ResolvedType::Primitive(PrimitiveType::I64) => 80,
        _ => 80,
    };
    WireSize::Variable {
        min_bits: 8,
        max_bits: Some(max_bits),
    }
}

fn named_type_wire_size(
    id: TypeId,
    compiled: &CompiledSchema,
    computing: &mut HashSet<TypeId>,
) -> WireSize {
    // If we're already computing this type's wire size, we've hit a cycle.
    // Return a sentinel — the type is recursive via indirection so it's unbounded.
    if computing.contains(&id) {
        return cycle_wire_size();
    }

    match compiled.registry.get(id) {
        Some(TypeDef::Enum(en)) => {
            // wire_bits is computed in pass 1 before message wire sizes (pass 2),
            // so it is always set by the time we reach here.
            WireSize::Fixed(u64::from(en.wire_bits))
        }
        Some(TypeDef::Flags(fl)) => {
            // wire_bytes is computed in pass 1 before message wire sizes (pass 2).
            WireSize::Fixed(u64::from(fl.wire_bytes) * 8)
        }
        Some(TypeDef::Newtype(nt)) => {
            let terminal = nt.terminal_type.clone();
            compute_resolved_type_wire_size(&terminal, compiled, computing)
        }
        Some(TypeDef::Message(msg)) => {
            if let Some(ws) = msg.wire_size.clone() {
                return ws;
            }
            compute_message_wire_size(id, compiled, computing)
        }
        Some(TypeDef::Union(un)) => {
            if let Some(ws) = un.wire_size.clone() {
                return ws;
            }
            compute_union_wire_size(id, compiled, computing)
        }
        Some(TypeDef::Config(_))
        | Some(TypeDef::GenericAlias(_))
        | Some(TypeDef::Trait(_))
        | Some(TypeDef::Impl(_))
        | None => WireSize::Variable {
            min_bits: 0,
            max_bits: None,
        },
    }
}

fn compute_message_wire_size(
    id: TypeId,
    compiled: &CompiledSchema,
    computing: &mut HashSet<TypeId>,
) -> WireSize {
    let msg = match compiled.registry.get(id) {
        Some(TypeDef::Message(m)) => m,
        _ => return WireSize::Fixed(0),
    };

    if msg.fields.is_empty() {
        return WireSize::Fixed(0);
    }

    // Clone fields to avoid borrow conflicts when we call back into compiled.
    let fields: Vec<(ResolvedType, FieldEncoding)> = msg
        .fields
        .iter()
        .map(|f| (f.resolved_type.clone(), f.encoding.clone()))
        .collect();

    computing.insert(id);

    let mut total_min: u64 = 0;
    let mut total_max: Option<u64> = Some(0);
    let mut is_variable = false;

    for (resolved_type, encoding) in &fields {
        let ws = compute_type_wire_size(resolved_type, encoding, compiled, computing);
        match ws {
            WireSize::Fixed(bits) => {
                total_min += bits;
                if let Some(ref mut max) = total_max {
                    *max += bits;
                }
            }
            WireSize::Variable { min_bits, max_bits } => {
                is_variable = true;
                total_min += min_bits;
                match (total_max, max_bits) {
                    (Some(cur), Some(field_max)) => total_max = Some(cur + field_max),
                    _ => total_max = None,
                }
            }
        }
    }

    computing.remove(&id);

    if is_variable {
        WireSize::Variable {
            min_bits: total_min,
            max_bits: total_max,
        }
    } else {
        WireSize::Fixed(total_min)
    }
}

fn compute_union_wire_size(
    id: TypeId,
    compiled: &CompiledSchema,
    computing: &mut HashSet<TypeId>,
) -> WireSize {
    let un = match compiled.registry.get(id) {
        Some(TypeDef::Union(u)) => u,
        _ => return WireSize::Fixed(0),
    };

    if un.variants.is_empty() {
        return WireSize::Variable {
            min_bits: 8,
            max_bits: Some(8),
        };
    }

    let tag_min: u64 = 8;
    let mut max_variant_bits: Option<u64> = Some(0);
    let mut min_variant_bits: u64 = u64::MAX;

    // Clone variant fields to avoid borrow conflicts.
    let variants: Vec<Vec<(ResolvedType, FieldEncoding)>> = un
        .variants
        .iter()
        .map(|v| {
            v.fields
                .iter()
                .map(|f| (f.resolved_type.clone(), f.encoding.clone()))
                .collect()
        })
        .collect();

    computing.insert(id);

    for variant_fields in &variants {
        let mut var_min: u64 = 0;
        let mut var_max: Option<u64> = Some(0);

        for (resolved_type, encoding) in variant_fields {
            let ws = compute_type_wire_size(resolved_type, encoding, compiled, computing);
            match ws {
                WireSize::Fixed(bits) => {
                    var_min += bits;
                    if let Some(ref mut max) = var_max {
                        *max += bits;
                    }
                }
                WireSize::Variable { min_bits, max_bits } => {
                    var_min += min_bits;
                    match (var_max, max_bits) {
                        (Some(cur), Some(field_max)) => var_max = Some(cur + field_max),
                        _ => var_max = None,
                    }
                }
            }
        }

        min_variant_bits = std::cmp::min(min_variant_bits, var_min);
        match (max_variant_bits, var_max) {
            (Some(cur), Some(v)) => max_variant_bits = Some(std::cmp::max(cur, v)),
            _ => max_variant_bits = None,
        }
    }

    computing.remove(&id);

    if min_variant_bits == u64::MAX {
        min_variant_bits = 0;
    }

    WireSize::Variable {
        min_bits: tag_min + min_variant_bits,
        max_bits: max_variant_bits.map(|m| tag_min + m),
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn wire_size_min_bits(ws: &WireSize) -> u64 {
    match ws {
        WireSize::Fixed(bits) => *bits,
        WireSize::Variable { min_bits, .. } => *min_bits,
    }
}

fn wire_size_max_bits(ws: &WireSize) -> Option<u64> {
    match ws {
        WireSize::Fixed(bits) => Some(*bits),
        WireSize::Variable { max_bits, .. } => *max_bits,
    }
}

/// Multiply a wire size by a constant factor (for geometric types).
fn multiply_wire_size(ws: &WireSize, multiplier: u64) -> WireSize {
    match ws {
        WireSize::Fixed(bits) => WireSize::Fixed(bits * multiplier),
        WireSize::Variable { min_bits, max_bits } => WireSize::Variable {
            min_bits: min_bits * multiplier,
            max_bits: max_bits.map(|m| m * multiplier),
        },
    }
}

// ---------------------------------------------------------------------------
// Recursive type detection
// ---------------------------------------------------------------------------

/// DFS state for the recursive type check.
struct RecursionState<'a> {
    /// TypeIds on the current path reached without passing through an
    /// indirection point (Optional, Array, Map, Result, Union).
    /// A cycle here is infinite recursion.
    direct_path: HashSet<TypeId>,
    /// TypeIds we have already fully explored — prevents re-entering
    /// already-finished subtrees and infinite loops through mutual recursion.
    visited: HashSet<TypeId>,
    compiled: &'a CompiledSchema,
    origin_span: crate::span::Span,
    diags: &'a mut Vec<Diagnostic>,
}

/// For each message type, DFS through field types to detect direct infinite cycles.
fn check_recursion(compiled: &CompiledSchema, diags: &mut Vec<Diagnostic>) {
    for &id in &compiled.declarations {
        if let Some(TypeDef::Message(msg)) = compiled.registry.get(id) {
            let mut state = RecursionState {
                direct_path: {
                    let mut s = HashSet::new();
                    s.insert(id);
                    s
                },
                visited: HashSet::new(),
                compiled,
                origin_span: msg.span,
                diags,
            };
            let fields: Vec<(ResolvedType, FieldEncoding)> = msg
                .fields
                .iter()
                .map(|f| (f.resolved_type.clone(), f.encoding.clone()))
                .collect();
            for (ty, _) in &fields {
                walk_type_for_recursion(ty, true, &mut state);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// wire_bits / wire_bytes helpers
// ---------------------------------------------------------------------------

fn compute_enum_wire_bits(en: &crate::ir::EnumDef) -> u8 {
    if let Some(backing) = &en.backing {
        return match backing {
            EnumBacking::U8 => 8,
            EnumBacking::U16 => 16,
            EnumBacking::U32 => 32,
            EnumBacking::U64 => 64,
        };
    }
    let max_ordinal = en.variants.iter().map(|v| v.ordinal).max().unwrap_or(0);
    let min_bits: u8 = if max_ordinal == 0 {
        1
    } else {
        let n = u64::from(max_ordinal) + 1;
        // Number of bits needed to represent n distinct values: ceil(log2(n))
        // = bit_width(n - 1) = 64 - leading_zeros(n - 1), clamped to at least 1.
        let leading = (n - 1).leading_zeros();
        let bits = 64u8.saturating_sub(leading as u8);
        std::cmp::max(bits, 1)
    };
    if en.annotations.non_exhaustive {
        std::cmp::max(min_bits, 8)
    } else {
        std::cmp::max(min_bits, 1)
    }
}

fn compute_flags_wire_bytes(fl: &crate::ir::FlagsDef) -> u8 {
    let max_bit = fl.bits.iter().map(|b| b.bit).max().unwrap_or(0);
    match max_bit {
        0..=7 => 1,
        8..=15 => 2,
        16..=31 => 4,
        _ => 8,
    }
}

fn walk_type_for_recursion(ty: &ResolvedType, direct: bool, state: &mut RecursionState<'_>) {
    match ty {
        ResolvedType::Named(id) => {
            // Direct cycle = infinite recursion.
            if direct && state.direct_path.contains(id) {
                state.diags.push(Diagnostic::error(
                    state.origin_span,
                    ErrorClass::RecursiveTypeInfinite,
                    "type contains infinite direct recursion",
                ));
                return;
            }

            // Indirect back-reference to a node on the direct path (e.g. via
            // array/optional) — this is valid recursion with indirection.
            if !direct && state.direct_path.contains(id) {
                return;
            }

            // Already fully explored this node — no need to descend again.
            if state.visited.contains(id) {
                return;
            }

            state.visited.insert(*id);

            match state.compiled.registry.get(*id) {
                Some(TypeDef::Message(msg)) => {
                    let was_new = if direct {
                        state.direct_path.insert(*id)
                    } else {
                        false
                    };
                    let fields: Vec<(ResolvedType, FieldEncoding)> = msg
                        .fields
                        .iter()
                        .map(|f| (f.resolved_type.clone(), f.encoding.clone()))
                        .collect();
                    for (field_ty, _) in &fields {
                        walk_type_for_recursion(field_ty, direct, state);
                    }
                    if was_new {
                        state.direct_path.remove(id);
                    }
                }
                Some(TypeDef::Union(un)) => {
                    // Union dispatch = indirection point.
                    let variant_fields: Vec<Vec<ResolvedType>> = un
                        .variants
                        .iter()
                        .map(|v| v.fields.iter().map(|f| f.resolved_type.clone()).collect())
                        .collect();
                    for fields in &variant_fields {
                        for field_ty in fields {
                            walk_type_for_recursion(field_ty, false, state);
                        }
                    }
                }
                Some(TypeDef::Newtype(nt)) => {
                    let inner = nt.inner_type.clone();
                    walk_type_for_recursion(&inner, direct, state);
                }
                _ => {} // Enum, Flags, Config, stub — terminal
            }
        }
        ResolvedType::Optional(inner) | ResolvedType::Array(inner) => {
            walk_type_for_recursion(inner, false, state);
        }
        ResolvedType::FixedArray(inner, _) => {
            walk_type_for_recursion(inner, false, state);
        }
        ResolvedType::Map(k, v) => {
            walk_type_for_recursion(k, false, state);
            walk_type_for_recursion(v, false, state);
        }
        ResolvedType::Set(inner) => {
            walk_type_for_recursion(inner, false, state);
        }
        ResolvedType::Result(ok, err) => {
            walk_type_for_recursion(ok, false, state);
            walk_type_for_recursion(err, false, state);
        }
        ResolvedType::Vec2(inner)
        | ResolvedType::Vec3(inner)
        | ResolvedType::Vec4(inner)
        | ResolvedType::Quat(inner)
        | ResolvedType::Mat3(inner)
        | ResolvedType::Mat4(inner) => {
            walk_type_for_recursion(inner, false, state);
        }
        _ => {} // Primitive, SubByte, Semantic — terminal
    }
}

// ---------------------------------------------------------------------------
// Trait Conformance Checking
// ---------------------------------------------------------------------------

use crate::ir::{ImplDef, TraitDef};
use smol_str::SmolStr;

/// Check that all impls in the schema conform to their traits.
fn check_impl_conformance(compiled: &CompiledSchema, diags: &mut Vec<Diagnostic>) {
    for (impl_id, impl_def) in compiled.impls() {
        let Some(trait_id) = compiled.registry.impl_trait_id(impl_id) else {
            // Lowering owns the single primary lookup/kind diagnostic.
            continue;
        };
        let Some(TypeDef::Trait(trait_def)) = compiled.registry.get(trait_id) else {
            continue;
        };
        check_single_impl_conformance(
            impl_def,
            trait_def,
            compiled.registry.impl_trait_span(impl_id),
            compiled,
            diags,
        );
    }
}

fn check_single_impl_conformance(
    impl_def: &ImplDef,
    trait_def: &TraitDef,
    trait_span: Option<crate::span::Span>,
    compiled: &CompiledSchema,
    diags: &mut Vec<Diagnostic>,
) {
    if impl_def.type_args.len() != trait_def.type_params.len() {
        diags.push(Diagnostic::error(
            trait_span.unwrap_or(impl_def.span),
            ErrorClass::UnresolvedType,
            format!(
                "trait '{}' has {} type parameters but impl provides {}",
                impl_def.trait_name,
                trait_def.type_params.len(),
                impl_def.type_args.len()
            ),
        ));
        return;
    }

    // Check target type has all required trait fields
    check_trait_fields(impl_def, trait_def, compiled, diags);

    // Check all trait functions are implemented
    check_trait_functions(impl_def, compiled, diags);
}

fn check_trait_fields(
    impl_def: &ImplDef,
    trait_def: &TraitDef,
    compiled: &CompiledSchema,
    diags: &mut Vec<Diagnostic>,
) {
    // Get the target type definition
    let target_type_def = match &impl_def.target_type {
        ResolvedType::Named(id) => compiled.registry.get(*id),
        _ => None,
    };

    let Some(target_def) = target_type_def else {
        // Type validation happens elsewhere
        return;
    };

    let target_fields = match target_def {
        TypeDef::Message(m) => &m.fields,
        _ => {
            diags.push(Diagnostic::error(
                impl_def.span,
                ErrorClass::UnresolvedType,
                format!(
                    "impl target '{:?}' is not a message type",
                    impl_def.target_type
                ),
            ));
            return;
        }
    };

    // Build type parameter names from trait def
    let type_param_names: Vec<&str> = trait_def
        .type_params
        .iter()
        .map(|p| p.name.node.as_str())
        .collect();

    // Check each required trait field exists on target
    for trait_field in &trait_def.fields {
        // Substitute type arguments into the trait field's unresolved type
        let substituted_ty = substitute_into_type_expr(
            &trait_field.unresolved_ty,
            &type_param_names,
            &impl_def.type_args,
            compiled,
        );

        let found = target_fields.iter().any(|f| {
            f.name == trait_field.name && types_compatible(&f.resolved_type, &substituted_ty)
        });

        if !found {
            diags.push(Diagnostic::error(
                impl_def.span,
                ErrorClass::UnresolvedType,
                format!(
                    "impl for '{:?}' missing required trait field '{}' of type '{:?}'",
                    impl_def.target_type, trait_field.name, substituted_ty
                ),
            ));
        }
    }
}

fn check_trait_functions(
    impl_def: &ImplDef,
    compiled: &CompiledSchema,
    diags: &mut Vec<Diagnostic>,
) {
    use crate::codegen::portable::{project_impl, PortableFunctionError};

    let error = match project_impl(compiled, impl_def) {
        Ok(_) => return,
        Err(error) => error,
    };
    let class = match &error {
        PortableFunctionError::MissingFunction { .. } => ErrorClass::ImplFnMissing,
        PortableFunctionError::ExtraFunction { .. } => ErrorClass::ImplFnExtra,
        PortableFunctionError::DuplicateFunction { .. }
        | PortableFunctionError::SignatureMismatch { .. } => ErrorClass::ImplFnSignatureMismatch,
        PortableFunctionError::InvalidAssignmentTarget { .. } => {
            ErrorClass::ImplFnAssignmentInvalid
        }
        PortableFunctionError::ReturnMismatch { .. }
        | PortableFunctionError::StatementsAfterReturn { .. } => ErrorClass::ImplFnReturnMismatch,
        PortableFunctionError::TypeMismatch { context, .. } if context == "return" => {
            ErrorClass::ImplFnReturnMismatch
        }
        PortableFunctionError::UnsupportedCall { .. }
        | PortableFunctionError::UnsupportedMethodCall { .. } => {
            // These constructs remain valid Vexil. Reference generators reject
            // them at the portable code-generation boundary.
            return;
        }
        PortableFunctionError::UnknownTrait { .. }
        | PortableFunctionError::InvalidTarget
        | PortableFunctionError::ExternalFunction { .. }
        | PortableFunctionError::UnknownLocal { .. }
        | PortableFunctionError::UnknownField { .. }
        | PortableFunctionError::DuplicateLocal { .. }
        | PortableFunctionError::UnsupportedExpressionStatement { .. }
        | PortableFunctionError::TypeMismatch { .. }
        | PortableFunctionError::InvalidOperator { .. }
        | PortableFunctionError::UnresolvedType { .. } => ErrorClass::ImplFnBodyTypeMismatch,
    };
    diags.push(Diagnostic::error(impl_def.span, class, error.to_string()));
}

fn types_compatible(a: &ResolvedType, b: &ResolvedType) -> bool {
    if a == b {
        return true;
    }

    match (a, b) {
        (ResolvedType::Named(id_a), ResolvedType::Named(id_b)) => id_a == id_b,
        _ => false,
    }
}

/// Substitute type arguments into a type expression for trait conformance checking.
///
/// `type_params` contains the parameter names from the trait (e.g., `["T"]`).
/// `type_args` contains the concrete types from the impl (e.g., `[u64]`).
/// For each `Named(name)` in `expr`, if `name` matches a parameter, replace with the
/// corresponding type from `type_args`. Otherwise, resolve via registry lookup.
fn substitute_into_type_expr(
    expr: &TypeExpr,
    type_params: &[&str],
    type_args: &[ResolvedType],
    compiled: &CompiledSchema,
) -> ResolvedType {
    match expr {
        TypeExpr::Named(name) => {
            if let Some(idx) = type_params.iter().position(|&p| p == name.as_str()) {
                if idx < type_args.len() {
                    return type_args[idx].clone();
                }
            }
            resolve_type_name(name, compiled)
        }
        TypeExpr::Primitive(p) => ResolvedType::Primitive(*p),
        TypeExpr::SubByte(s) => ResolvedType::SubByte(*s),
        TypeExpr::Semantic(s) => ResolvedType::Semantic(*s),
        TypeExpr::Generic(name, arg) => {
            let inner = Box::new(substitute_into_type_expr(
                &arg.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Named(resolve_generic_type(name, *inner, compiled))
        }
        TypeExpr::Optional(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Optional(inner)
        }
        TypeExpr::Array(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Array(inner)
        }
        TypeExpr::FixedArray(inner, size) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::FixedArray(inner, *size)
        }
        TypeExpr::Set(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Set(inner)
        }
        TypeExpr::Map(key, value) => {
            let key = Box::new(substitute_into_type_expr(
                &key.node,
                type_params,
                type_args,
                compiled,
            ));
            let value = Box::new(substitute_into_type_expr(
                &value.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Map(key, value)
        }
        TypeExpr::Result(ok, err) => {
            let ok = Box::new(substitute_into_type_expr(
                &ok.node,
                type_params,
                type_args,
                compiled,
            ));
            let err = Box::new(substitute_into_type_expr(
                &err.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Result(ok, err)
        }
        TypeExpr::Vec2(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Vec2(inner)
        }
        TypeExpr::Vec3(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Vec3(inner)
        }
        TypeExpr::Vec4(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Vec4(inner)
        }
        TypeExpr::Quat(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Quat(inner)
        }
        TypeExpr::Mat3(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Mat3(inner)
        }
        TypeExpr::Mat4(inner) => {
            let inner = Box::new(substitute_into_type_expr(
                &inner.node,
                type_params,
                type_args,
                compiled,
            ));
            ResolvedType::Mat4(inner)
        }
        TypeExpr::BitsInline(names) => ResolvedType::BitsInline(names.clone()),
        TypeExpr::Qualified(ns, name) => {
            let qualified_name: SmolStr = format!("{ns}.{name}").into();
            resolve_type_name(&qualified_name, compiled)
        }
    }
}

/// Resolve a generic type instantiation (e.g., `Vec<u64>`) by looking up the alias
/// and substituting type arguments.
fn resolve_generic_type(
    name: &SmolStr,
    inner_type: ResolvedType,
    compiled: &CompiledSchema,
) -> TypeId {
    if let Some((_, crate::ir::TypeDef::GenericAlias(alias_def))) =
        compiled.find_type(name.as_str())
    {
        let type_params: Vec<&str> = alias_def.type_params.iter().map(|p| p.as_str()).collect();
        let type_args = vec![inner_type];
        let substituted =
            substitute_into_type_expr(&alias_def.target_type, &type_params, &type_args, compiled);
        if let ResolvedType::Named(id) = substituted {
            return id;
        }
    }
    POISON_TYPE_ID
}

/// Resolve a named type to a ResolvedType by looking it up in the registry.
fn resolve_type_name(name: &SmolStr, compiled: &CompiledSchema) -> ResolvedType {
    if let Some((id, _)) = compiled.find_type(name.as_str()) {
        ResolvedType::Named(id)
    } else {
        ResolvedType::Named(POISON_TYPE_ID)
    }
}