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
use std::sync::Arc;

use wirespec_backend_api::*;
use wirespec_backend_c::*;

fn generate_c(src: &str) -> (String, String) {
    let ast = wirespec_syntax::parse(src).unwrap();
    let sem = wirespec_sema::analyze(
        &ast,
        wirespec_sema::ComplianceProfile::default(),
        &Default::default(),
    )
    .unwrap();
    let layout = wirespec_layout::lower(&sem).unwrap();
    let codec = wirespec_codec::lower(&layout).unwrap();

    let backend = CBackend;
    let ctx = BackendContext {
        module_name: "test".into(),
        module_prefix: "test".into(),
        source_prefixes: Default::default(),
        compliance_profile: "phase2_extended_current".into(),
        common_options: CommonOptions::default(),
        target_options: Box::new(CBackendOptions::default()),
        checksum_bindings: Arc::new(checksum_binding::CChecksumBindings),
        is_entry_module: true,
    };

    let lowered = backend.lower(&codec, &ctx).unwrap();
    (
        lowered.header_content.clone(),
        lowered.source_content.clone(),
    )
}

#[test]
fn codegen_simple_packet_header() {
    let (header, _) = generate_c(
        "packet UdpDatagram { src_port: u16, dst_port: u16, length: u16, checksum: u16 }",
    );
    assert!(header.contains("typedef struct"), "missing typedef struct");
    assert!(header.contains("test_udp_datagram_t"), "missing type name");
    assert!(
        header.contains("uint16_t src_port"),
        "missing src_port field"
    );
    assert!(
        header.contains("wirespec_result_t test_udp_datagram_parse"),
        "missing parse decl"
    );
    assert!(
        header.contains("wirespec_result_t test_udp_datagram_serialize"),
        "missing serialize decl"
    );
}

#[test]
fn codegen_simple_packet_source() {
    let (_, source) = generate_c("packet P { x: u8, y: u16 }");
    assert!(
        source.contains("wirespec_cursor_read_u8"),
        "missing u8 cursor read"
    );
    assert!(
        source.contains("wirespec_cursor_read_u16be"),
        "missing u16be cursor read"
    );
    assert!(source.contains("wirespec_write_u8"), "missing u8 write");
    assert!(
        source.contains("wirespec_write_u16be"),
        "missing u16be write"
    );
}

#[test]
fn codegen_packet_with_require() {
    let (_, source) = generate_c("packet P { length: u16, require length >= 8 }");
    assert!(
        source.contains("WIRESPEC_ERR_CONSTRAINT"),
        "missing constraint error"
    );
}

#[test]
fn codegen_packet_with_optional() {
    let (header, source) = generate_c("packet P { flags: u8, extra: if flags & 0x01 { u16 } }");
    assert!(
        header.contains("bool has_extra"),
        "missing has_extra flag in header"
    );
    assert!(source.contains("has_extra"), "missing has_extra in source");
}

#[test]
fn codegen_bytes_field() {
    let (header, _) = generate_c("packet P { data: bytes[remaining] }");
    assert!(
        header.contains("wirespec_bytes_t data"),
        "missing bytes field"
    );
}

#[test]
fn codegen_array_field() {
    let (header, source) = generate_c("packet P { count: u8, items: [u8; count] }");
    assert!(header.contains("uint8_t items["), "missing array field");
    assert!(
        header.contains("uint32_t items_count"),
        "missing array count field"
    );
    assert!(source.contains("for"), "missing for loop");
}

#[test]
fn codegen_bitgroup() {
    let (_, source) = generate_c("packet P { a: bits[4], b: bits[4], c: u16 }");
    assert!(source.contains(">>"), "missing shift for bit extract");
    assert!(source.contains("& 0xf"), "missing mask for 4-bit field");
}

#[test]
fn codegen_frame() {
    let src = r#"
        frame F = match tag: u8 {
            0x00 => A {},
            0x01 => B { x: u8 },
            _ => Unknown { data: bytes[remaining] },
        }
    "#;
    let (header, source) = generate_c(src);
    assert!(header.contains("tag_t"), "missing tag enum type in header");
    assert!(header.contains("union"), "missing union in header");
    assert!(source.contains("switch"), "missing switch in source");
}

