facet-format 0.44.6

Core Serializer/Deserializer traits for facet's next-generation format architecture with JIT compilation support
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
//! Cranelift-based compiler for deserializers.
//!
//! This module takes a `Shape` and generates native code that consumes
//! `ParseEvent`s and writes directly to struct memory.

use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Arc;

use cranelift::prelude::*;
use cranelift_jit::{JITBuilder, JITModule};
use cranelift_module::{FuncId, Linkage, Module};

use facet_core::{Def, Facet, Field, Shape, Type as FacetType, UserType};

use super::format::make_c_sig;
use super::helpers::{self, JitContext, ParserVTable};
use super::jit_debug;
use crate::{DeserializeError, DeserializeErrorKind, FormatParser};

/// Cached JIT module(s) that own the compiled code memory.
///
/// This struct keeps the JITModule alive to prevent the compiled code from being freed.
/// It also stores nested modules for complex types (e.g., structs with nested struct fields).
pub struct CachedModule {
    /// The main JIT module that owns the compiled code
    #[allow(dead_code)]
    module: JITModule,
    /// Nested modules for complex types (structs with nested structs)
    #[allow(dead_code)]
    nested_modules: Vec<JITModule>,
    /// The function pointer to the compiled deserializer
    fn_ptr: *const u8,
}

impl CachedModule {
    /// Create a new cached module.
    pub const fn new(module: JITModule, nested_modules: Vec<JITModule>, fn_ptr: *const u8) -> Self {
        Self {
            module,
            nested_modules,
            fn_ptr,
        }
    }

    /// Get the function pointer.
    pub const fn fn_ptr(&self) -> *const u8 {
        self.fn_ptr
    }
}

// Safety: The compiled code is thread-safe (no mutable state)
unsafe impl Send for CachedModule {}
unsafe impl Sync for CachedModule {}

/// A compiled deserializer for a specific type and parser.
pub struct CompiledDeserializer<T, P> {
    /// Pointer to the compiled function
    fn_ptr: *const u8,
    /// VTable for calling parser methods from JIT code
    vtable: ParserVTable,
    /// Reference to the cached module that owns the compiled code.
    /// This keeps the JIT memory alive while the deserializer is in use.
    _cached: Arc<CachedModule>,
    /// Phantom data for type safety
    _phantom: PhantomData<fn(&mut P) -> T>,
}

// Safety: The compiled code is thread-safe
unsafe impl<T, P> Send for CompiledDeserializer<T, P> {}
unsafe impl<T, P> Sync for CompiledDeserializer<T, P> {}

impl<T, P> CompiledDeserializer<T, P> {
    /// Create from a cached module and vtable.
    pub fn from_cached(cached: Arc<CachedModule>, vtable: ParserVTable) -> Self {
        let fn_ptr = cached.fn_ptr();
        Self {
            fn_ptr,
            vtable,
            _cached: cached,
            _phantom: PhantomData,
        }
    }

    /// Get the raw function pointer.
    pub const fn as_ptr(&self) -> *const u8 {
        self.fn_ptr
    }

    /// Get the vtable.
    pub const fn vtable(&self) -> &ParserVTable {
        &self.vtable
    }
}

impl<'de, T: Facet<'de>, P: FormatParser<'de>> CompiledDeserializer<T, P> {
    /// Execute the compiled deserializer.
    pub fn deserialize(&self, parser: &mut P) -> Result<T, DeserializeError> {
        // Create output storage
        let mut output: MaybeUninit<T> = MaybeUninit::uninit();

        // Create JIT context with parser pointer and vtable
        let mut ctx = JitContext {
            parser: parser as *mut P as *mut (),
            vtable: &self.vtable,
            peeked_event: None,
            fields_seen: 0, // Tracks which fields have been initialized (for cleanup on error)
        };

        if super::jit_debug_enabled() {
            jit_debug!("About to call compiled function at {:p}", self.fn_ptr);
            jit_debug!("  ctx: {:p}", &mut ctx);
            jit_debug!("  out: {:p}", output.as_mut_ptr());

            // Dump first 16 bytes of the function to see if it looks like code
            let code_bytes = unsafe { std::slice::from_raw_parts(self.fn_ptr, 16) };
            let bytes_str: String = code_bytes.iter().map(|b| format!("{:02x} ", b)).collect();
            jit_debug!("  First 16 bytes of function: {}", bytes_str);
        }

        // Call the compiled function
        // Signature: fn(ctx: *mut JitContext, out: *mut T) -> i32
        type CompiledFn<T> = unsafe extern "C" fn(*mut JitContext, *mut T) -> i32;
        let func: CompiledFn<T> = unsafe { std::mem::transmute(self.fn_ptr) };

        let result = unsafe { func(&mut ctx, output.as_mut_ptr()) };

        #[cfg(debug_assertions)]
        eprintln!("[JIT] Compiled function returned: {}", result);

        if result == 0 {
            // Safe: the JIT code validates all required fields are set via bitmask tracking
            // before returning 0 (success). Required fields (non-Option) must all be present,
            // otherwise the JIT returns ERR_MISSING_REQUIRED_FIELD.
            Ok(unsafe { output.assume_init() })
        } else {
            // Error path: clean up any partially-initialized fields
            // The JIT stored which fields were written in ctx.fields_seen
            let fields_seen = ctx.fields_seen;
            if fields_seen != 0 {
                // Drop any fields that were initialized before the error
                unsafe {
                    cleanup_partial_struct::<T>(output.as_mut_ptr() as *mut u8, fields_seen);
                }
            }

            if result == helpers::ERR_MISSING_REQUIRED_FIELD {
                Err(DeserializeError {
                    span: None, // JIT doesn't track span yet
                    path: None, // JIT doesn't track path yet
                    kind: DeserializeErrorKind::MissingField {
                        field: "unknown", // TODO: Track which field is missing
                        container_shape: T::SHAPE,
                    },
                })
            } else {
                Err(DeserializeError {
                    span: None,
                    path: None,
                    kind: DeserializeErrorKind::Bug {
                        error: format!("JIT deserialization failed with code {}", result).into(),
                        context: "tier-1 JIT execution",
                    },
                })
            }
        }
    }
}

/// Clean up a partially-initialized struct by dropping fields that were written.
///
/// # Safety
/// - `ptr` must point to valid memory for type T
/// - `fields_seen` must accurately reflect which fields have been initialized
/// - Only fields that actually need Drop will be dropped
unsafe fn cleanup_partial_struct<'a, T: Facet<'a>>(ptr: *mut u8, fields_seen: u64) {
    use facet_core::PtrMut;

    let shape = T::SHAPE;
    let FacetType::User(UserType::Struct(struct_def)) = &shape.ty else {
        return; // Only structs need cleanup
    };

    for (idx, field) in struct_def.fields.iter().enumerate() {
        // Check if this field was initialized
        if (fields_seen & (1u64 << idx)) == 0 {
            continue;
        }

        // Get the field's shape to check if it needs Drop
        let field_shape = field.shape();

        // Drop the field if it has a drop_in_place function
        // SAFETY: The field was initialized by the JIT, so it's safe to drop
        unsafe {
            let field_ptr = ptr.add(field.offset);
            let _ = field_shape.call_drop_in_place(PtrMut::new(field_ptr));
        }
    }
}

/// Check if a shape is JIT-compatible.
///
/// Currently supports:
/// - Simple structs without flatten fields or untagged enums
/// - `Vec<T>` where T is a supported element type (scalars, strings, nested Vecs, JIT-compatible structs)
pub fn is_jit_compatible(shape: &'static Shape) -> bool {
    // Check for Vec<T> types
    if let Def::List(list_def) = &shape.def {
        return is_vec_element_supported(list_def.t);
    }

    // Check if it's a struct via shape.ty
    let FacetType::User(UserType::Struct(struct_def)) = &shape.ty else {
        return false;
    };

    // Check for flatten
    if struct_def.fields.iter().any(|f| f.is_flattened()) {
        return false;
    }

    // Check that all field types are supported
    struct_def.fields.iter().all(is_field_type_supported)
}

/// Check if a field type is supported for JIT compilation.
fn is_field_type_supported(field: &Field) -> bool {
    // Just check if WriteKind::from_shape can handle this type
    WriteKind::from_shape(field.shape()).is_some()
}

/// Check if a Vec element type is supported for JIT compilation.
///
/// Supports:
/// - Primitives (f64, i64, etc.)
/// - Strings
/// - Nested Vecs (if their elements are also supported)
/// - JIT-compatible structs
fn is_vec_element_supported(elem_shape: &'static Shape) -> bool {
    use facet_core::ScalarType;

    // Check for supported scalar types
    if let Some(scalar_type) = elem_shape.scalar_type() {
        return matches!(
            scalar_type,
            ScalarType::Bool
                | ScalarType::U8
                | ScalarType::U16
                | ScalarType::U32
                | ScalarType::U64
                | ScalarType::I8
                | ScalarType::I16
                | ScalarType::I32
                | ScalarType::I64
                | ScalarType::F32
                | ScalarType::F64
                | ScalarType::String
        );
    }

    // Check for nested Vec
    if let Def::List(list_def) = &elem_shape.def {
        return is_vec_element_supported(list_def.t);
    }

    // Check for JIT-compatible struct
    if let FacetType::User(UserType::Struct(_)) = &elem_shape.ty {
        return is_jit_compatible(elem_shape);
    }

    false
}

/// Result of compiling a module, containing everything needed for caching.
pub struct CompileResult {
    /// The main JIT module
    pub module: JITModule,
    /// Nested modules for complex types
    pub nested_modules: Vec<JITModule>,
    /// Function pointer to the compiled deserializer
    pub fn_ptr: *const u8,
}

