wirespec-backend-c 0.4.2

C backend for wirespec
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
// crates/wirespec-backend-c/src/parse_emit.rs
//
// Per-field parse code generation (cursor reads, bitgroups, conditionals, arrays).

use wirespec_codec::ir::*;

use crate::expr::{ExprContext, expr_to_c};
use crate::names::*;
use crate::type_map::*;

/// Bundles the "threading" parameters used throughout field-parse emission,
/// keeping individual function signatures under the clippy arg-count limit.
struct FieldParseCtx<'a> {
    prefix: &'a str,
    indent: &'a str,
    struct_prefix: &'a str,
    expr_ctx: &'a ExprContext,
}

/// Returns true if the wire type is a signed integer that needs a cast
/// when passed to the unsigned cursor-read / write functions.
fn needs_signed_cast(wt: &WireType) -> bool {
    matches!(
        wt,
        WireType::I8 | WireType::I16 | WireType::I32 | WireType::I64
    )
}

/// Returns the unsigned C type corresponding to a signed wire type.
fn unsigned_c_type(wt: &WireType) -> &'static str {
    match wt {
        WireType::I8 => "uint8_t",
        WireType::I16 => "uint16_t",
        WireType::I32 => "uint32_t",
        WireType::I64 => "uint64_t",
        _ => unreachable!(),
    }
}

/// Emit parse body for a list of items (fields, derived, requires).
///
/// `expr_ctx` controls how field references are resolved in expressions.
/// For top-level structs, pass `None` (uses `ExprContext::Parse`).
/// For variant fields, pass a `CapsuleVariantParse` context.
pub fn emit_parse_items(
    out: &mut String,
    fields: &[CodecField],
    items: &[CodecItem],
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
) {
    emit_parse_items_with_ctx(
        out,
        fields,
        items,
        prefix,
        indent,
        struct_prefix,
        &ExprContext::Parse,
    );
}

/// Like `emit_parse_items` but with an explicit `ExprContext` for expression evaluation.
pub fn emit_parse_items_with_ctx(
    out: &mut String,
    fields: &[CodecField],
    items: &[CodecItem],
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
    expr_ctx: &ExprContext,
) {
    // Track which bitgroups we've already emitted
    let mut emitted_bitgroups: Vec<u32> = Vec::new();
    let ctx = FieldParseCtx {
        prefix,
        indent,
        struct_prefix,
        expr_ctx,
    };

    for item in items {
        match item {
            CodecItem::Field { field_id } => {
                if let Some(f) = fields.iter().find(|f| &f.field_id == field_id) {
                    emit_field_parse_with_ctx(out, f, fields, &ctx, &mut emitted_bitgroups);
                }
            }
            CodecItem::Derived(d) => {
                let expr_str = expr_to_c(&d.expr, expr_ctx);
                out.push_str(&format!(
                    "{indent}{struct_prefix}{} = {expr_str};\n",
                    d.name
                ));
            }
            CodecItem::Require(r) => {
                let expr_str = expr_to_c(&r.expr, expr_ctx);
                out.push_str(&format!(
                    "{indent}if (!({expr_str})) return WIRESPEC_ERR_CONSTRAINT;\n"
                ));
            }
        }
    }
}

fn emit_field_parse(
    out: &mut String,
    f: &CodecField,
    all_fields: &[CodecField],
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
    emitted_bitgroups: &mut Vec<u32>,
) {
    let ctx = FieldParseCtx {
        prefix,
        indent,
        struct_prefix,
        expr_ctx: &ExprContext::Parse,
    };
    emit_field_parse_with_ctx(out, f, all_fields, &ctx, emitted_bitgroups);
}