#[test]
fn codegen_capsule() {
    let src = r#"
        capsule C {
            type_field: u8,
            length: u16,
            payload: match type_field within length {
                0 => D { data: bytes[remaining] },
                _ => U { data: bytes[remaining] },
            },
        }
    "#;
    let (_, source) = generate_c(src);
    assert!(
        source.contains("wirespec_cursor_sub"),
        "missing sub-cursor for within"
    );
}

#[test]
fn codegen_derived_field() {
    let (header, _) = generate_c("packet P { flags: u8, let is_set: bool = (flags & 1) != 0 }");
    assert!(
        header.contains("bool is_set"),
        "missing derived field in header"
    );
}

#[test]
fn codegen_enum() {
    let (header, _) = generate_c("enum E: u8 { A = 0, B = 1 }");
    // Now uses typedef + #define pattern instead of C enum
    assert!(
        header.contains("typedef uint8_t"),
        "missing enum underlying typedef in header"
    );
    assert!(
        header.contains("#define"),
        "missing enum member #define in header"
    );
}

#[test]
fn codegen_artifact_emission() {
    let ast = wirespec_syntax::parse("packet P { x: u8 }").unwrap();
    let sem = wirespec_sema::analyze(
        &ast,
        wirespec_sema::ComplianceProfile::default(),
        &Default::default(),
    )
    .unwrap();
    let layout = wirespec_layout::lower(&sem).unwrap();
    let codec = wirespec_codec::lower(&layout).unwrap();

    let backend = CBackend;
    let ctx = BackendContext {
        module_name: "test".into(),
        module_prefix: "test".into(),
        source_prefixes: Default::default(),
        compliance_profile: "phase2_extended_current".into(),
        common_options: CommonOptions::default(),
        target_options: Box::new(CBackendOptions::default()),
        checksum_bindings: Arc::new(checksum_binding::CChecksumBindings),
        is_entry_module: true,
    };

    let mut sink = MemorySink::new();
    let output = backend.lower_and_emit(&codec, &ctx, &mut sink).unwrap();
    assert_eq!(output.artifacts.len(), 2, "should emit .h + .c");
    assert_eq!(sink.artifacts.len(), 2, "sink should have 2 artifacts");
    assert!(
        output.artifacts[0]
            .relative_path
            .to_string_lossy()
            .ends_with(".h"),
        "first artifact should be .h"
    );
    assert!(
        output.artifacts[1]
            .relative_path
            .to_string_lossy()
            .ends_with(".c"),
        "second artifact should be .c"
    );
}

#[test]
fn codegen_void_r_suppression() {
    let (_, source) = generate_c("packet P { x: u8 }");
    assert!(source.contains("(void)r;"), "missing (void)r suppression");
}

#[test]
fn codegen_signed_type_cast() {
    let (_, source) = generate_c("packet P { x: i8 }");
    // Parse should cast the pointer for signed type
    assert!(
        source.contains("(uint8_t *)"),
        "missing unsigned pointer cast for i8 parse"
    );
    // Serialize should cast the value for signed type
    assert!(
        source.contains("(uint8_t)"),
        "missing unsigned value cast for i8 serialize"
    );
}

#[test]
fn codegen_frame_raw_tag() {
    let src = "frame F = match tag: u8 { 0 => A {}, _ => B { data: bytes[remaining] } }";
    let (header, source) = generate_c(src);
    // Header should have raw tag field in the frame struct
    assert!(
        header.contains("uint8_t frame_type;"),
        "missing raw tag field in header"
    );
    // Source should store the raw tag value
    assert!(
        source.contains("frame_type = _tag_val"),
        "missing raw tag store in parse"
    );
    // Serialize should write frame_type
    assert!(
        source.contains("val->frame_type"),
        "missing frame_type in serialize"
    );
}

#[test]
fn codegen_frame_default_case() {
    // Frames require a wildcard (_) branch per spec §4.2.
    // Verify that the wildcard variant generates a default: case.
    let src = "frame F = match tag: u8 { 0 => A {}, 1 => B { x: u8 }, _ => Unknown { data: bytes[remaining] } }";
    let (_, source) = generate_c(src);
    assert!(
        source.contains("default:"),
        "missing default case for wildcard variant"
    );
}