/// Try to compile a module for the given type.
///
/// Returns the module, nested modules, and function pointer on success.
/// The caller is responsible for keeping the modules alive.
pub fn try_compile_module<'de, T: Facet<'de>>() -> Option<CompileResult> {
    let shape = T::SHAPE;

    if !is_jit_compatible(shape) {
        return None;
    }

    // Build the JIT module
    let mut builder = JITBuilder::new(cranelift_module::default_libcall_names()).ok()?;

    // Register helper functions
    register_helpers(&mut builder);

    let mut module = JITModule::new(builder);

    // Compile the deserializer based on type
    let (func_id, nested_modules) = if let Def::List(_) = &shape.def {
        let func_id = compile_list_deserializer(&mut module, shape)?;
        (func_id, Vec::new())
    } else {
        compile_deserializer(&mut module, shape)?
    };

    // Finalize and get the function pointer
    module.finalize_definitions().ok()?;
    let fn_ptr = module.get_finalized_function(func_id);

    Some(CompileResult {
        module,
        nested_modules,
        fn_ptr,
    })
}

/// Register helper functions with the JIT module.
fn register_helpers(builder: &mut JITBuilder) {
    // Register the write helpers
    builder.symbol("jit_write_u8", helpers::jit_write_u8 as *const u8);
    builder.symbol("jit_write_u16", helpers::jit_write_u16 as *const u8);
    builder.symbol("jit_write_u32", helpers::jit_write_u32 as *const u8);
    builder.symbol("jit_write_u64", helpers::jit_write_u64 as *const u8);
    builder.symbol("jit_write_i8", helpers::jit_write_i8 as *const u8);
    builder.symbol("jit_write_i16", helpers::jit_write_i16 as *const u8);
    builder.symbol("jit_write_i32", helpers::jit_write_i32 as *const u8);
    builder.symbol("jit_write_i64", helpers::jit_write_i64 as *const u8);
    builder.symbol("jit_write_f32", helpers::jit_write_f32 as *const u8);
    builder.symbol("jit_write_f64", helpers::jit_write_f64 as *const u8);
    builder.symbol("jit_write_bool", helpers::jit_write_bool as *const u8);
    builder.symbol("jit_write_string", helpers::jit_write_string as *const u8);
    builder.symbol("jit_drop_in_place", helpers::jit_drop_in_place as *const u8);
    builder.symbol("jit_memcpy", helpers::jit_memcpy as *const u8);
    builder.symbol(
        "jit_write_error_string",
        helpers::jit_write_error_string as *const u8,
    );
    builder.symbol("jit_field_matches", helpers::jit_field_matches as *const u8);
    builder.symbol(
        "jit_deserialize_nested",
        helpers::jit_deserialize_nested as *const u8,
    );
    builder.symbol("jit_peek_event", helpers::jit_peek_event as *const u8);
    builder.symbol("jit_next_event", helpers::jit_next_event as *const u8);
    builder.symbol(
        "jit_option_init_none",
        helpers::jit_option_init_none as *const u8,
    );
    builder.symbol(
        "jit_option_init_some_from_value",
        helpers::jit_option_init_some_from_value as *const u8,
    );
    builder.symbol(
        "jit_vec_init_with_capacity",
        helpers::jit_vec_init_with_capacity as *const u8,
    );
    builder.symbol("jit_vec_push", helpers::jit_vec_push as *const u8);
    builder.symbol(
        "jit_deserialize_vec",
        helpers::jit_deserialize_vec as *const u8,
    );
    builder.symbol(
        "jit_deserialize_list_by_shape",
        helpers::jit_deserialize_list_by_shape as *const u8,
    );
    // Specialized push helpers for Vec JIT
    builder.symbol("jit_vec_push_bool", helpers::jit_vec_push_bool as *const u8);
    builder.symbol("jit_vec_push_i64", helpers::jit_vec_push_i64 as *const u8);
    builder.symbol("jit_vec_push_u64", helpers::jit_vec_push_u64 as *const u8);
    builder.symbol("jit_vec_push_f64", helpers::jit_vec_push_f64 as *const u8);
    builder.symbol(
        "jit_vec_push_string",
        helpers::jit_vec_push_string as *const u8,
    );
}

/// Element type classification for JIT code generation.
#[derive(Debug, Clone, Copy)]
enum ListElementKind {
    Bool,
    I64,
    U64,
    F64,
    String,
}

impl ListElementKind {
    fn from_shape(shape: &Shape) -> Option<Self> {
        use facet_core::ScalarType;
        let scalar_type = shape.scalar_type()?;
        match scalar_type {
            ScalarType::Bool => Some(Self::Bool),
            ScalarType::I8 | ScalarType::I16 | ScalarType::I32 | ScalarType::I64 => Some(Self::I64),
            ScalarType::U8 | ScalarType::U16 | ScalarType::U32 | ScalarType::U64 => Some(Self::U64),
            ScalarType::F32 | ScalarType::F64 => Some(Self::F64),
            ScalarType::String => Some(Self::String),
            _ => None,
        }
    }

    /// Returns whether this is a numeric type that accepts any numeric scalar tag.
    /// For numeric types, we accept I64, U64, and F64 since:
    /// - JSON doesn't distinguish signed/unsigned integers
    /// - JSON integers can be coerced to floats (e.g., `1` for f64)
    const fn is_numeric(&self) -> bool {
        matches!(
            self,
            ListElementKind::I64 | ListElementKind::U64 | ListElementKind::F64
        )
    }

    /// Returns the expected ScalarTag for non-numeric types.
    /// Returns None for numeric types (handled separately).
    const fn expected_non_numeric_tag(&self) -> Option<u8> {
        use helpers::ScalarTag;
        match self {
            ListElementKind::Bool => Some(ScalarTag::Bool as u8),
            ListElementKind::String => Some(ScalarTag::Str as u8),
            // Numeric types are handled separately
            ListElementKind::I64 | ListElementKind::U64 | ListElementKind::F64 => None,
        }
    }
}