fn emit_field_parse_with_ctx(
    out: &mut String,
    f: &CodecField,
    all_fields: &[CodecField],
    ctx: &FieldParseCtx<'_>,
    emitted_bitgroups: &mut Vec<u32>,
) {
    let prefix = ctx.prefix;
    let indent = ctx.indent;
    let struct_prefix = ctx.struct_prefix;
    let expr_ctx = ctx.expr_ctx;
    match f.strategy {
        FieldStrategy::Primitive | FieldStrategy::Checksum => {
            let read_fn = cursor_read_fn(&f.wire_type, f.endianness);
            if needs_signed_cast(&f.wire_type) {
                let utype = unsigned_c_type(&f.wire_type);
                out.push_str(&format!(
                    "{indent}r = {read_fn}(cur, ({utype} *)&{struct_prefix}{});\n",
                    f.name
                ));
            } else {
                out.push_str(&format!(
                    "{indent}r = {read_fn}(cur, &{struct_prefix}{});\n",
                    f.name
                ));
            }
            out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
        }
        FieldStrategy::BitGroup => {
            if let Some(ref bg) = f.bitgroup_member
                && !emitted_bitgroups.contains(&bg.group_id)
            {
                emitted_bitgroups.push(bg.group_id);
                emit_bitgroup_parse(out, f, all_fields, prefix, indent, struct_prefix, bg);
            }
            // If already emitted, this field was handled as part of the group
        }
        FieldStrategy::BytesFixed => {
            if let Some(BytesSpec::Fixed { size }) = &f.bytes_spec {
                out.push_str(&format!(
                    "{indent}r = wirespec_cursor_read_bytes(cur, {size}, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::BytesLength => {
            if let Some(BytesSpec::Length { ref expr }) = f.bytes_spec {
                let len_expr = expr_to_c(expr, expr_ctx);
                out.push_str(&format!(
                    "{indent}r = wirespec_cursor_read_bytes(cur, (size_t){len_expr}, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::BytesRemaining => {
            out.push_str(&format!(
                "{indent}{struct_prefix}{}.ptr = cur->base + cur->pos;\n",
                f.name
            ));
            out.push_str(&format!(
                "{indent}{struct_prefix}{}.len = wirespec_cursor_remaining(cur);\n",
                f.name
            ));
            out.push_str(&format!("{indent}cur->pos = cur->len;\n"));
        }
        FieldStrategy::BytesLor => {
            if let Some(BytesSpec::LengthOrRemaining { ref expr }) = f.bytes_spec {
                // Check if the length field is available (has_X)
                let len_expr = expr_to_c(expr, expr_ctx);
                // We need to figure out which field is the length source
                // For LOR, the condition is typically based on whether a field has a value
                // The expr gives us the length expression
                let value_id = get_value_ref_id(expr);
                let field_name = crate::expr::extract_field_name(&value_id);
                out.push_str(&format!(
                    "{indent}if ({struct_prefix}has_{field_name}) {{\n"
                ));
                out.push_str(&format!(
                    "{indent}    r = wirespec_cursor_read_bytes(cur, (size_t){len_expr}, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
                out.push_str(&format!("{indent}}} else {{\n"));
                out.push_str(&format!(
                    "{indent}    {struct_prefix}{}.ptr = cur->base + cur->pos;\n",
                    f.name
                ));
                out.push_str(&format!(
                    "{indent}    {struct_prefix}{}.len = wirespec_cursor_remaining(cur);\n",
                    f.name
                ));
                out.push_str(&format!("{indent}    cur->pos = cur->len;\n"));
                out.push_str(&format!("{indent}}}\n"));
            }
        }
        FieldStrategy::Conditional => {
            if let Some(ref cond) = f.condition {
                let cond_str = expr_to_c(cond, expr_ctx);
                out.push_str(&format!("{indent}{struct_prefix}has_{} = false;\n", f.name));
                out.push_str(&format!("{indent}if ({cond_str}) {{\n"));

                // Parse the inner field
                let inner_wt = f.inner_wire_type.as_ref().unwrap_or(&f.wire_type);
                // Check if the inner type is a struct reference
                if let Some(ref ref_name) = f.ref_type_name
                    && matches!(
                        inner_wt,
                        WireType::Struct(_) | WireType::VarInt | WireType::ContVarInt
                    )
                {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}    r = {parse_fn}(cur, &{struct_prefix}{});\n",
                        f.name
                    ));
                } else {
                    let read_fn = cursor_read_fn(inner_wt, f.endianness);
                    out.push_str(&format!(
                        "{indent}    r = {read_fn}(cur, &{struct_prefix}{});\n",
                        f.name
                    ));
                }
                out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
                out.push_str(&format!(
                    "{indent}    {struct_prefix}has_{} = true;\n",
                    f.name
                ));
                out.push_str(&format!("{indent}}}\n"));
            }
        }
        FieldStrategy::Array => {
            if let Some(ref arr) = f.array_spec {
                emit_array_parse_with_ctx(out, f, arr, prefix, indent, struct_prefix, expr_ctx);
            }
        }
        FieldStrategy::Struct => {
            if let Some(ref ref_name) = f.ref_type_name {
                let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                out.push_str(&format!(
                    "{indent}r = {parse_fn}(cur, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::VarInt | FieldStrategy::ContVarInt => {
            if let Some(ref ref_name) = f.ref_type_name {
                let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                out.push_str(&format!(
                    "{indent}r = {parse_fn}(cur, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
    }
}

fn emit_bitgroup_parse(
    out: &mut String,
    _first_field: &CodecField,
    all_fields: &[CodecField],
    _prefix: &str,
    indent: &str,
    struct_prefix: &str,
    bg: &BitgroupMember,
) {
    let group_id = bg.group_id;
    let total_bits = bg.total_bits;
    let container_type = bitgroup_c_type(total_bits);
    let read_fn = bitgroup_read_fn(total_bits, bg.group_endianness);
    let var_name = format!("_bg{group_id}");

    out.push_str(&format!("{indent}{{\n"));
    out.push_str(&format!("{indent}    {container_type} {var_name};\n"));
    out.push_str(&format!("{indent}    r = {read_fn}(cur, &{var_name});\n"));
    out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));

    // Extract all fields in this group
    for f in all_fields {
        if let Some(ref mbg) = f.bitgroup_member
            && mbg.group_id == group_id
        {
            let mask = if mbg.member_width_bits >= 64 {
                u64::MAX
            } else {
                (1u64 << mbg.member_width_bits) - 1
            };
            let shift = mbg.member_offset_bits;
            let ctype = wire_type_to_c(&f.wire_type, "");
            // Use the simplest unsigned type for the cast
            let cast_type = if ctype.contains("int") {
                &ctype
            } else {
                "uint8_t"
            };
            out.push_str(&format!(
                    "{indent}    {struct_prefix}{} = ({cast_type})(({var_name} >> {shift}) & 0x{mask:x});\n",
                    f.name
                ));
        }
    }

    out.push_str(&format!("{indent}}}\n"));
}

fn emit_array_parse_with_ctx(
    out: &mut String,
    f: &CodecField,
    arr: &ArraySpec,
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
    expr_ctx: &ExprContext,
) {
    if let Some(ref count_expr) = arr.count_expr {
        let count_str = expr_to_c(count_expr, expr_ctx);
        let max_elems = f.max_elements.unwrap_or(256);

        out.push_str(&format!(
            "{indent}{struct_prefix}{}_count = (uint32_t){count_str};\n",
            f.name
        ));
        out.push_str(&format!(
            "{indent}if ({struct_prefix}{}_count > {max_elems}) return WIRESPEC_ERR_CAPACITY;\n",
            f.name
        ));
        out.push_str(&format!(
            "{indent}for (uint32_t _i = 0; _i < {struct_prefix}{}_count; _i++) {{\n",
            f.name
        ));

        // Parse each element
        match arr.element_strategy {
            FieldStrategy::Primitive => {
                let read_fn = cursor_read_fn(&arr.element_wire_type, None);
                out.push_str(&format!(
                    "{indent}    r = {read_fn}(cur, &{struct_prefix}{}[_i]);\n",
                    f.name
                ));
                out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
            }
            FieldStrategy::Struct => {
                if let Some(ref ref_name) = arr.element_ref_type_name {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}    r = {parse_fn}(cur, &{struct_prefix}{}[_i]);\n",
                        f.name
                    ));
                    out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
                }
            }
            FieldStrategy::VarInt | FieldStrategy::ContVarInt => {
                if let Some(ref ref_name) = arr.element_ref_type_name {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}    r = {parse_fn}(cur, &{struct_prefix}{}[_i]);\n",
                        f.name
                    ));
                    out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
                }
            }
            _ => unreachable!(
                "unexpected array element strategy: {:?}",
                arr.element_strategy
            ),
        }

        out.push_str(&format!("{indent}}}\n"));
    } else {
        // [T; fill] — parse until cursor exhausted
        let max_elems = f.max_elements.unwrap_or(256);

        // Determine the cursor variable to use
        let cur_var = if let Some(ref within_expr) = arr.within_expr {
            // [T; fill] within expr — create a sub-cursor bounded by the expression
            let within_c = expr_to_c(within_expr, expr_ctx);
            out.push_str(&format!("{indent}{{\n"));
            out.push_str(&format!("{indent}    wirespec_cursor_t _arr_sub;\n"));
            out.push_str(&format!(
                "{indent}    r = wirespec_cursor_sub(cur, (size_t){within_c}, &_arr_sub);\n"
            ));
            out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
            "&_arr_sub".to_string()
        } else {
            "cur".to_string()
        };

        out.push_str(&format!(
            "{indent}    {struct_prefix}{}_count = 0;\n",
            f.name
        ));
        out.push_str(&format!(
            "{indent}    while (wirespec_cursor_remaining({cur_var}) > 0) {{\n",
        ));
        out.push_str(&format!(
            "{indent}        if ({struct_prefix}{}_count >= {max_elems}) return WIRESPEC_ERR_CAPACITY;\n",
            f.name
        ));

        match arr.element_strategy {
            FieldStrategy::Primitive => {
                let read_fn = cursor_read_fn(&arr.element_wire_type, None);
                out.push_str(&format!(
                    "{indent}        r = {read_fn}({cur_var}, &{struct_prefix}{}[{struct_prefix}{}_count]);\n",
                    f.name, f.name
                ));
                out.push_str(&format!(
                    "{indent}        if (r != WIRESPEC_OK) return r;\n"
                ));
            }
            FieldStrategy::Struct => {
                if let Some(ref ref_name) = arr.element_ref_type_name {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}        r = {parse_fn}({cur_var}, &{struct_prefix}{}[{struct_prefix}{}_count]);\n",
                        f.name, f.name
                    ));
                    out.push_str(&format!(
                        "{indent}        if (r != WIRESPEC_OK) return r;\n"
                    ));
                }
            }
            FieldStrategy::VarInt | FieldStrategy::ContVarInt => {
                if let Some(ref ref_name) = arr.element_ref_type_name {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}        r = {parse_fn}({cur_var}, &{struct_prefix}{}[{struct_prefix}{}_count]);\n",
                        f.name, f.name
                    ));
                    out.push_str(&format!(
                        "{indent}        if (r != WIRESPEC_OK) return r;\n"
                    ));
                }
            }
            _ => unreachable!(
                "unexpected fill array element strategy: {:?}",
                arr.element_strategy
            ),
        }

        out.push_str(&format!(
            "{indent}        {struct_prefix}{}_count++;\n",
            f.name
        ));
        out.push_str(&format!("{indent}    }}\n"));

        if arr.within_expr.is_some() {
            out.push_str(&format!("{indent}}}\n"));
        }
    }
}