// ── VarInt codegen tests ──

#[test]
fn codegen_varint_prefix_match() {
    let src = r#"type VarInt = { prefix: bits[2], value: match prefix { 0b00 => bits[6], 0b01 => bits[14], 0b10 => bits[30], 0b11 => bits[62] } }"#;
    let (header, source) = generate_c(src);
    assert!(
        header.contains("typedef uint64_t"),
        "missing VarInt typedef"
    );
    assert!(header.contains("_parse"), "missing parse declaration");
    assert!(
        header.contains("_serialize"),
        "missing serialize declaration"
    );
    assert!(
        header.contains("_wire_size"),
        "missing wire_size declaration"
    );
    assert!(source.contains("prefix"), "missing prefix in parse");
}

#[test]
fn codegen_cont_varint() {
    let src = r#"type MqttLen = varint { continuation_bit: msb, value_bits: 7, max_bytes: 4, byte_order: little }"#;
    let (header, source) = generate_c(src);
    assert!(
        header.contains("typedef uint64_t"),
        "missing VarInt typedef"
    );
    assert!(
        source.contains("0x80") || source.contains("0x7F") || source.contains("0x7f"),
        "missing continuation bit mask"
    );
}

// ── Checksum codegen tests ──

#[test]
fn codegen_checksum_internet() {
    let src = "packet P { data: u32, @checksum(internet) checksum: u16 }";
    let (_, source) = generate_c(src);
    assert!(
        source.contains("wirespec_internet_checksum"),
        "missing internet checksum verify"
    );
    assert!(
        source.contains("WIRESPEC_ERR_CHECKSUM"),
        "missing checksum error"
    );
    assert!(
        source.contains("wirespec_internet_checksum_compute"),
        "missing internet checksum compute"
    );
}

// ── Const/Enum codegen tests ──

#[test]
fn codegen_const_define() {
    let src = "const MAX_LEN: u8 = 20\npacket P { x: u8 }";
    let (header, _) = generate_c(src);
    assert!(header.contains("#define"), "missing #define for const");
    assert!(header.contains("MAX_LEN"), "missing const name in #define");
}

#[test]
fn codegen_enum_typedef_define() {
    let src = "enum E: u8 { A = 0, B = 1 }\npacket P { x: u8 }";
    let (header, _) = generate_c(src);
    assert!(header.contains("typedef"), "missing typedef for enum");
    assert!(
        header.contains("#define"),
        "missing #define for enum members"
    );
}

// ── State machine codegen tests ──

#[test]
fn codegen_state_machine_header() {
    let src = r#"
        state machine PathState {
            state Init { path_id: u8 }
            state Active { path_id: u8, rtt: u64 = 0 }
            state Closed [terminal]

            initial Init

            transition Init -> Active {
                on activate(id: u8)
                action { dst.path_id = src.path_id; }
            }
            transition Active -> Closed { on close }
            transition * -> Closed { on error }
        }
    "#;
    let (header, _source) = generate_c(src);

    // State tag enum
    assert!(
        header.contains("_state_tag_t"),
        "missing state tag enum type"
    );
    assert!(
        header.contains("TEST_PATH_STATE_INIT"),
        "missing INIT state tag member"
    );
    assert!(
        header.contains("TEST_PATH_STATE_ACTIVE"),
        "missing ACTIVE state tag member"
    );
    assert!(
        header.contains("TEST_PATH_STATE_CLOSED"),
        "missing CLOSED state tag member"
    );

    // State data struct (tagged union)
    assert!(
        header.contains("test_path_state_t"),
        "missing state machine type name"
    );
    assert!(
        header.contains("uint8_t path_id"),
        "missing path_id field in state struct"
    );
    assert!(
        header.contains("uint64_t rtt"),
        "missing rtt field in state struct"
    );
    assert!(
        header.contains("uint8_t _unused"),
        "missing _unused placeholder for terminal state"
    );

    // Event tag enum
    assert!(
        header.contains("_event_tag_t"),
        "missing event tag enum type"
    );
    assert!(
        header.contains("EVENT_ACTIVATE"),
        "missing ACTIVATE event tag member"
    );
    assert!(
        header.contains("EVENT_CLOSE"),
        "missing CLOSE event tag member"
    );
    assert!(
        header.contains("EVENT_ERROR"),
        "missing ERROR event tag member"
    );

    // Event data struct
    assert!(
        header.contains("test_path_state_event_t"),
        "missing event struct type name"
    );

    // Dispatch declaration
    assert!(
        header.contains("_dispatch"),
        "missing dispatch function declaration"
    );

    // Init helper
    assert!(header.contains("_init"), "missing init helper function");
    assert!(
        header.contains("static inline void"),
        "init helper should be static inline"
    );
}