/// Compile a deserializer function for a Vec/List type.
///
/// Generates specialized JIT code for the element type - no generic helper calls.
fn compile_list_deserializer(module: &mut JITModule, shape: &'static Shape) -> Option<FuncId> {
    let Def::List(list_def) = &shape.def else {
        return None;
    };

    let elem_shape = list_def.t;
    let elem_kind = ListElementKind::from_shape(elem_shape)?;

    // Get the init and push functions from the list def
    let init_fn = list_def.init_in_place_with_capacity()?;
    let push_fn = list_def.push()?;

    let pointer_type = module.target_config().pointer_type();

    // Function signature: fn(ctx: *mut JitContext, out: *mut T) -> i32
    let sig = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut T
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    // Helper signatures
    let sig_next_event = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx
        s.params.push(AbiParam::new(pointer_type)); // out: *mut RawEvent
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_peek_event = sig_next_event.clone();

    let sig_vec_init = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // capacity: usize
        s.params.push(AbiParam::new(pointer_type)); // init_fn: *const u8
        s
    };

    // Push signatures vary by type
    let sig_vec_push_scalar = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // vec_ptr
        s.params.push(AbiParam::new(pointer_type)); // push_fn
        match elem_kind {
            ListElementKind::Bool => s.params.push(AbiParam::new(types::I8)), // bool as i8
            ListElementKind::I64 => s.params.push(AbiParam::new(types::I64)),
            ListElementKind::U64 => s.params.push(AbiParam::new(types::I64)), // u64 passed as i64
            ListElementKind::F64 => s.params.push(AbiParam::new(types::F64)),
            ListElementKind::String => {
                s.params.push(AbiParam::new(pointer_type)); // ptr
                s.params.push(AbiParam::new(pointer_type)); // len
                s.params.push(AbiParam::new(pointer_type)); // capacity
                s.params.push(AbiParam::new(types::I8)); // owned
            }
        }
        s
    };

    // Declare helper functions
    let next_event_id = module
        .declare_function("jit_next_event", Linkage::Import, &sig_next_event)
        .ok()?;
    let _peek_event_id = module
        .declare_function("jit_peek_event", Linkage::Import, &sig_peek_event)
        .ok()?;
    let vec_init_id = module
        .declare_function("jit_vec_init_with_capacity", Linkage::Import, &sig_vec_init)
        .ok()?;

    let push_fn_name = match elem_kind {
        ListElementKind::Bool => "jit_vec_push_bool",
        ListElementKind::I64 => "jit_vec_push_i64",
        ListElementKind::U64 => "jit_vec_push_u64",
        ListElementKind::F64 => "jit_vec_push_f64",
        ListElementKind::String => "jit_vec_push_string",
    };
    let vec_push_id = module
        .declare_function(push_fn_name, Linkage::Import, &sig_vec_push_scalar)
        .ok()?;

    // Declare our function
    let func_id = module
        .declare_function("jit_deserialize_list", Linkage::Local, &sig)
        .ok()?;

    let mut ctx = module.make_context();
    ctx.func.signature = sig;

    let mut builder_ctx = FunctionBuilderContext::new();
    {
        let mut builder = FunctionBuilder::new(&mut ctx.func, &mut builder_ctx);

        // Import helper functions
        let next_event_ref = module.declare_func_in_func(next_event_id, builder.func);
        let vec_init_ref = module.declare_func_in_func(vec_init_id, builder.func);
        let vec_push_ref = module.declare_func_in_func(vec_push_id, builder.func);

        // Create all blocks upfront
        let entry = builder.create_block();
        let check_array_start = builder.create_block();
        let init_vec = builder.create_block();
        let loop_peek = builder.create_block(); // Named loop_peek for clarity, but uses next_event
        let check_end = builder.create_block();
        let push_elem = builder.create_block();
        let success = builder.create_block();
        let error = builder.create_block();

        // Entry block
        builder.append_block_params_for_function_params(entry);
        builder.switch_to_block(entry);

        let ctx_ptr = builder.block_params(entry)[0];
        let out_ptr = builder.block_params(entry)[1];

        // Allocate stack slot for RawEvent
        let raw_event_slot = builder.create_sized_stack_slot(StackSlotData::new(
            StackSlotKind::ExplicitSlot,
            helpers::RAW_EVENT_SIZE as u32,
            8,
        ));
        let raw_event_ptr = builder.ins().stack_addr(pointer_type, raw_event_slot, 0);

        // Constants
        let init_fn_ptr = builder
            .ins()
            .iconst(pointer_type, init_fn as *const () as i64);
        let push_fn_ptr = builder
            .ins()
            .iconst(pointer_type, push_fn as *const () as i64);
        let zero_cap = builder.ins().iconst(pointer_type, 0);

        // Read first event (should be ArrayStart)
        let call = builder
            .ins()
            .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
        let result = builder.inst_results(call)[0];
        let is_ok = builder.ins().icmp_imm(IntCC::Equal, result, 0);
        builder
            .ins()
            .brif(is_ok, check_array_start, &[], error, &[]);
        builder.seal_block(entry);

        // Check ArrayStart
        builder.switch_to_block(check_array_start);
        let tag = builder.ins().load(
            types::I8,
            MemFlags::trusted(),
            raw_event_ptr,
            helpers::RAW_EVENT_TAG_OFFSET as i32,
        );
        let is_array_start =
            builder
                .ins()
                .icmp_imm(IntCC::Equal, tag, helpers::EventTag::ArrayStart as i64);
        builder
            .ins()
            .brif(is_array_start, init_vec, &[], error, &[]);
        builder.seal_block(check_array_start);

        // Initialize Vec
        builder.switch_to_block(init_vec);
        builder
            .ins()
            .call(vec_init_ref, &[out_ptr, zero_cap, init_fn_ptr]);
        builder.ins().jump(loop_peek, &[]);
        builder.seal_block(init_vec);

        // Loop: get next event (combines peek+consume into single call)
        builder.switch_to_block(loop_peek);
        let call = builder
            .ins()
            .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
        let result = builder.inst_results(call)[0];
        let is_ok = builder.ins().icmp_imm(IntCC::Equal, result, 0);
        builder.ins().brif(is_ok, check_end, &[], error, &[]);

        // Check for ArrayEnd - if so, we're done; otherwise push the element
        builder.switch_to_block(check_end);
        let tag = builder.ins().load(
            types::I8,
            MemFlags::trusted(),
            raw_event_ptr,
            helpers::RAW_EVENT_TAG_OFFSET as i32,
        );
        let is_end = builder
            .ins()
            .icmp_imm(IntCC::Equal, tag, helpers::EventTag::ArrayEnd as i64);
        builder.ins().brif(is_end, success, &[], push_elem, &[]);
        builder.seal_block(check_end);

        // Push element - extract scalar from payload and call push
        // The event data is already in raw_event_ptr from next_event above
        builder.switch_to_block(push_elem);

        // Validate scalar tag before reading payload to prevent type confusion
        let actual_tag = builder.ins().load(
            types::I8,
            MemFlags::trusted(),
            raw_event_ptr,
            helpers::RAW_EVENT_SCALAR_TAG_OFFSET as i32,
        );

        let validated_block = builder.create_block();
        if elem_kind.is_numeric() {
            // For numeric types, accept any of I64, U64, F64
            let is_i64 =
                builder
                    .ins()
                    .icmp_imm(IntCC::Equal, actual_tag, helpers::ScalarTag::I64 as i64);
            let check_u64 = builder.create_block();
            builder
                .ins()
                .brif(is_i64, validated_block, &[], check_u64, &[]);

            builder.switch_to_block(check_u64);
            let is_u64 =
                builder
                    .ins()
                    .icmp_imm(IntCC::Equal, actual_tag, helpers::ScalarTag::U64 as i64);
            let check_f64 = builder.create_block();
            builder
                .ins()
                .brif(is_u64, validated_block, &[], check_f64, &[]);

            builder.switch_to_block(check_f64);
            let is_f64 =
                builder
                    .ins()
                    .icmp_imm(IntCC::Equal, actual_tag, helpers::ScalarTag::F64 as i64);
            builder.ins().brif(is_f64, validated_block, &[], error, &[]);

            builder.seal_block(check_u64);
            builder.seal_block(check_f64);
        } else if let Some(expected_tag) = elem_kind.expected_non_numeric_tag() {
            // For bool/string, require exact match
            let tag_matches = builder
                .ins()
                .icmp_imm(IntCC::Equal, actual_tag, expected_tag as i64);
            builder
                .ins()
                .brif(tag_matches, validated_block, &[], error, &[]);
        } else {
            // No validation needed (shouldn't happen for list elements)
            builder.ins().jump(validated_block, &[]);
        }
        builder.switch_to_block(validated_block);

        let payload_ptr = builder
            .ins()
            .iadd_imm(raw_event_ptr, helpers::RAW_EVENT_PAYLOAD_OFFSET as i64);

        match elem_kind {
            ListElementKind::Bool => {
                let val = builder
                    .ins()
                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                builder
                    .ins()
                    .call(vec_push_ref, &[out_ptr, push_fn_ptr, val]);
            }
            ListElementKind::I64 => {
                let val = builder
                    .ins()
                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                builder
                    .ins()
                    .call(vec_push_ref, &[out_ptr, push_fn_ptr, val]);
            }
            ListElementKind::U64 => {
                let val = builder
                    .ins()
                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                builder
                    .ins()
                    .call(vec_push_ref, &[out_ptr, push_fn_ptr, val]);
            }
            ListElementKind::F64 => {
                let val = builder
                    .ins()
                    .load(types::F64, MemFlags::trusted(), payload_ptr, 0);
                builder
                    .ins()
                    .call(vec_push_ref, &[out_ptr, push_fn_ptr, val]);
            }
            ListElementKind::String => {
                // Load string payload fields
                let str_ptr = builder.ins().load(
                    pointer_type,
                    MemFlags::trusted(),
                    payload_ptr,
                    helpers::STRING_PTR_OFFSET as i32,
                );
                let str_len = builder.ins().load(
                    pointer_type,
                    MemFlags::trusted(),
                    payload_ptr,
                    helpers::STRING_LEN_OFFSET as i32,
                );
                let str_cap = builder.ins().load(
                    pointer_type,
                    MemFlags::trusted(),
                    payload_ptr,
                    helpers::STRING_CAPACITY_OFFSET as i32,
                );
                let str_owned = builder.ins().load(
                    types::I8,
                    MemFlags::trusted(),
                    payload_ptr,
                    helpers::STRING_OWNED_OFFSET as i32,
                );
                builder.ins().call(
                    vec_push_ref,
                    &[out_ptr, push_fn_ptr, str_ptr, str_len, str_cap, str_owned],
                );
            }
        }
        builder.ins().jump(loop_peek, &[]);
        builder.seal_block(push_elem);
        builder.seal_block(validated_block);

        // Now we can seal loop_peek since all predecessors are known
        builder.seal_block(loop_peek);

        // Success: return 0 (ArrayEnd was already consumed by next_event)
        builder.switch_to_block(success);
        let zero = builder.ins().iconst(types::I32, 0);
        builder.ins().return_(&[zero]);
        builder.seal_block(success);

        // Error: return -10
        builder.switch_to_block(error);
        let err = builder.ins().iconst(types::I32, -10);
        builder.ins().return_(&[err]);
        builder.seal_block(error);

        builder.finalize();
    }

    // Define the function
    module.define_function(func_id, &mut ctx).ok()?;

    Some(func_id)
}