/// Extract value_id from a CodecExpr if it's a ValueRef, or return empty string.
fn get_value_ref_id(expr: &CodecExpr) -> String {
    match expr {
        CodecExpr::ValueRef { reference } => reference.value_id.clone(),
        _ => String::new(),
    }
}

/// Emit parse for frame variants (the switch dispatch).
pub fn emit_frame_parse_body(out: &mut String, frame: &CodecFrame, prefix: &str, indent: &str) {
    let struct_prefix = "out->";

    // Read the tag field
    match &frame.tag.wire_type {
        WireType::VarInt | WireType::ContVarInt => {
            if let Some(ref ref_name) = frame.tag.ref_type_name {
                let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                out.push_str(&format!("{indent}uint64_t _tag_val;\n"));
                out.push_str(&format!("{indent}r = {parse_fn}(cur, &_tag_val);\n"));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            } else {
                // Fallback: read as u8 if no ref_type_name (should not happen in practice)
                out.push_str(&format!("{indent}uint64_t _tag_val;\n"));
                out.push_str(&format!(
                    "{indent}r = wirespec_cursor_read_u8(cur, (uint8_t *)&_tag_val);\n"
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        _ => {
            // Primitive tag
            let tag_read_fn = cursor_read_fn(&frame.tag.wire_type, frame.tag.endianness);
            let tag_ctype = wire_type_to_c(&frame.tag.wire_type, prefix);
            out.push_str(&format!("{indent}{tag_ctype} _tag_val;\n"));
            out.push_str(&format!("{indent}r = {tag_read_fn}(cur, &_tag_val);\n"));
            out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
        }
    }

    // Store raw tag value
    out.push_str(&format!("{indent}{struct_prefix}frame_type = _tag_val;\n"));

    // Switch on tag value.
    // Large-range variants (>4096 values) cannot be expanded as individual
    // case labels.  Collect them separately so they can be handled inside the
    // single `default:` block via if-guards, avoiding duplicate `default:`
    // labels which are illegal in C.
    let mut large_range_deferred: Vec<(i64, i64, String)> = Vec::new();
    let mut wildcard_variant: Option<&CodecVariantScope> = None;
    for variant in &frame.variants {
        if matches!(variant.pattern, VariantPattern::Wildcard) {
            wildcard_variant = Some(variant);
        }
    }

    out.push_str(&format!("{indent}switch (_tag_val) {{\n"));
    for variant in &frame.variants {
        if matches!(variant.pattern, VariantPattern::Wildcard) {
            // Wildcard is emitted as part of the default: block below.
            continue;
        }
        if let Some(deferred) =
            emit_variant_case(out, variant, frame, prefix, indent, struct_prefix)
        {
            large_range_deferred.push(deferred);
        }
    }

    // Emit a single default: block that handles large-range variants (via
    // if-guards) followed by the wildcard body or an invalid-tag error.
    out.push_str(&format!("{indent}    default:\n"));
    let def_indent = format!("{indent}        ");
    for (lo, hi, body) in large_range_deferred {
        out.push_str(&format!(
            "{def_indent}if (_tag_val >= {lo} && _tag_val <= {hi}) {{\n"
        ));
        // body already ends with `break;\n`
        out.push_str(&body);
        out.push_str(&format!("{def_indent}}}\n"));
    }
    if let Some(wv) = wildcard_variant {
        emit_variant_case_body(out, wv, frame, prefix, &def_indent, struct_prefix);
    } else {
        out.push_str(&format!("{def_indent}return WIRESPEC_ERR_INVALID_TAG;\n"));
    }
    out.push_str(&format!("{indent}}}\n"));
}

/// Emit the body of a variant case (tag assignment + field parsing + break),
/// writing into `out` at `inner_indent`.  Does not emit a `case` or `default:`
/// label — the caller is responsible for the label.
fn emit_variant_case_body(
    out: &mut String,
    variant: &CodecVariantScope,
    frame: &CodecFrame,
    prefix: &str,
    inner_indent: &str,
    struct_prefix: &str,
) {
    let tag_val = c_frame_tag_value(prefix, &frame.name, &variant.name);
    let vname = to_snake_case(&variant.name);
    let variant_prefix = format!("{struct_prefix}value.{vname}.");
    let header_field_names = vec![frame.tag.field_name.clone()];
    let expr_ctx = ExprContext::CapsuleVariantParse {
        variant_prefix: variant_prefix.clone(),
        header_field_names,
    };

    out.push_str(&format!("{inner_indent}{struct_prefix}tag = {tag_val};\n"));
    emit_parse_items_with_ctx(
        out,
        &variant.fields,
        &variant.items,
        prefix,
        inner_indent,
        &variant_prefix,
        &expr_ctx,
    );
    out.push_str(&format!("{inner_indent}break;\n"));
}

/// Emit a switch case for a frame variant.  Wildcard variants are handled by
/// the caller (skipped here).  Returns `Some((lo, hi, body))` for large-range
/// variants that cannot be expanded as individual case labels; the caller must
/// embed the body inside the `default:` block via an if-guard.  Returns `None`
/// for exact-value and small-range variants (emitted directly into `out`).
fn emit_variant_case(
    out: &mut String,
    variant: &CodecVariantScope,
    frame: &CodecFrame,
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
) -> Option<(i64, i64, String)> {
    let inner_indent = format!("{indent}        ");

    match &variant.pattern {
        VariantPattern::Exact { value } => {
            out.push_str(&format!("{indent}    case {value}:\n"));
            emit_variant_case_body(out, variant, frame, prefix, &inner_indent, struct_prefix);
            None
        }
        VariantPattern::RangeInclusive { start, end } => {
            let count = end.saturating_sub(*start).saturating_add(1);
            if count > 4096 {
                // Too many values to expand as case labels.  Return the body
                // so the caller can embed it in the default: block with an
                // if-guard, avoiding a duplicate `default:` label.
                let mut body = String::new();
                emit_variant_case_body(
                    &mut body,
                    variant,
                    frame,
                    prefix,
                    &inner_indent,
                    struct_prefix,
                );
                Some((*start, *end, body))
            } else {
                for v in *start..=*end {
                    out.push_str(&format!("{indent}    case {v}:\n"));
                }
                emit_variant_case_body(out, variant, frame, prefix, &inner_indent, struct_prefix);
                None
            }
        }
        VariantPattern::Wildcard => {
            // Wildcard is handled entirely by the caller; nothing emitted here.
            None
        }
    }
}

/// Emit parse for capsule (header fields + sub-cursor dispatch).
pub fn emit_capsule_parse_body(
    out: &mut String,
    capsule: &CodecCapsule,
    prefix: &str,
    indent: &str,
) {
    let struct_prefix = "out->";

    // Parse header fields
    let mut emitted_bitgroups: Vec<u32> = Vec::new();
    for item in &capsule.header_items {
        match item {
            CodecItem::Field { field_id } => {
                if let Some(f) = capsule
                    .header_fields
                    .iter()
                    .find(|f| &f.field_id == field_id)
                {
                    emit_field_parse(
                        out,
                        f,
                        &capsule.header_fields,
                        prefix,
                        indent,
                        struct_prefix,
                        &mut emitted_bitgroups,
                    );
                }
            }
            CodecItem::Derived(d) => {
                let expr_str = expr_to_c(&d.expr, &ExprContext::Parse);
                out.push_str(&format!(
                    "{indent}{struct_prefix}{} = {expr_str};\n",
                    d.name
                ));
            }
            CodecItem::Require(r) => {
                let expr_str = expr_to_c(&r.expr, &ExprContext::Parse);
                out.push_str(&format!(
                    "{indent}if (!({expr_str})) return WIRESPEC_ERR_CONSTRAINT;\n"
                ));
            }
        }
    }

    // Create sub-cursor for "within" field (always uses the within_field, NOT the tag expr)
    let within_expr = format!("(size_t)({struct_prefix}{})", capsule.within_field);

    out.push_str(&format!("{indent}wirespec_cursor_t sub;\n"));
    out.push_str(&format!(
        "{indent}r = wirespec_cursor_sub(cur, {within_expr}, &sub);\n"
    ));
    out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));

    // Determine the tag expression for switching
    // For expr-based tags: use the expression (e.g., "(out->type_and_flags >> 4)")
    // For field-based tags: use the field directly
    let tag_switch_expr = if let Some(ref expr) = capsule.tag_expr {
        expr_to_c(expr, &ExprContext::Parse)
    } else {
        format!("{struct_prefix}{}", capsule.tag.field_name)
    };

    // Switch on tag.
    // Large-range variants and the wildcard are handled in a single default:
    // block to avoid duplicate `default:` labels, which are illegal in C.
    let mut large_range_deferred: Vec<(i64, i64, String)> = Vec::new();
    let mut wildcard_variant: Option<&CodecVariantScope> = None;
    for variant in &capsule.variants {
        if matches!(variant.pattern, VariantPattern::Wildcard) {
            wildcard_variant = Some(variant);
        }
    }

    out.push_str(&format!("{indent}switch ({tag_switch_expr}) {{\n"));
    for variant in &capsule.variants {
        if matches!(variant.pattern, VariantPattern::Wildcard) {
            continue;
        }
        if let Some(deferred) =
            emit_capsule_variant_case(out, variant, capsule, prefix, indent, struct_prefix)
        {
            large_range_deferred.push(deferred);
        }
    }

    // Emit a single default: block covering large-range variants (via
    // if-guards) and optionally a wildcard variant.
    out.push_str(&format!("{indent}    default:\n"));
    let def_indent = format!("{indent}        ");
    for (lo, hi, body) in large_range_deferred {
        out.push_str(&format!(
            "{def_indent}if ({tag_switch_expr} >= {lo} && {tag_switch_expr} <= {hi}) {{\n"
        ));
        // body already ends with `break;\n`
        out.push_str(&body);
        out.push_str(&format!("{def_indent}}}\n"));
    }
    if let Some(wv) = wildcard_variant {
        emit_capsule_variant_case_body(out, wv, capsule, prefix, &def_indent, struct_prefix);
    } else {
        out.push_str(&format!("{def_indent}return WIRESPEC_ERR_INVALID_TAG;\n"));
    }
    out.push_str(&format!("{indent}}}\n"));

    // Check trailing data in sub-cursor
    out.push_str(&format!(
        "{indent}if (wirespec_cursor_remaining(&sub) != 0) return WIRESPEC_ERR_TRAILING_DATA;\n"
    ));
}

/// Emit the body of a capsule variant case (tag assignment + item parsing +
/// break), writing into `out` at `inner_indent`.  Does not emit any label.
fn emit_capsule_variant_case_body(
    out: &mut String,
    variant: &CodecVariantScope,
    capsule: &CodecCapsule,
    prefix: &str,
    inner_indent: &str,
    struct_prefix: &str,
) {
    let tag_val = c_frame_tag_value(prefix, &capsule.name, &variant.name);
    let vname = to_snake_case(&variant.name);
    let variant_prefix = format!("{struct_prefix}value.{vname}.");
    let header_field_names: Vec<String> = capsule
        .header_fields
        .iter()
        .map(|f| f.name.clone())
        .collect();
    let expr_ctx = ExprContext::CapsuleVariantParse {
        variant_prefix: variant_prefix.clone(),
        header_field_names,
    };

    out.push_str(&format!("{inner_indent}{struct_prefix}tag = {tag_val};\n"));

    for item in &variant.items {
        match item {
            CodecItem::Field { field_id } => {
                if let Some(f) = variant.fields.iter().find(|f| &f.field_id == field_id) {
                    emit_capsule_field_parse(
                        out,
                        f,
                        &variant.fields,
                        prefix,
                        inner_indent,
                        &variant_prefix,
                        &expr_ctx,
                    );
                }
            }
            CodecItem::Derived(d) => {
                let expr_str = expr_to_c(&d.expr, &expr_ctx);
                out.push_str(&format!(
                    "{inner_indent}{variant_prefix}{} = {expr_str};\n",
                    d.name
                ));
            }
            CodecItem::Require(r) => {
                let expr_str = expr_to_c(&r.expr, &expr_ctx);
                out.push_str(&format!(
                    "{inner_indent}if (!({expr_str})) return WIRESPEC_ERR_CONSTRAINT;\n"
                ));
            }
        }
    }

    out.push_str(&format!("{inner_indent}break;\n"));
}

/// Emit a switch case for a capsule variant.  Wildcard variants are skipped
/// (handled by the caller in the default: block).  Returns `Some((lo, hi,
/// body))` for large-range variants; the caller must embed the body in the
/// default: block via an if-guard to avoid a duplicate `default:` label.
fn emit_capsule_variant_case(
    out: &mut String,
    variant: &CodecVariantScope,
    capsule: &CodecCapsule,
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
) -> Option<(i64, i64, String)> {
    let inner_indent = format!("{indent}        ");

    match &variant.pattern {
        VariantPattern::Exact { value } => {
            out.push_str(&format!("{indent}    case {value}:\n"));
            emit_capsule_variant_case_body(
                out,
                variant,
                capsule,
                prefix,
                &inner_indent,
                struct_prefix,
            );
            None
        }
        VariantPattern::RangeInclusive { start, end } => {
            let count = end.saturating_sub(*start).saturating_add(1);
            if count > 4096 {
                // Too many values to expand as case labels.  Return the body
                // so the caller can embed it in the default: block.
                let mut body = String::new();
                emit_capsule_variant_case_body(
                    &mut body,
                    variant,
                    capsule,
                    prefix,
                    &inner_indent,
                    struct_prefix,
                );
                Some((*start, *end, body))
            } else {
                for v in *start..=*end {
                    out.push_str(&format!("{indent}    case {v}:\n"));
                }
                emit_capsule_variant_case_body(
                    out,
                    variant,
                    capsule,
                    prefix,
                    &inner_indent,
                    struct_prefix,
                );
                None
            }
        }
        VariantPattern::Wildcard => {
            // Wildcard is handled by the caller; nothing emitted here.
            None
        }
    }
}

/// Like emit_field_parse but uses `&sub` cursor for capsule payload variants.
fn emit_capsule_field_parse(
    out: &mut String,
    f: &CodecField,
    all_fields: &[CodecField],
    prefix: &str,
    indent: &str,
    struct_prefix: &str,
    expr_ctx: &ExprContext,
) {
    match f.strategy {
        FieldStrategy::Primitive | FieldStrategy::Checksum => {
            let read_fn = cursor_read_fn(&f.wire_type, f.endianness);
            if needs_signed_cast(&f.wire_type) {
                let utype = unsigned_c_type(&f.wire_type);
                out.push_str(&format!(
                    "{indent}r = {read_fn}(&sub, ({utype} *)&{struct_prefix}{});\n",
                    f.name
                ));
            } else {
                out.push_str(&format!(
                    "{indent}r = {read_fn}(&sub, &{struct_prefix}{});\n",
                    f.name
                ));
            }
            out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
        }
        FieldStrategy::Struct => {
            if let Some(ref ref_name) = f.ref_type_name {
                let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                out.push_str(&format!(
                    "{indent}r = {parse_fn}(&sub, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::VarInt | FieldStrategy::ContVarInt => {
            if let Some(ref ref_name) = f.ref_type_name {
                let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                out.push_str(&format!(
                    "{indent}r = {parse_fn}(&sub, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::Conditional => {
            if let Some(ref cond) = f.condition {
                let cond_str = expr_to_c(cond, expr_ctx);
                out.push_str(&format!("{indent}{struct_prefix}has_{} = false;\n", f.name));
                out.push_str(&format!("{indent}if ({cond_str}) {{\n"));

                // Determine the inner wire type
                let inner_wt = f.inner_wire_type.as_ref().unwrap_or(&f.wire_type);

                // Check if the inner type is a struct reference
                if let Some(ref ref_name) = f.ref_type_name
                    && matches!(inner_wt, WireType::Struct(_))
                {
                    let parse_fn = c_func_name(prefix, ref_name, "parse_cursor");
                    out.push_str(&format!(
                        "{indent}    r = {parse_fn}(&sub, &{struct_prefix}{});\n",
                        f.name
                    ));
                } else {
                    let read_fn = cursor_read_fn(inner_wt, f.endianness);
                    out.push_str(&format!(
                        "{indent}    r = {read_fn}(&sub, &{struct_prefix}{});\n",
                        f.name
                    ));
                }
                out.push_str(&format!("{indent}    if (r != WIRESPEC_OK) return r;\n"));
                out.push_str(&format!(
                    "{indent}    {struct_prefix}has_{} = true;\n",
                    f.name
                ));
                out.push_str(&format!("{indent}}}\n"));
            }
        }
        FieldStrategy::BytesRemaining => {
            out.push_str(&format!(
                "{indent}{struct_prefix}{}.ptr = sub.base + sub.pos;\n",
                f.name
            ));
            out.push_str(&format!(
                "{indent}{struct_prefix}{}.len = wirespec_cursor_remaining(&sub);\n",
                f.name
            ));
            out.push_str(&format!("{indent}sub.pos = sub.len;\n"));
        }
        FieldStrategy::BytesFixed => {
            if let Some(BytesSpec::Fixed { size }) = &f.bytes_spec {
                out.push_str(&format!(
                    "{indent}r = wirespec_cursor_read_bytes(&sub, {size}, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        FieldStrategy::BytesLength => {
            if let Some(BytesSpec::Length { ref expr }) = f.bytes_spec {
                let len_expr = expr_to_c(expr, expr_ctx);
                out.push_str(&format!(
                    "{indent}r = wirespec_cursor_read_bytes(&sub, (size_t){len_expr}, &{struct_prefix}{});\n",
                    f.name
                ));
                out.push_str(&format!("{indent}if (r != WIRESPEC_OK) return r;\n"));
            }
        }
        _ => {
            // For other strategies in capsule context, emit using the regular function
            // with the correct expression context, then replace `cur` references with
            // `&sub` to use the sub-cursor.
            let mut tmp = String::new();
            let mut dummy_bg = Vec::new();
            let ctx = FieldParseCtx {
                prefix,
                indent,
                struct_prefix,
                expr_ctx,
            };
            emit_field_parse_with_ctx(&mut tmp, f, all_fields, &ctx, &mut dummy_bg);
            // Replace cursor variable: (cur, -> (&sub, and cur-> -> sub.
            let tmp = tmp.replace("(cur, ", "(&sub, ");
            let tmp = tmp.replace("cur->", "sub.");
            out.push_str(&tmp);
        }
    }
}