#[test]
fn codegen_state_machine_source() {
    let src = r#"
        state machine PathState {
            state Init { path_id: u8 }
            state Active { path_id: u8, rtt: u64 = 0 }
            state Closed [terminal]

            initial Init

            transition Init -> Active {
                on activate(id: u8)
                action { dst.path_id = src.path_id; }
            }
            transition Active -> Closed { on close }
            transition * -> Closed { on error }
        }
    "#;
    let (_header, source) = generate_c(src);

    // Dispatch function
    assert!(
        source.contains("src_tag"),
        "dispatch should use src_tag variable"
    );
    assert!(
        source.contains("WIRESPEC_OK"),
        "dispatch should return WIRESPEC_OK on successful transition"
    );
    assert!(
        source.contains("WIRESPEC_ERR_INVALID_STATE"),
        "dispatch should return WIRESPEC_ERR_INVALID_STATE as fallback"
    );
    assert!(
        source.contains("*sm = dst"),
        "dispatch should apply transition via *sm = dst"
    );
}

#[test]
fn codegen_state_machine_with_guard() {
    let src = r#"
        state machine S {
            state A { count: u8 = 0 }
            state B [terminal]
            initial A
            transition A -> A {
                on tick
                guard src.count < 10
                action { dst.count = src.count + 1; }
            }
            transition A -> B { on stop }
        }
    "#;
    let (header, source) = generate_c(src);

    // Header checks
    assert!(header.contains("_state_tag_t"), "missing state tag enum");
    assert!(header.contains("_event_tag_t"), "missing event tag enum");
    assert!(header.contains("_dispatch"), "missing dispatch decl");
    assert!(header.contains("uint8_t count"), "missing count field");

    // Source checks - guard
    assert!(
        source.contains("sm->a.count"),
        "guard should reference sm->a.count"
    );
    // Source checks - action
    assert!(
        source.contains("dst.a.count"),
        "action should set dst.a.count"
    );
    assert!(source.contains("src_tag"), "dispatch should use src_tag");
    assert!(
        source.contains("WIRESPEC_OK"),
        "dispatch should return WIRESPEC_OK"
    );
    assert!(
        source.contains("WIRESPEC_ERR_INVALID_STATE"),
        "dispatch should return WIRESPEC_ERR_INVALID_STATE"
    );
}

// ── Endianness codegen tests ──

#[test]
fn codegen_little_endian_module() {
    let src = "@endian little\npacket LittleEndianPacket { x: u16, y: u32 }";
    let (_, source) = generate_c(src);
    assert!(
        source.contains("read_u16le"),
        "should use read_u16le with @endian little, got:\n{}",
        source
    );
    assert!(
        source.contains("read_u32le"),
        "should use read_u32le with @endian little, got:\n{}",
        source
    );
}

#[test]
fn codegen_big_endian_module() {
    let src = "@endian big\npacket BigEndianPacket { x: u16, y: u32 }";
    let (_, source) = generate_c(src);
    assert!(
        source.contains("read_u16be"),
        "should use read_u16be with @endian big, got:\n{}",
        source
    );
    assert!(
        source.contains("read_u32be"),
        "should use read_u32be with @endian big, got:\n{}",
        source
    );
}

// ── Enum endianness propagation tests ──

#[test]
fn codegen_enum_little_endian() {
    let src = "@endian little\nmodule test\nenum E: u16 { A = 1 }\npacket P { code: E }";
    let (_, source) = generate_c(src);
    assert!(
        source.contains("read_u16le"),
        "enum field should use read_u16le, not read_u16be"
    );
}