/// Compile a deserializer function for a struct.
///
/// Returns the function ID and a Vec of all nested JITModules that must be kept alive.
fn compile_deserializer(
    module: &mut JITModule,
    shape: &'static Shape,
) -> Option<(FuncId, Vec<JITModule>)> {
    let FacetType::User(UserType::Struct(struct_def)) = &shape.ty else {
        return None;
    };

    // DEBUG: Log the shape we're compiling
    #[cfg(debug_assertions)]
    {
        eprintln!("[JIT DEBUG] ========================================");
        eprintln!("[JIT DEBUG] Compiling deserializer for: {shape}");
        eprintln!("[JIT DEBUG] Shape pointer: {:p}", shape);
        eprintln!("[JIT DEBUG] Shape.id (ConstTypeId): {:?}", shape.id);
        eprintln!("[JIT DEBUG] Shape.layout: {:?}", shape.layout);
        eprintln!("[JIT DEBUG] struct_def pointer: {:p}", struct_def);
        eprintln!(
            "[JIT DEBUG] struct_def.fields pointer: {:p}",
            struct_def.fields.as_ptr()
        );
        eprintln!(
            "[JIT DEBUG] struct_def.fields.len() = {}",
            struct_def.fields.len()
        );
        eprintln!("[JIT DEBUG] Fields from Shape (struct_def.fields):");
        for (i, f) in struct_def.fields.iter().enumerate() {
            let field_ptr = f as *const facet_core::Field;
            // Also get the field's inner shape to see if it's pointing to something weird
            let field_shape = f.shape();
            eprintln!(
                "[JIT DEBUG]   [{}] field_ptr={:p}, name='{}', offset={}",
                i, field_ptr, f.name, f.offset
            );
            eprintln!(
                "[JIT DEBUG]       field_shape_ptr={:p}, field_shape_type='{field_shape}'",
                field_shape as *const _
            );
        }

        // If this is UserSparse, also print what the ACTUAL offsets should be
        if shape.type_identifier == "UserSparse" {
            eprintln!("[JIT DEBUG] *** UserSparse detected - checking actual memory layout ***");
            eprintln!(
                "[JIT DEBUG] sizeof(UserSparse shape) struct_def layout says: {:?}",
                shape.layout
            );
            eprintln!("[JIT DEBUG] struct_def.repr: {:?}", struct_def.repr);
            eprintln!("[JIT DEBUG] struct_def.kind: {:?}", struct_def.kind);
        }
        eprintln!("[JIT DEBUG] ----------------------------------------");
    }

    // Extract field info for code generation.
    // Track:
    // - `required_bit_index` for missing-required validation
    // - `seen_bit_index` (real struct field index) for duplicate handling/cleanup
    let mut required_bit_counter = 0usize;
    let mut fields: Vec<FieldCodegenInfo> = Vec::with_capacity(struct_def.fields.len());
    for (field_index, f) in struct_def.fields.iter().enumerate() {
        let write_kind = WriteKind::from_shape(f.shape())?;
        let is_required = !matches!(write_kind, WriteKind::Option(_));
        let required_bit_index = if is_required {
            let idx = required_bit_counter;
            required_bit_counter += 1;
            Some(idx)
        } else {
            None
        };
        fields.push(FieldCodegenInfo {
            name: f.effective_name(),
            offset: f.offset,
            shape: f.shape(),
            write_kind,
            seen_bit_index: field_index,
            required_bit_index,
        });
    }

    // DEBUG: Log the extracted fields
    #[cfg(debug_assertions)]
    {
        eprintln!(
            "[JIT DEBUG] Extracted FieldCodegenInfo ({} fields):",
            fields.len()
        );
        for (i, f) in fields.iter().enumerate() {
            eprintln!(
                "[JIT DEBUG]   [{}] name='{}', offset={}",
                i, f.name, f.offset
            );
        }
        eprintln!("[JIT DEBUG] ========================================");
    }

    // Check if we have too many required fields for the bitmask (u64 can track 0-63, max 64 fields)
    // Note: 64 required fields would need `1u64 << 64` which overflows, so max is 63.
    if required_bit_counter >= 64 {
        jit_debug!(
            "[Tier-2 JIT] Too many required fields ({} >= 64, max 63 for u64 bitmask)",
            required_bit_counter
        );
        return None;
    }

    // `ctx.fields_seen` is a u64 indexed by *field index*.
    // Keep Tier-1 limited to at most 63 fields so tracking never overflows.
    if fields.len() >= 64 {
        jit_debug!(
            "[Tier-1 JIT] Too many fields ({} >= 64, max 63 for u64 field-seen bitmask)",
            fields.len()
        );
        return None;
    }

    // Calculate the expected bitmask for all required fields
    let required_fields_mask: u64 = if required_bit_counter > 0 {
        (1u64 << required_bit_counter) - 1
    } else {
        0
    };

    // Pre-compile nested types (structs, Option inner types, Vec element types).
    // We do this before building the parent to avoid any potential issues.
    // Each type gets compiled once and cached.
    // IMPORTANT: We must keep the JITModules alive, so we collect them in all_nested_modules.
    let mut nested_lookup: std::collections::HashMap<*const Shape, *const u8> =
        std::collections::HashMap::new();
    let mut all_nested_modules: Vec<JITModule> = Vec::new();

    // Helper to compile a shape and cache it
    let mut compile_and_cache = |shape: &'static Shape| -> Option<*const u8> {
        #[cfg(debug_assertions)]
        eprintln!("[JIT DEBUG] compile_and_cache called for nested shape: {shape} at {shape:p}");

        let ptr = shape as *const Shape;
        if let std::collections::hash_map::Entry::Vacant(e) = nested_lookup.entry(ptr) {
            #[cfg(debug_assertions)]
            eprintln!("[JIT DEBUG]   -> compiling nested shape (not in cache)");

            let mut nested_builder =
                JITBuilder::new(cranelift_module::default_libcall_names()).ok()?;
            register_helpers(&mut nested_builder);
            let mut nested_module = JITModule::new(nested_builder);
            let (nested_func_id, sub_nested_modules) =
                compile_deserializer(&mut nested_module, shape)?;
            nested_module.finalize_definitions().ok()?;
            let fn_ptr = nested_module.get_finalized_function(nested_func_id);
            e.insert(fn_ptr);
            // Keep the nested module alive by storing it
            all_nested_modules.push(nested_module);
            // Also keep any sub-nested modules (for deeply nested types)
            all_nested_modules.extend(sub_nested_modules);
            Some(fn_ptr)
        } else {
            #[cfg(debug_assertions)]
            eprintln!("[JIT DEBUG]   -> using cached nested shape");
            Some(nested_lookup[&ptr])
        }
    };

    for field in &fields {
        match field.write_kind {
            WriteKind::NestedStruct(nested_shape) => {
                compile_and_cache(nested_shape);
            }
            WriteKind::Option(option_shape) => {
                // Pre-compile the inner type if it's a struct
                if let Def::Option(option_def) = &option_shape.def {
                    let inner_shape = option_def.t;
                    if let FacetType::User(UserType::Struct(_)) = &inner_shape.ty
                        && is_jit_compatible(inner_shape)
                    {
                        compile_and_cache(inner_shape);
                    }
                }
            }
            WriteKind::Vec(vec_shape) => {
                // Pre-compile the element type if it's a struct
                if let Def::List(list_def) = &vec_shape.def {
                    let elem_shape = list_def.t;
                    if let FacetType::User(UserType::Struct(_)) = &elem_shape.ty
                        && is_jit_compatible(elem_shape)
                    {
                        compile_and_cache(elem_shape);
                    }
                }
            }
            _ => {}
        }
    }

    let pointer_type = module.target_config().pointer_type();

    // Function signature: fn(ctx: *mut JitContext, out: *mut T) -> i32
    let mut sig = make_c_sig(module);
    sig.params.push(AbiParam::new(pointer_type)); // ctx
    sig.params.push(AbiParam::new(pointer_type)); // out
    sig.returns.push(AbiParam::new(types::I32)); // result

    // Create unique function name
    static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let func_name = format!(
        "jit_deserialize_{}",
        COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
    );

    let func_id = module
        .declare_function(&func_name, Linkage::Local, &sig)
        .ok()?;

    // Declare helper function signatures
    let sig_next_event = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut RawEvent
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_peek_event = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut RawEvent
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_skip_value = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // parser
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_field_matches = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // name_ptr
        s.params.push(AbiParam::new(pointer_type)); // name_len
        s.params.push(AbiParam::new(pointer_type)); // expected_ptr
        s.params.push(AbiParam::new(pointer_type)); // expected_len
        s.returns.push(AbiParam::new(types::I32)); // 1 if match, 0 otherwise
        s
    };

    let sig_write_i64 = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::I64)); // value
        s
    };

    let sig_write_u64 = sig_write_i64.clone();

    let sig_write_i8 = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::I8)); // value
        s
    };

    let sig_write_i16 = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::I16)); // value
        s
    };

    let sig_write_i32 = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::I32)); // value
        s
    };

    let sig_write_u8 = sig_write_i8.clone();

    let sig_write_u16 = sig_write_i16.clone();

    let sig_write_u32 = sig_write_i32.clone();

    let sig_write_f64 = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::F64)); // value
        s
    };

    let sig_write_bool = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(types::I8)); // value (bool as i8)
        s
    };

    let sig_write_string = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out
        s.params.push(AbiParam::new(pointer_type)); // offset
        s.params.push(AbiParam::new(pointer_type)); // ptr
        s.params.push(AbiParam::new(pointer_type)); // len
        s.params.push(AbiParam::new(pointer_type)); // capacity
        s.params.push(AbiParam::new(types::I8)); // owned (bool as i8)
        s
    };

    let sig_deserialize_nested = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // func_ptr: *const u8
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_option_init_none = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // init_none_fn: *const u8
        s
    };

    let sig_option_init_some_from_value = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // value_ptr: *const u8
        s.params.push(AbiParam::new(pointer_type)); // init_some_fn: *const u8
        s
    };

    let sig_drop_in_place = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // shape_ptr: *const Shape
        s.params.push(AbiParam::new(pointer_type)); // ptr: *mut u8
        s
    };

    let sig_vec_init_with_capacity = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // capacity: usize
        s.params.push(AbiParam::new(pointer_type)); // init_fn: *const u8
        s
    };

    let sig_vec_push = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // vec_ptr: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // push_fn: *const u8
        s.params.push(AbiParam::new(pointer_type)); // item_deserializer: *const u8
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    let sig_deserialize_vec = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // init_fn: *const u8
        s.params.push(AbiParam::new(pointer_type)); // push_fn: *const u8
        s.params.push(AbiParam::new(pointer_type)); // elem_size: usize
        s.params.push(AbiParam::new(pointer_type)); // elem_deserializer: *const u8
        s.params.push(AbiParam::new(types::I8)); // scalar_tag: u8
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    // Simpler signature for recursive list deserialization by shape
    let sig_deserialize_list_by_shape = {
        let mut s = make_c_sig(module);
        s.params.push(AbiParam::new(pointer_type)); // ctx: *mut JitContext
        s.params.push(AbiParam::new(pointer_type)); // out: *mut u8
        s.params.push(AbiParam::new(pointer_type)); // list_shape: *const Shape
        s.params.push(AbiParam::new(pointer_type)); // elem_struct_deserializer: *const u8 (or null)
        s.returns.push(AbiParam::new(types::I32)); // result
        s
    };

    // Declare all helper functions
    let field_matches_id = module
        .declare_function("jit_field_matches", Linkage::Import, &sig_field_matches)
        .ok()?;
    let write_i64_id = module
        .declare_function("jit_write_i64", Linkage::Import, &sig_write_i64)
        .ok()?;
    let write_u64_id = module
        .declare_function("jit_write_u64", Linkage::Import, &sig_write_u64)
        .ok()?;
    let write_i8_id = module
        .declare_function("jit_write_i8", Linkage::Import, &sig_write_i8)
        .ok()?;
    let write_i16_id = module
        .declare_function("jit_write_i16", Linkage::Import, &sig_write_i16)
        .ok()?;
    let write_i32_id = module
        .declare_function("jit_write_i32", Linkage::Import, &sig_write_i32)
        .ok()?;
    let write_u8_id = module
        .declare_function("jit_write_u8", Linkage::Import, &sig_write_u8)
        .ok()?;
    let write_u16_id = module
        .declare_function("jit_write_u16", Linkage::Import, &sig_write_u16)
        .ok()?;
    let write_u32_id = module
        .declare_function("jit_write_u32", Linkage::Import, &sig_write_u32)
        .ok()?;
    let write_f64_id = module
        .declare_function("jit_write_f64", Linkage::Import, &sig_write_f64)
        .ok()?;
    let write_bool_id = module
        .declare_function("jit_write_bool", Linkage::Import, &sig_write_bool)
        .ok()?;
    let write_string_id = module
        .declare_function("jit_write_string", Linkage::Import, &sig_write_string)
        .ok()?;
    let deserialize_nested_id = module
        .declare_function(
            "jit_deserialize_nested",
            Linkage::Import,
            &sig_deserialize_nested,
        )
        .ok()?;
    let peek_event_id = module
        .declare_function("jit_peek_event", Linkage::Import, &sig_peek_event)
        .ok()?;
    let next_event_id = module
        .declare_function("jit_next_event", Linkage::Import, &sig_next_event)
        .ok()?;
    let option_init_none_id = module
        .declare_function(
            "jit_option_init_none",
            Linkage::Import,
            &sig_option_init_none,
        )
        .ok()?;
    let option_init_some_from_value_id = module
        .declare_function(
            "jit_option_init_some_from_value",
            Linkage::Import,
            &sig_option_init_some_from_value,
        )
        .ok()?;
    let drop_in_place_id = module
        .declare_function("jit_drop_in_place", Linkage::Import, &sig_drop_in_place)
        .ok()?;
    let vec_init_with_capacity_id = module
        .declare_function(
            "jit_vec_init_with_capacity",
            Linkage::Import,
            &sig_vec_init_with_capacity,
        )
        .ok()?;
    let vec_push_id = module
        .declare_function("jit_vec_push", Linkage::Import, &sig_vec_push)
        .ok()?;
    let deserialize_vec_id = module
        .declare_function("jit_deserialize_vec", Linkage::Import, &sig_deserialize_vec)
        .ok()?;
    let deserialize_list_by_shape_id = module
        .declare_function(
            "jit_deserialize_list_by_shape",
            Linkage::Import,
            &sig_deserialize_list_by_shape,
        )
        .ok()?;

    let mut ctx = module.make_context();
    ctx.func.signature = sig;

    // Build the function body
    let mut builder_ctx = FunctionBuilderContext::new();
    {
        let mut builder = FunctionBuilder::new(&mut ctx.func, &mut builder_ctx);

        // Import helper functions
        let field_matches_ref = module.declare_func_in_func(field_matches_id, builder.func);
        let write_i64_ref = module.declare_func_in_func(write_i64_id, builder.func);
        let write_u64_ref = module.declare_func_in_func(write_u64_id, builder.func);
        let write_i8_ref = module.declare_func_in_func(write_i8_id, builder.func);
        let write_i16_ref = module.declare_func_in_func(write_i16_id, builder.func);
        let write_i32_ref = module.declare_func_in_func(write_i32_id, builder.func);
        let write_u8_ref = module.declare_func_in_func(write_u8_id, builder.func);
        let write_u16_ref = module.declare_func_in_func(write_u16_id, builder.func);
        let write_u32_ref = module.declare_func_in_func(write_u32_id, builder.func);
        let write_f64_ref = module.declare_func_in_func(write_f64_id, builder.func);
        let write_bool_ref = module.declare_func_in_func(write_bool_id, builder.func);
        let write_string_ref = module.declare_func_in_func(write_string_id, builder.func);
        let deserialize_nested_ref =
            module.declare_func_in_func(deserialize_nested_id, builder.func);
        let peek_event_ref = module.declare_func_in_func(peek_event_id, builder.func);
        let next_event_ref = module.declare_func_in_func(next_event_id, builder.func);
        let option_init_none_ref = module.declare_func_in_func(option_init_none_id, builder.func);
        let option_init_some_from_value_ref =
            module.declare_func_in_func(option_init_some_from_value_id, builder.func);
        let drop_in_place_ref = module.declare_func_in_func(drop_in_place_id, builder.func);
        let _vec_init_with_capacity_ref =
            module.declare_func_in_func(vec_init_with_capacity_id, builder.func);
        let _vec_push_ref = module.declare_func_in_func(vec_push_id, builder.func);
        let _deserialize_vec_ref = module.declare_func_in_func(deserialize_vec_id, builder.func);
        let deserialize_list_by_shape_ref =
            module.declare_func_in_func(deserialize_list_by_shape_id, builder.func);

        // Create entry block
        let entry_block = builder.create_block();
        builder.append_block_params_for_function_params(entry_block);
        builder.switch_to_block(entry_block);
        builder.seal_block(entry_block);

        // Get parameters
        let ctx_ptr = builder.block_params(entry_block)[0];
        let out_ptr = builder.block_params(entry_block)[1];

        // Create variable to track which required fields have been set (bitmask)
        let required_fields_seen = builder.declare_var(types::I64);
        let zero_i64 = builder.ins().iconst(types::I64, 0);
        builder.def_var(required_fields_seen, zero_i64);
        // Track all fields initialized so far (bit index == struct field index).
        // Used for duplicate-key drop-before-overwrite and error cleanup.
        let fields_seen = builder.declare_var(types::I64);
        builder.def_var(fields_seen, zero_i64);

        // Allocate stack slot for RawEvent
        let raw_event_slot = builder.create_sized_stack_slot(StackSlotData::new(
            StackSlotKind::ExplicitSlot,
            helpers::RAW_EVENT_SIZE as u32,
            8, // alignment
        ));
        let raw_event_ptr = builder.ins().stack_addr(pointer_type, raw_event_slot, 0);

        // Load parser pointer from ctx
        let parser_ptr = builder.ins().load(
            pointer_type,
            MemFlags::trusted(),
            ctx_ptr,
            helpers::JIT_CONTEXT_PARSER_OFFSET as i32,
        );

        // Load vtable pointer from ctx
        let vtable_ptr = builder.ins().load(
            pointer_type,
            MemFlags::trusted(),
            ctx_ptr,
            helpers::JIT_CONTEXT_VTABLE_OFFSET as i32,
        );

        // Load skip_value function pointer from vtable
        let skip_value_fn = builder.ins().load(
            pointer_type,
            MemFlags::trusted(),
            vtable_ptr,
            helpers::VTABLE_SKIP_VALUE_OFFSET as i32,
        );

        // Create blocks
        let error_block = builder.create_block();
        let success_block = builder.create_block();
        let field_loop = builder.create_block();

        // Import the signature for indirect calls (skip_value only)
        let sig_skip_value_ref = builder.import_signature(sig_skip_value.clone());

        // Call jit_next_event to get StructStart (uses JitContext for peek buffer)
        let call_result = builder
            .ins()
            .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
        let result = builder.inst_results(call_result)[0];

        // Check for error
        let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
        let check_struct_start = builder.create_block();
        builder
            .ins()
            .brif(is_error, error_block, &[], check_struct_start, &[]);

        builder.switch_to_block(check_struct_start);
        // Load tag and check it's StructStart (0)
        let tag = builder.ins().load(
            types::I8,
            MemFlags::trusted(),
            raw_event_ptr,
            helpers::RAW_EVENT_TAG_OFFSET as i32,
        );
        let is_struct_start = builder.ins().icmp_imm(IntCC::Equal, tag, 0); // EventTag::StructStart = 0

        // Create block to initialize Option fields to None before parsing
        let init_options_block = builder.create_block();
        builder
            .ins()
            .brif(is_struct_start, init_options_block, &[], error_block, &[]);

        // Initialize all Option fields to None before deserialization
        // This ensures missing Option fields are properly initialized (not UB)
        builder.switch_to_block(init_options_block);
        for field in &fields {
            if let WriteKind::Option(option_shape) = field.write_kind {
                let Def::Option(option_def) = &option_shape.def else {
                    continue;
                };
                let init_none_fn_ptr = option_def.vtable.init_none as *const u8;
                let init_none_fn_val = builder.ins().iconst(pointer_type, init_none_fn_ptr as i64);
                let offset_val = builder.ins().iconst(pointer_type, field.offset as i64);
                let field_ptr = builder.ins().iadd(out_ptr, offset_val);
                builder
                    .ins()
                    .call(option_init_none_ref, &[field_ptr, init_none_fn_val]);
            }
        }
        builder.ins().jump(field_loop, &[]);
        builder.seal_block(init_options_block);

        // Field loop
        builder.switch_to_block(field_loop);

        // Call jit_next_event (uses JitContext for peek buffer)
        let call_result = builder
            .ins()
            .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
        let result = builder.inst_results(call_result)[0];

        // Check for error
        let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
        let check_event_tag = builder.create_block();
        builder
            .ins()
            .brif(is_error, error_block, &[], check_event_tag, &[]);

        builder.switch_to_block(check_event_tag);
        // Load tag
        let tag = builder.ins().load(
            types::I8,
            MemFlags::trusted(),
            raw_event_ptr,
            helpers::RAW_EVENT_TAG_OFFSET as i32,
        );

        // Check for StructEnd (1)
        let is_struct_end = builder.ins().icmp_imm(IntCC::Equal, tag, 1); // EventTag::StructEnd = 1
        let check_field_key = builder.create_block();
        builder
            .ins()
            .brif(is_struct_end, success_block, &[], check_field_key, &[]);

        builder.switch_to_block(check_field_key);
        // Check for FieldKey (4)
        let is_field_key = builder.ins().icmp_imm(IntCC::Equal, tag, 4); // EventTag::FieldKey = 4
        let process_field = builder.create_block();
        builder
            .ins()
            .brif(is_field_key, process_field, &[], error_block, &[]);

        builder.switch_to_block(process_field);

        // Load field name ptr and len from payload
        let payload_ptr = builder
            .ins()
            .iadd_imm(raw_event_ptr, helpers::RAW_EVENT_PAYLOAD_OFFSET as i64);
        let name_ptr = builder.ins().load(
            pointer_type,
            MemFlags::trusted(),
            payload_ptr,
            helpers::FIELD_NAME_PTR_OFFSET as i32,
        );
        let name_len = builder.ins().load(
            pointer_type,
            MemFlags::trusted(),
            payload_ptr,
            helpers::FIELD_NAME_LEN_OFFSET as i32,
        );

        // Create blocks for each field and a default (skip) block
        let field_blocks: Vec<Block> = fields.iter().map(|_| builder.create_block()).collect();
        let skip_field_block = builder.create_block();
        let after_field = builder.create_block();

        // Create "set bit and continue" blocks for each required field
        // These blocks OR in the required bit and then jump to after_field
        let set_bit_blocks: Vec<Option<Block>> = fields
            .iter()
            .map(|f| {
                if f.required_bit_index.is_some() {
                    Some(builder.create_block())
                } else {
                    None
                }
            })
            .collect();
        let set_seen_blocks: Vec<Block> = fields.iter().map(|_| builder.create_block()).collect();

        // Track compare blocks for sealing
        let mut compare_blocks: Vec<Block> = Vec::new();

        // Linear scan: compare field name against each expected field
        for (i, field) in fields.iter().enumerate() {
            let next_compare = if i + 1 < fields.len() {
                let block = builder.create_block();
                compare_blocks.push(block);
                block
            } else {
                skip_field_block
            };

            // Embed field name pointer as a constant (the string is 'static)
            // Note: field.name is already the effective name (set from Field::effective_name() during FieldCodegenInfo creation)
            let expected_ptr = builder
                .ins()
                .iconst(pointer_type, field.name.as_ptr() as i64);
            let expected_len = builder.ins().iconst(pointer_type, field.name.len() as i64);

            // Call jit_field_matches
            let call_result = builder.ins().call(
                field_matches_ref,
                &[name_ptr, name_len, expected_ptr, expected_len],
            );
            let matches = builder.inst_results(call_result)[0];

            // If matches, jump to field block; otherwise continue to next compare
            let is_match = builder.ins().icmp_imm(IntCC::NotEqual, matches, 0);
            builder
                .ins()
                .brif(is_match, field_blocks[i], &[], next_compare, &[]);

            if i + 1 < fields.len() {
                builder.switch_to_block(next_compare);
            }
        }

        // Skip field block: skip unknown field value
        builder.switch_to_block(skip_field_block);
        // Call skip_value to properly skip the entire value (including nested objects/arrays)
        let call_result =
            builder
                .ins()
                .call_indirect(sig_skip_value_ref, skip_value_fn, &[parser_ptr]);
        let result = builder.inst_results(call_result)[0];
        let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
        builder
            .ins()
            .brif(is_error, error_block, &[], after_field, &[]);

        // Generate field parsing blocks
        for (i, field) in fields.iter().enumerate() {
            builder.switch_to_block(field_blocks[i]);

            let offset_val = builder.ins().iconst(pointer_type, field.offset as i64);

            #[cfg(debug_assertions)]
            eprintln!(
                "[JIT COMPILE] Field '{}' at offset {}",
                field.name, field.offset
            );

            // Determine the target block after successfully writing this field.
            // All fields go through set_seen_blocks to update `fields_seen`.
            let continue_target = set_seen_blocks[i];

            // Duplicate-key handling: if this field was already initialized, drop the old value
            // before writing the new one (JSON "last wins" semantics without leaks).
            let already_seen_mask = builder
                .ins()
                .iconst(types::I64, 1i64 << field.seen_bit_index);
            let current_seen = builder.use_var(fields_seen);
            let already_seen_bits = builder.ins().band(current_seen, already_seen_mask);
            let already_seen = builder
                .ins()
                .icmp_imm(IntCC::NotEqual, already_seen_bits, 0);
            let drop_old_value = builder.create_block();
            let after_drop_old = builder.create_block();
            builder
                .ins()
                .brif(already_seen, drop_old_value, &[], after_drop_old, &[]);

            builder.switch_to_block(drop_old_value);
            let field_ptr_for_drop = builder.ins().iadd(out_ptr, offset_val);
            let field_shape_ptr = builder
                .ins()
                .iconst(pointer_type, field.shape as *const Shape as usize as i64);
            builder
                .ins()
                .call(drop_in_place_ref, &[field_shape_ptr, field_ptr_for_drop]);
            builder.ins().jump(after_drop_old, &[]);
            builder.seal_block(drop_old_value);

            builder.switch_to_block(after_drop_old);
            builder.seal_block(after_drop_old);

            // Handle field based on type
            match field.write_kind {
                WriteKind::NestedStruct(nested_shape) => {
                    // For nested structs, DON'T call next_event first!
                    // The nested deserializer will consume the StructStart itself.
                    let func_ptr = nested_lookup[&(nested_shape as *const Shape)];
                    let func_ptr_val = builder.ins().iconst(pointer_type, func_ptr as i64);

                    // Calculate the nested struct's output pointer
                    let nested_out_ptr = builder.ins().iadd(out_ptr, offset_val);

                    // Call jit_deserialize_nested(ctx_ptr, nested_out_ptr, func_ptr)
                    let call_result = builder.ins().call(
                        deserialize_nested_ref,
                        &[ctx_ptr, nested_out_ptr, func_ptr_val],
                    );
                    let nested_result = builder.inst_results(call_result)[0];

                    // Check if nested deserialization failed
                    let nested_is_error =
                        builder
                            .ins()
                            .icmp_imm(IntCC::SignedLessThan, nested_result, 0);
                    builder
                        .ins()
                        .brif(nested_is_error, error_block, &[], continue_target, &[]);
                }
                WriteKind::Option(option_shape) => {
                    // Option field: peek to check for Null, then consume and handle
                    // Call jit_peek_event(ctx, raw_event_ptr)
                    let call_result = builder
                        .ins()
                        .call(peek_event_ref, &[ctx_ptr, raw_event_ptr]);
                    let result = builder.inst_results(call_result)[0];

                    // Check for error
                    let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
                    let check_null_block = builder.create_block();
                    builder
                        .ins()
                        .brif(is_error, error_block, &[], check_null_block, &[]);

                    builder.switch_to_block(check_null_block);

                    // Check if peeked value is Null (scalar_tag == ScalarTag::Null = 1)
                    let scalar_tag = builder.ins().load(
                        types::I8,
                        MemFlags::trusted(),
                        raw_event_ptr,
                        1, // scalar_tag offset
                    );
                    let is_null = builder.ins().icmp_imm(IntCC::Equal, scalar_tag, 1);

                    let handle_none_block = builder.create_block();
                    let handle_some_block = builder.create_block();
                    builder
                        .ins()
                        .brif(is_null, handle_none_block, &[], handle_some_block, &[]);

                    // Handle None case: consume Null event and init to None
                    builder.switch_to_block(handle_none_block);
                    // Consume the peeked Null event
                    let _consume_result = builder
                        .ins()
                        .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);

                    // Get Option vtable
                    let Def::Option(option_def) = &option_shape.def else {
                        unreachable!();
                    };
                    let init_none_fn_ptr = option_def.vtable.init_none as *const u8;
                    let init_none_fn_val =
                        builder.ins().iconst(pointer_type, init_none_fn_ptr as i64);

                    // Calculate field pointer
                    let field_ptr = builder.ins().iadd(out_ptr, offset_val);

                    // Call jit_option_init_none(field_ptr, init_none_fn)
                    builder
                        .ins()
                        .call(option_init_none_ref, &[field_ptr, init_none_fn_val]);

                    builder.ins().jump(continue_target, &[]);

                    // Handle Some case: deserialize inner value, init to Some
                    builder.switch_to_block(handle_some_block);

                    // Get Option info
                    let Def::Option(option_def) = &option_shape.def else {
                        unreachable!();
                    };
                    let inner_shape = option_def.t;

                    // Determine how to deserialize the inner value
                    let inner_write_kind = WriteKind::from_shape(inner_shape);
                    if inner_write_kind.is_none() {
                        // Inner type not supported in Tier-2, bail
                        builder.ins().jump(error_block, &[]);
                        builder.seal_block(check_null_block);
                        builder.seal_block(handle_some_block);
                        continue;
                    }
                    let inner_write_kind = inner_write_kind.unwrap();

                    // Allocate stack slot for the inner value (max 256 bytes)
                    let value_slot = builder.create_sized_stack_slot(StackSlotData::new(
                        StackSlotKind::ExplicitSlot,
                        256,
                        8,
                    ));
                    let value_ptr = builder.ins().stack_addr(pointer_type, value_slot, 0);
                    let value_offset = builder.ins().iconst(pointer_type, 0);

                    // Zero out the stack slot to avoid uninitialized data
                    let zero_i64 = builder.ins().iconst(types::I64, 0);
                    for offset in (0..256).step_by(8) {
                        builder
                            .ins()
                            .store(MemFlags::trusted(), zero_i64, value_ptr, offset);
                    }

                    // Consume the peeked event and deserialize the value
                    // Use the same deserialization pattern as regular fields
                    let call_result = builder
                        .ins()
                        .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
                    let result = builder.inst_results(call_result)[0];

                    // Check for error
                    let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
                    let write_value_block = builder.create_block();
                    builder
                        .ins()
                        .brif(is_error, error_block, &[], write_value_block, &[]);

                    builder.switch_to_block(write_value_block);

                    // Validate scalar tag before reading payload to prevent type confusion
                    let actual_tag = builder.ins().load(
                        types::I8,
                        MemFlags::trusted(),
                        raw_event_ptr,
                        helpers::RAW_EVENT_SCALAR_TAG_OFFSET as i32,
                    );

                    let validated_block = if inner_write_kind.is_numeric() {
                        // For numeric types, accept any of I64, U64, F64
                        let validated_block = builder.create_block();
                        let is_i64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::I64 as i64,
                        );
                        let check_u64 = builder.create_block();
                        builder
                            .ins()
                            .brif(is_i64, validated_block, &[], check_u64, &[]);

                        builder.switch_to_block(check_u64);
                        let is_u64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::U64 as i64,
                        );
                        let check_f64 = builder.create_block();
                        builder
                            .ins()
                            .brif(is_u64, validated_block, &[], check_f64, &[]);

                        builder.switch_to_block(check_f64);
                        let is_f64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::F64 as i64,
                        );
                        builder
                            .ins()
                            .brif(is_f64, validated_block, &[], error_block, &[]);

                        builder.seal_block(check_u64);
                        builder.seal_block(check_f64);
                        builder.switch_to_block(validated_block);
                        Some(validated_block)
                    } else if let Some(expected_tag) = inner_write_kind.expected_non_numeric_tag() {
                        // For bool/string, require exact match
                        let validated_block = builder.create_block();
                        let tag_matches =
                            builder
                                .ins()
                                .icmp_imm(IntCC::Equal, actual_tag, expected_tag as i64);
                        builder
                            .ins()
                            .brif(tag_matches, validated_block, &[], error_block, &[]);
                        builder.switch_to_block(validated_block);
                        Some(validated_block)
                    } else {
                        None
                    };

                    // Get the payload pointer
                    let payload_ptr = builder
                        .ins()
                        .iadd_imm(raw_event_ptr, helpers::RAW_EVENT_PAYLOAD_OFFSET as i64);

                    // Deserialize based on inner type and write to stack slot
                    match inner_write_kind {
                        WriteKind::I8 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_i8_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::I16 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_i16 = builder.ins().ireduce(types::I16, value);
                            builder
                                .ins()
                                .call(write_i16_ref, &[value_ptr, value_offset, value_i16]);
                        }
                        WriteKind::I32 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_i32 = builder.ins().ireduce(types::I32, value);
                            builder
                                .ins()
                                .call(write_i32_ref, &[value_ptr, value_offset, value_i32]);
                        }
                        WriteKind::I64 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_i64_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::U8 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_u8_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::U16 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_u16 = builder.ins().ireduce(types::I16, value);
                            builder
                                .ins()
                                .call(write_u16_ref, &[value_ptr, value_offset, value_u16]);
                        }
                        WriteKind::U32 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_u32 = builder.ins().ireduce(types::I32, value);
                            builder
                                .ins()
                                .call(write_u32_ref, &[value_ptr, value_offset, value_u32]);
                        }
                        WriteKind::U64 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_u64_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::F64 | WriteKind::F32 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::F64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_f64_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::Bool => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_bool_ref, &[value_ptr, value_offset, value]);
                        }
                        WriteKind::String => {
                            let str_ptr = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                0,
                            );
                            let str_len = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                8,
                            );
                            let str_capacity = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                16,
                            );
                            let str_owned =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 24);
                            builder.ins().call(
                                write_string_ref,
                                &[
                                    value_ptr,
                                    value_offset,
                                    str_ptr,
                                    str_len,
                                    str_capacity,
                                    str_owned,
                                ],
                            );
                        }
                        WriteKind::NestedStruct(_) | WriteKind::Option(_) | WriteKind::Vec(_) => {
                            // Nested structs, Options, and Vecs in Options not yet supported
                            // TODO: implement nested struct deserialization for Option<NestedStruct>
                            builder.ins().jump(error_block, &[]);
                            builder.seal_block(check_null_block);
                            builder.seal_block(handle_some_block);
                            builder.seal_block(write_value_block);
                            if let Some(vb) = validated_block {
                                builder.seal_block(vb);
                            }
                            continue;
                        }
                    }

                    // Get init_some function
                    let init_some_fn_ptr = option_def.vtable.init_some as *const u8;
                    let init_some_fn_val =
                        builder.ins().iconst(pointer_type, init_some_fn_ptr as i64);

                    // Calculate field pointer
                    let field_ptr = builder.ins().iadd(out_ptr, offset_val);

                    // Call jit_option_init_some_from_value(field_ptr, value_ptr, init_some_fn)
                    builder.ins().call(
                        option_init_some_from_value_ref,
                        &[field_ptr, value_ptr, init_some_fn_val],
                    );

                    builder.ins().jump(continue_target, &[]);
                    builder.seal_block(check_null_block);
                    builder.seal_block(handle_none_block);
                    builder.seal_block(handle_some_block);
                    builder.seal_block(write_value_block);
                    if let Some(vb) = validated_block {
                        builder.seal_block(vb);
                    }
                }
                WriteKind::Vec(vec_shape) => {
                    // Vec field: call jit_deserialize_list_by_shape which handles
                    // nested Vecs recursively
                    let vec_shape_ptr = vec_shape as *const Shape;
                    let vec_shape_val = builder.ins().iconst(pointer_type, vec_shape_ptr as i64);

                    // Calculate the field pointer
                    let field_ptr = builder.ins().iadd(out_ptr, offset_val);

                    // Check if Vec element is a struct and get its deserializer
                    let elem_deserializer_val = if let Def::List(list_def) = &vec_shape.def {
                        let elem_shape = list_def.t;
                        if let FacetType::User(UserType::Struct(_)) = &elem_shape.ty {
                            // Get the pre-compiled deserializer for this struct type
                            if let Some(&func_ptr) =
                                nested_lookup.get(&(elem_shape as *const Shape))
                            {
                                builder.ins().iconst(pointer_type, func_ptr as i64)
                            } else {
                                // Struct element but no deserializer - will fail in helper
                                builder.ins().iconst(pointer_type, 0)
                            }
                        } else {
                            // Not a struct element
                            builder.ins().iconst(pointer_type, 0)
                        }
                    } else {
                        builder.ins().iconst(pointer_type, 0)
                    };

                    // Call jit_deserialize_list_by_shape(ctx_ptr, field_ptr, vec_shape, elem_deserializer)
                    let call_result = builder.ins().call(
                        deserialize_list_by_shape_ref,
                        &[ctx_ptr, field_ptr, vec_shape_val, elem_deserializer_val],
                    );
                    let vec_result = builder.inst_results(call_result)[0];

                    // Check if deserialization failed
                    let vec_is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, vec_result, 0);
                    builder
                        .ins()
                        .brif(vec_is_error, error_block, &[], continue_target, &[]);
                }
                _ => {
                    // For scalars/strings, call next_event to get the value
                    // Call jit_next_event (uses JitContext for peek buffer)
                    let call_result = builder
                        .ins()
                        .call(next_event_ref, &[ctx_ptr, raw_event_ptr]);
                    let result = builder.inst_results(call_result)[0];

                    // Check for error
                    let is_error = builder.ins().icmp_imm(IntCC::SignedLessThan, result, 0);
                    let write_value_block = builder.create_block();
                    builder
                        .ins()
                        .brif(is_error, error_block, &[], write_value_block, &[]);

                    builder.switch_to_block(write_value_block);

                    // Validate scalar tag before reading payload to prevent type confusion
                    // (e.g., reading a string pointer as a u64 value)
                    let actual_tag = builder.ins().load(
                        types::I8,
                        MemFlags::trusted(),
                        raw_event_ptr,
                        helpers::RAW_EVENT_SCALAR_TAG_OFFSET as i32,
                    );

                    let validated_block = if field.write_kind.is_numeric() {
                        // For numeric types, accept any of I64, U64, F64
                        let validated_block = builder.create_block();
                        let is_i64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::I64 as i64,
                        );
                        let check_u64 = builder.create_block();
                        builder
                            .ins()
                            .brif(is_i64, validated_block, &[], check_u64, &[]);

                        builder.switch_to_block(check_u64);
                        let is_u64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::U64 as i64,
                        );
                        let check_f64 = builder.create_block();
                        builder
                            .ins()
                            .brif(is_u64, validated_block, &[], check_f64, &[]);

                        builder.switch_to_block(check_f64);
                        let is_f64 = builder.ins().icmp_imm(
                            IntCC::Equal,
                            actual_tag,
                            helpers::ScalarTag::F64 as i64,
                        );
                        builder
                            .ins()
                            .brif(is_f64, validated_block, &[], error_block, &[]);

                        builder.seal_block(check_u64);
                        builder.seal_block(check_f64);
                        builder.switch_to_block(validated_block);
                        Some(validated_block)
                    } else if let Some(expected_tag) = field.write_kind.expected_non_numeric_tag() {
                        // For bool/string, require exact match
                        let validated_block = builder.create_block();
                        let tag_matches =
                            builder
                                .ins()
                                .icmp_imm(IntCC::Equal, actual_tag, expected_tag as i64);
                        builder
                            .ins()
                            .brif(tag_matches, validated_block, &[], error_block, &[]);
                        builder.switch_to_block(validated_block);
                        Some(validated_block)
                    } else {
                        None
                    };

                    // Get the payload pointer
                    let payload_ptr = builder
                        .ins()
                        .iadd_imm(raw_event_ptr, helpers::RAW_EVENT_PAYLOAD_OFFSET as i64);

                    // Write the value based on field type
                    match field.write_kind {
                        WriteKind::I8 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_i8_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::I16 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_i16 = builder.ins().ireduce(types::I16, value);
                            builder
                                .ins()
                                .call(write_i16_ref, &[out_ptr, offset_val, value_i16]);
                        }
                        WriteKind::I32 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_i32 = builder.ins().ireduce(types::I32, value);
                            builder
                                .ins()
                                .call(write_i32_ref, &[out_ptr, offset_val, value_i32]);
                        }
                        WriteKind::I64 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_i64_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::U8 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_u8_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::U16 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_u16 = builder.ins().ireduce(types::I16, value);
                            builder
                                .ins()
                                .call(write_u16_ref, &[out_ptr, offset_val, value_u16]);
                        }
                        WriteKind::U32 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            let value_u32 = builder.ins().ireduce(types::I32, value);
                            builder
                                .ins()
                                .call(write_u32_ref, &[out_ptr, offset_val, value_u32]);
                        }
                        WriteKind::U64 => {
                            let value =
                                builder
                                    .ins()
                                    .load(types::I64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_u64_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::F64 | WriteKind::F32 => {
                            // Load f64 value from scalar payload
                            let value =
                                builder
                                    .ins()
                                    .load(types::F64, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_f64_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::Bool => {
                            // Load bool value from scalar payload (as u8)
                            let value =
                                builder
                                    .ins()
                                    .load(types::I8, MemFlags::trusted(), payload_ptr, 0);
                            builder
                                .ins()
                                .call(write_bool_ref, &[out_ptr, offset_val, value]);
                        }
                        WriteKind::String => {
                            // Load string payload: ptr, len, capacity, owned
                            // StringPayload layout: ptr (0), len (8), capacity (16), owned (24)
                            let str_ptr = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                0,
                            );
                            let str_len = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                8, // offset to len field
                            );
                            let str_capacity = builder.ins().load(
                                pointer_type,
                                MemFlags::trusted(),
                                payload_ptr,
                                16, // offset to capacity field
                            );
                            let str_owned = builder.ins().load(
                                types::I8,
                                MemFlags::trusted(),
                                payload_ptr,
                                24, // offset to owned field
                            );
                            builder.ins().call(
                                write_string_ref,
                                &[
                                    out_ptr,
                                    offset_val,
                                    str_ptr,
                                    str_len,
                                    str_capacity,
                                    str_owned,
                                ],
                            );
                        }
                        WriteKind::NestedStruct(_) => {
                            unreachable!("Nested struct should be handled in outer match");
                        }
                        WriteKind::Option(_) => {
                            unreachable!("Option should be handled in outer match");
                        }
                        WriteKind::Vec(_) => {
                            unreachable!("Vec should be handled in outer match");
                        }
                    }

                    builder.ins().jump(continue_target, &[]);
                    builder.seal_block(write_value_block);
                    if let Some(vb) = validated_block {
                        builder.seal_block(vb);
                    }
                }
            }
        }

        // Generate set_seen_blocks: mark field initialized, then route to required-bit update.
        for (i, field) in fields.iter().enumerate() {
            let set_seen_block = set_seen_blocks[i];
            builder.switch_to_block(set_seen_block);
            let current = builder.use_var(fields_seen);
            let bit = builder
                .ins()
                .iconst(types::I64, 1i64 << field.seen_bit_index);
            let updated = builder.ins().bor(current, bit);
            builder.def_var(fields_seen, updated);
            if let Some(set_bit_block) = set_bit_blocks[i] {
                builder.ins().jump(set_bit_block, &[]);
            } else {
                builder.ins().jump(after_field, &[]);
            }
        }

        // Generate set_bit_blocks: OR in required-field bit and jump to after_field.
        for (i, field) in fields.iter().enumerate() {
            if let Some(bit_index) = field.required_bit_index {
                let set_bit_block = set_bit_blocks[i].unwrap();
                builder.switch_to_block(set_bit_block);

                // Load current bitmask
                let current = builder.use_var(required_fields_seen);

                // OR in the bit for this field
                let bit = builder.ins().iconst(types::I64, 1i64 << bit_index);
                let updated = builder.ins().bor(current, bit);

                // Store back
                builder.def_var(required_fields_seen, updated);

                // Jump to after_field
                builder.ins().jump(after_field, &[]);
            }
        }

        // After field: loop back
        builder.switch_to_block(after_field);
        builder.ins().jump(field_loop, &[]);

        // Success block: validate that all required fields have been seen
        builder.switch_to_block(success_block);

        if required_fields_mask != 0 {
            // Check if all required fields were provided
            let seen = builder.use_var(required_fields_seen);
            let expected = builder
                .ins()
                .iconst(types::I64, required_fields_mask as i64);
            let all_seen = builder.ins().icmp(IntCC::Equal, seen, expected);

            // Create a block for the final success return
            let return_success = builder.create_block();
            let missing_field_error = builder.create_block();

            builder
                .ins()
                .brif(all_seen, return_success, &[], missing_field_error, &[]);

            // Missing field error: store seen mask and return ERR_MISSING_REQUIRED_FIELD
            builder.switch_to_block(missing_field_error);
            // Store the fields_seen mask to ctx for cleanup of partially-initialized struct
            let seen_for_error = builder.use_var(fields_seen);
            builder.ins().store(
                MemFlags::trusted(),
                seen_for_error,
                ctx_ptr,
                helpers::JIT_CONTEXT_FIELDS_SEEN_OFFSET as i32,
            );
            let err_missing = builder
                .ins()
                .iconst(types::I32, helpers::ERR_MISSING_REQUIRED_FIELD as i64);
            builder.ins().return_(&[err_missing]);

            // Final success return
            builder.switch_to_block(return_success);
            let zero = builder.ins().iconst(types::I32, 0);
            builder.ins().return_(&[zero]);

            builder.seal_block(return_success);
            builder.seal_block(missing_field_error);
        } else {
            // No required fields - just return success
            let zero = builder.ins().iconst(types::I32, 0);
            builder.ins().return_(&[zero]);
        }

        // Error block: store seen mask for cleanup and return error
        builder.switch_to_block(error_block);
        // Store the fields_seen mask to ctx for cleanup of partially-initialized struct
        let seen_for_cleanup = builder.use_var(fields_seen);
        builder.ins().store(
            MemFlags::trusted(),
            seen_for_cleanup,
            ctx_ptr,
            helpers::JIT_CONTEXT_FIELDS_SEEN_OFFSET as i32,
        );
        let err = builder.ins().iconst(types::I32, -1);
        builder.ins().return_(&[err]);

        // Seal all blocks
        builder.seal_block(check_struct_start);
        builder.seal_block(field_loop);
        builder.seal_block(check_event_tag);
        builder.seal_block(check_field_key);
        builder.seal_block(process_field);
        builder.seal_block(skip_field_block);
        builder.seal_block(after_field);
        builder.seal_block(success_block);
        builder.seal_block(error_block);
        for block in &field_blocks {
            builder.seal_block(*block);
        }
        for block in &compare_blocks {
            builder.seal_block(*block);
        }
        for block in set_bit_blocks.iter().flatten() {
            builder.seal_block(*block);
        }
        for block in &set_seen_blocks {
            builder.seal_block(*block);
        }

        builder.finalize();
    }

    module.define_function(func_id, &mut ctx).ok()?;

    Some((func_id, all_nested_modules))
}