// ── Range pattern safeguard tests ──

#[test]
fn codegen_frame_range_pattern() {
    let src = r#"
        frame F = match tag: u8 {
            0x00 => A {},
            0x08..=0x0f => B { x: u8 },
            _ => Unknown { data: bytes[remaining] },
        }
    "#;
    let (_, source) = generate_c(src);
    // All values in the range should appear as case labels
    assert!(source.contains("case 8:"), "missing case 8 for range start");
    assert!(source.contains("case 15:"), "missing case 15 for range end");
    assert!(source.contains("switch"), "missing switch statement");
}

// ── Fuzz harness codegen tests ──

#[test]
fn codegen_fuzz_harness() {
    let ast = wirespec_syntax::parse("packet P { x: u8, y: u16 }").unwrap();
    let sem = wirespec_sema::analyze(
        &ast,
        wirespec_sema::ComplianceProfile::default(),
        &Default::default(),
    )
    .unwrap();
    let layout = wirespec_layout::lower(&sem).unwrap();
    let codec = wirespec_codec::lower(&layout).unwrap();

    let backend = CBackend;
    let ctx = BackendContext {
        module_name: "test".into(),
        module_prefix: "test".into(),
        source_prefixes: Default::default(),
        compliance_profile: "phase2_extended_current".into(),
        common_options: CommonOptions::default(),
        target_options: Box::new(CBackendOptions {
            emit_fuzz_harness: true,
        }),
        checksum_bindings: Arc::new(checksum_binding::CChecksumBindings),
        is_entry_module: true,
    };

    let mut sink = MemorySink::new();
    let output = backend.lower_and_emit(&codec, &ctx, &mut sink).unwrap();
    assert_eq!(output.artifacts.len(), 3, "should emit .h + .c + _fuzz.c");
    assert_eq!(sink.artifacts.len(), 3, "sink should have 3 artifacts");

    let fuzz_content = String::from_utf8_lossy(&sink.artifacts[2].1);
    assert!(
        fuzz_content.contains("LLVMFuzzerTestOneInput"),
        "missing LLVMFuzzerTestOneInput"
    );
    assert!(
        fuzz_content.contains("__builtin_trap"),
        "missing __builtin_trap"
    );
    assert!(fuzz_content.contains("memcmp"), "missing memcmp");
    assert!(
        fuzz_content.contains("test_p_parse"),
        "missing parse function name"
    );
    assert!(
        fuzz_content.contains("test_p_serialize"),
        "missing serialize function name"
    );
    assert!(fuzz_content.contains("test_p_t"), "missing type name");
}

#[test]
fn codegen_no_fuzz_by_default() {
    let ast = wirespec_syntax::parse("packet P { x: u8 }").unwrap();
    let sem = wirespec_sema::analyze(
        &ast,
        wirespec_sema::ComplianceProfile::default(),
        &Default::default(),
    )
    .unwrap();
    let layout = wirespec_layout::lower(&sem).unwrap();
    let codec = wirespec_codec::lower(&layout).unwrap();

    let backend = CBackend;
    let ctx = BackendContext {
        module_name: "test".into(),
        module_prefix: "test".into(),
        source_prefixes: Default::default(),
        compliance_profile: "phase2_extended_current".into(),
        common_options: CommonOptions::default(),
        target_options: Box::new(CBackendOptions::default()),
        checksum_bindings: Arc::new(checksum_binding::CChecksumBindings),
        is_entry_module: true,
    };

    let mut sink = MemorySink::new();
    let output = backend.lower_and_emit(&codec, &ctx, &mut sink).unwrap();
    assert_eq!(
        output.artifacts.len(),
        2,
        "should emit only .h + .c (no fuzz)"
    );
    assert_eq!(
        sink.artifacts.len(),
        2,
        "sink should have 2 artifacts (no fuzz)"
    );
}

#[test]
fn codegen_fuzz_targets_frame_first() {
    let src = r#"frame F = match tag: u8 { 0 => A {}, _ => B { data: bytes[remaining] } }
    packet P { x: u8 }"#;
    let ast = wirespec_syntax::parse(src).unwrap();
    let sem = wirespec_sema::analyze(
        &ast,
        wirespec_sema::ComplianceProfile::default(),
        &Default::default(),
    )
    .unwrap();
    let layout = wirespec_layout::lower(&sem).unwrap();
    let codec = wirespec_codec::lower(&layout).unwrap();

    let backend = CBackend;
    let ctx = BackendContext {
        module_name: "test".into(),
        module_prefix: "test".into(),
        source_prefixes: Default::default(),
        compliance_profile: "phase2_extended_current".into(),
        common_options: CommonOptions::default(),
        target_options: Box::new(CBackendOptions {
            emit_fuzz_harness: true,
        }),
        checksum_bindings: Arc::new(checksum_binding::CChecksumBindings),
        is_entry_module: true,
    };

    let lowered = Backend::lower(&backend, &codec, &ctx).unwrap();
    let fuzz = lowered
        .fuzz_content
        .as_ref()
        .expect("fuzz content should exist");
    assert!(
        fuzz.contains("test_f_parse"),
        "should target frame F, not packet P"
    );
    assert!(
        fuzz.contains("test_f_serialize"),
        "should target frame F for serialize"
    );
    assert!(fuzz.contains("test_f_t"), "should use frame F type name");
}

// ── Advanced SM codegen tests ──

#[test]
fn codegen_sm_in_state_guard() {
    let src = r#"
        state machine S {
            state Active { status: u8 = 0 }
            state Done [terminal]
            initial Active
            transition Active -> Done {
                on finish
                guard src.status == 1
                action {}
            }
            transition * -> Done { on abort }
        }
    "#;
    let (header, source) = generate_c(src);
    assert!(source.contains("_dispatch"), "missing dispatch function");
    assert!(header.contains("TEST_S_ACTIVE"), "missing ACTIVE tag");
    assert!(header.contains("TEST_S_DONE"), "missing DONE tag");
    assert!(
        source.contains("sm->active.status"),
        "guard should reference sm->active.status"
    );
}

#[test]
fn codegen_sm_plus_assign() {
    let src = r#"
        state machine S {
            state A { count: u8 = 0 }
            state B [terminal]
            initial A
            transition A -> A {
                on tick
                guard src.count < 10
                action { dst.count = src.count + 1; }
            }
            transition A -> B { on done }
        }
    "#;
    let (_, source) = generate_c(src);
    assert!(source.contains("count"), "missing count field reference");
    assert!(source.contains("WIRESPEC_OK"), "missing WIRESPEC_OK return");
}

#[test]
fn codegen_frame_varint_tag_parse() {
    let src = r#"
        type VarInt = { prefix: bits[2], value: match prefix {
            0b00 => bits[6], 0b01 => bits[14], 0b10 => bits[30], 0b11 => bits[62],
        } }
        frame F = match tag: VarInt {
            0x06 => Crypto { offset: u32 },
            _ => Unknown { data: bytes[remaining] },
        }
    "#;
    let (_, source) = generate_c(src);
    // Should use VarInt parse, not read_u8
    assert!(source.contains("var_int_parse_cursor"));
    assert!(
        !source.contains("wirespec_cursor_read_u8(cur, &_tag_val)")
            || source.contains("var_int_parse_cursor")
    );
}

#[test]
fn codegen_fill_array() {
    let src = "packet P { items: [u8; fill] }";
    let (header, source) = generate_c(src);
    assert!(header.contains("items_count"));
    // Should have a loop parsing until cursor exhausted
    assert!(source.contains("wirespec_cursor_remaining"));
}

#[test]
fn codegen_fill_array_within() {
    let src = r#"
        packet P {
            length: u16,
            items: [u8; fill] within length,
        }
    "#;
    let (_, source) = generate_c(src);
    // Should create a sub-cursor bounded by length
    assert!(source.contains("wirespec_cursor_sub") || source.contains("_arr_sub"));
}

// ── Large range codegen tests ──