/// Field info for code generation.
#[allow(dead_code)]
struct FieldCodegenInfo {
    /// Field name (for matching)
    name: &'static str,
    /// Byte offset in the struct
    offset: usize,
    /// Field shape metadata (for duplicate drop-in-place)
    shape: &'static Shape,
    /// Type of write operation needed
    write_kind: WriteKind,
    /// Index in the field-seen bitmask (matches real struct field index)
    seen_bit_index: usize,
    /// Index in the required-field bitmask (None if optional)
    required_bit_index: Option<usize>,
}

/// What kind of write operation is needed for a field.
#[allow(dead_code)]
enum WriteKind {
    U8,
    U16,
    U32,
    U64,
    I8,
    I16,
    I32,
    I64,
    F32,
    F64,
    Bool,
    String,
    /// Nested struct that needs to be deserialized via a separate compiled function
    NestedStruct(&'static Shape),
    /// `Option<T>` - shape is the Option shape (includes inner type)
    Option(&'static Shape),
    /// `Vec<T>` - shape is the Vec shape (includes element type)
    Vec(&'static Shape),
}

#[allow(dead_code)]
impl WriteKind {
    /// Returns whether this is a numeric type that accepts any numeric scalar tag.
    /// For numeric types, we accept I64, U64, and F64 since:
    /// - JSON doesn't distinguish signed/unsigned integers
    /// - JSON integers can be coerced to floats (e.g., `1` for f64)
    const fn is_numeric(&self) -> bool {
        matches!(
            self,
            WriteKind::I8
                | WriteKind::I16
                | WriteKind::I32
                | WriteKind::I64
                | WriteKind::U8
                | WriteKind::U16
                | WriteKind::U32
                | WriteKind::U64
                | WriteKind::F32
                | WriteKind::F64
        )
    }

    /// Returns the expected ScalarTag for non-numeric scalar types.
    /// Returns None for numeric types (handled separately) and non-scalar types.
    const fn expected_non_numeric_tag(&self) -> Option<u8> {
        use helpers::ScalarTag;
        match self {
            WriteKind::Bool => Some(ScalarTag::Bool as u8),
            WriteKind::String => Some(ScalarTag::Str as u8),
            // Numeric types are handled separately, non-scalar types don't need validation
            _ => None,
        }
    }

    fn from_shape(shape: &'static Shape) -> Option<Self> {
        use facet_core::ScalarType;

        // Check for scalar types via shape.scalar_type()
        if let Some(scalar_type) = shape.scalar_type() {
            return match scalar_type {
                ScalarType::Bool => Some(WriteKind::Bool),
                ScalarType::U8 => Some(WriteKind::U8),
                ScalarType::U16 => Some(WriteKind::U16),
                ScalarType::U32 => Some(WriteKind::U32),
                ScalarType::U64 => Some(WriteKind::U64),
                ScalarType::I8 => Some(WriteKind::I8),
                ScalarType::I16 => Some(WriteKind::I16),
                ScalarType::I32 => Some(WriteKind::I32),
                ScalarType::I64 => Some(WriteKind::I64),
                ScalarType::F32 => Some(WriteKind::F32),
                ScalarType::F64 => Some(WriteKind::F64),
                ScalarType::String => Some(WriteKind::String),
                _ => None, // Other scalar types not yet supported
            };
        }

        // Check by Def (Option, Vec, nested structs)
        match &shape.def {
            Def::Option(_option_def) => {
                // For now, support Option<T> where T is JIT-compatible
                // TODO: Could recursively check inner type compatibility
                Some(WriteKind::Option(shape))
            }
            Def::List(list_def) => {
                // Check if we can handle the element type
                if is_vec_element_supported(list_def.t) {
                    Some(WriteKind::Vec(shape))
                } else {
                    None
                }
            }
            _ => {
                // Check for nested struct
                if let FacetType::User(UserType::Struct(_)) = &shape.ty {
                    // Recursively check if the nested struct is JIT-compatible
                    if is_jit_compatible(shape) {
                        return Some(WriteKind::NestedStruct(shape));
                    }
                }
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_jit_compatibility_primitives() {
        // Test that primitive types are not JIT-compatible (they're not structs)
        assert!(!is_jit_compatible(i64::SHAPE));
        assert!(!is_jit_compatible(String::SHAPE));
        assert!(!is_jit_compatible(bool::SHAPE));
    }

    #[test]
    fn test_vec_element_supported() {
        // Direct tests for is_vec_element_supported
        assert!(is_vec_element_supported(i64::SHAPE));
        assert!(is_vec_element_supported(f64::SHAPE));
        assert!(is_vec_element_supported(bool::SHAPE));
        assert!(is_vec_element_supported(String::SHAPE));

        // Nested Vec<f64>
        assert!(is_vec_element_supported(<Vec<f64>>::SHAPE));

        // Deeply nested Vec<Vec<f64>>
        assert!(is_vec_element_supported(<Vec<Vec<f64>>>::SHAPE));

        // Triple nested Vec<Vec<Vec<f64>>>
        assert!(is_vec_element_supported(<Vec<Vec<Vec<f64>>>>::SHAPE));
    }
}