#[test]
fn test_large_range_no_panic() {
    // A frame variant matching range 0..=10000 is too large for individual case
    // labels (threshold is 4096).  The C backend should emit an if-guard with
    // >= and <= comparisons instead of 10001 case labels, and must not panic.
    let src = r#"
        frame F = match tag: u16 {
            0..=10000 => Big { x: u8 },
            _ => Other { data: bytes[remaining] },
        }
    "#;
    let (_, source) = generate_c(src);
    // Should contain an if-guard with range check, not 10001 case labels
    assert!(
        source.contains(">=") && source.contains("<="),
        "large range should use >= / <= if-guard instead of individual case labels. Got:\n{source}"
    );
    // Should NOT contain case 5000 (middle of range), proving it didn't expand
    assert!(
        !source.contains("case 5000:"),
        "large range should not expand to individual case labels. Got:\n{source}"
    );
}

#[test]
fn test_large_range_with_wildcard() {
    // A frame with both a large range variant AND a wildcard variant should
    // merge the large-range if-guard and the wildcard body into a single
    // default: block in the parse switch.  The parse function uses
    // switch (_tag_val) while the serialize function uses switch (val->tag),
    // so we count default: occurrences within the parse switch section.
    let src = r#"
        frame F = match tag: u16 {
            0..=10000 => Big { x: u8 },
            _ => Fallback { data: bytes[remaining] },
        }
    "#;
    let (_, source) = generate_c(src);
    // The parse function has a single switch(_tag_val) with a single default:
    // block.  Verify the total count of "default:" in the source is reasonable
    // (parse=1, serialize=1, serialized_len=1 = 3 total, not more).
    let default_count = source.matches("default:").count();
    assert_eq!(
        default_count, 3,
        "should have exactly 3 default: labels (parse, serialize, serialized_len), found {default_count}. Got:\n{source}"
    );
}

// ── Bounds checking / safety tests ──

#[test]
fn codegen_indexed_delegate_has_bounds_check() {
    let src = r#"
        state machine PathState {
            state Active {}
            state Closed [terminal]
            initial Active
            transition Active -> Closed { on close }
        }

        state machine Connection {
            state Open { paths: [PathState; 2] }
            state Done [terminal]
            initial Open
            transition Open -> Open {
                on close_path(idx: u8, ev: u8)
                delegate src.paths[idx] <- ev
            }
            transition Open -> Done { on shutdown }
        }
    "#;
    let (_, source) = generate_c(src);

    assert!(
        source.contains("WIRESPEC_ERR_BOUNDS"),
        "indexed delegate should emit a bounds check using WIRESPEC_ERR_BOUNDS. Got:\n{source}"
    );
    assert!(
        source.contains(">= 2"),
        "bounds check should compare index against array size 2. Got:\n{source}"
    );
}

#[test]
fn codegen_fill_action_comment_documents_safety() {
    let src = r#"
        state machine PathState {
            state Active {}
            state Closed [terminal]
            initial Active
            transition Active -> Closed { on close }
        }

        state machine Conn {
            state Init { paths: [PathState; 4] }
            state Done [terminal]
            initial Init
            transition Init -> Init {
                on reset
                action { dst.paths = fill(PathState::Active, 4); }
            }
            transition Init -> Done { on shutdown }
        }
    "#;
    let (_, source) = generate_c(src);

    assert!(
        source.contains("validated") || source.contains("compile time"),
        "fill loop should have a safety comment about compile-time validation. Got:\n{source}"
    );
}

#[test]
fn codegen_subscript_expr_documents_bounds_at_call_site() {
    let src = r#"
        state machine PathState {
            state Active {}
            state Closed [terminal]
            initial Active
            transition Active -> Closed { on close }
        }

        state machine Connection {
            state Open { paths: [PathState; 3] }
            state Done [terminal]
            initial Open
            transition Open -> Open {
                on close_path(idx: u8, ev: u8)
                delegate src.paths[idx] <- ev
            }
            transition Open -> Done { on shutdown }
        }
    "#;
    let (_, source) = generate_c(src);

    let bounds_pos = source.find("WIRESPEC_ERR_BOUNDS");
    let index_pos = source.find("paths[_idx]");
    assert!(
        bounds_pos.is_some() && index_pos.is_some(),
        "should have both bounds check and array indexing. Got:\n{source}"
    );
    assert!(
        bounds_pos.unwrap() < index_pos.unwrap(),
        "bounds check should appear before array indexing. Got:\n{source}"
    );
}