facet-format 0.42.0

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
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
extern crate alloc;

use alloc::borrow::Cow;
use alloc::format;
use alloc::string::String;
use core::fmt;

use facet_core::{
    Def, Facet, KnownPointer, NumericType, PrimitiveType, StructKind, Type, UserType,
};
pub use facet_path::{Path, PathStep};
use facet_reflect::{HeapValue, Partial, ReflectError, Resolution, is_spanned_shape};

use crate::{
    ContainerKind, FieldLocationHint, FormatParser, ParseEvent, ScalarTypeHint, ScalarValue,
};

/// Result of variant lookup for HTML/XML elements.
enum VariantMatch {
    /// Direct match: a variant with matching rename attribute.
    Direct(usize),
    /// Custom element fallback: a variant with `html::custom_element` or `xml::custom_element`.
    CustomElement(usize),
}

/// Generic deserializer that drives a format-specific parser directly into `Partial`.
///
/// The const generic `BORROW` controls whether string data can be borrowed:
/// - `BORROW=true`: strings without escapes are borrowed from input
/// - `BORROW=false`: all strings are owned
pub struct FormatDeserializer<'input, const BORROW: bool, P> {
    parser: P,
    /// The span of the most recently consumed event (for error reporting).
    last_span: Option<facet_reflect::Span>,
    /// Current path through the type structure (for error reporting).
    current_path: Path,
    _marker: core::marker::PhantomData<&'input ()>,
}

impl<'input, P> FormatDeserializer<'input, true, P> {
    /// Create a new deserializer that can borrow strings from input.
    pub const fn new(parser: P) -> Self {
        Self {
            parser,
            last_span: None,
            current_path: Path::new(),
            _marker: core::marker::PhantomData,
        }
    }
}

impl<'input, P> FormatDeserializer<'input, false, P> {
    /// Create a new deserializer that produces owned strings.
    pub const fn new_owned(parser: P) -> Self {
        Self {
            parser,
            last_span: None,
            current_path: Path::new(),
            _marker: core::marker::PhantomData,
        }
    }
}

impl<'input, const BORROW: bool, P> FormatDeserializer<'input, BORROW, P> {
    /// Consume the facade and return the underlying parser.
    pub fn into_inner(self) -> P {
        self.parser
    }

    /// Borrow the inner parser mutably.
    pub fn parser_mut(&mut self) -> &mut P {
        &mut self.parser
    }
}

impl<'input, P> FormatDeserializer<'input, true, P>
where
    P: FormatParser<'input>,
{
    /// Deserialize the next value in the stream into `T`, allowing borrowed strings.
    pub fn deserialize<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'input>,
    {
        let wip: Partial<'input, true> =
            Partial::alloc::<T>().map_err(DeserializeError::reflect)?;
        let partial = self.deserialize_into(wip)?;
        let heap_value: HeapValue<'input, true> =
            partial.build().map_err(DeserializeError::reflect)?;
        heap_value
            .materialize::<T>()
            .map_err(DeserializeError::reflect)
    }

    /// Deserialize the next value in the stream into `T` (for backward compatibility).
    pub fn deserialize_root<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'input>,
    {
        self.deserialize()
    }

    /// Deserialize using deferred mode, allowing interleaved field initialization.
    ///
    /// This is required for formats like TOML that allow table reopening, where
    /// fields of a nested struct may be set, then fields of a sibling, then more
    /// fields of the original struct.
    pub fn deserialize_deferred<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'input>,
    {
        let wip: Partial<'input, true> =
            Partial::alloc::<T>().map_err(DeserializeError::reflect)?;
        let wip = wip
            .begin_deferred(Resolution::new())
            .map_err(DeserializeError::reflect)?;
        let partial = self.deserialize_into(wip)?;
        let partial = partial
            .finish_deferred()
            .map_err(DeserializeError::reflect)?;
        let heap_value: HeapValue<'input, true> =
            partial.build().map_err(DeserializeError::reflect)?;
        heap_value
            .materialize::<T>()
            .map_err(DeserializeError::reflect)
    }
}

impl<'input, P> FormatDeserializer<'input, false, P>
where
    P: FormatParser<'input>,
{
    /// Deserialize the next value in the stream into `T`, using owned strings.
    pub fn deserialize<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'static>,
    {
        // SAFETY: alloc_owned produces Partial<'static, false>, but our deserializer
        // expects 'input. Since BORROW=false means we never borrow from input anyway,
        // this is safe. We also transmute the HeapValue back to 'static before materializing.
        #[allow(unsafe_code)]
        let wip: Partial<'input, false> = unsafe {
            core::mem::transmute::<Partial<'static, false>, Partial<'input, false>>(
                Partial::alloc_owned::<T>().map_err(DeserializeError::reflect)?,
            )
        };
        let partial = self.deserialize_into(wip)?;
        let heap_value: HeapValue<'input, false> =
            partial.build().map_err(DeserializeError::reflect)?;

        // SAFETY: HeapValue<'input, false> contains no borrowed data because BORROW=false.
        // The transmute only changes the phantom lifetime marker.
        #[allow(unsafe_code)]
        let heap_value: HeapValue<'static, false> = unsafe {
            core::mem::transmute::<HeapValue<'input, false>, HeapValue<'static, false>>(heap_value)
        };

        heap_value
            .materialize::<T>()
            .map_err(DeserializeError::reflect)
    }

    /// Deserialize the next value in the stream into `T` (for backward compatibility).
    pub fn deserialize_root<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'static>,
    {
        self.deserialize()
    }

    /// Deserialize using deferred mode, allowing interleaved field initialization.
    ///
    /// This is required for formats like TOML that allow table reopening, where
    /// fields of a nested struct may be set, then fields of a sibling, then more
    /// fields of the original struct.
    pub fn deserialize_deferred<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
    where
        T: Facet<'static>,
    {
        // SAFETY: alloc_owned produces Partial<'static, false>, but our deserializer
        // expects 'input. Since BORROW=false means we never borrow from input anyway,
        // this is safe. We also transmute the HeapValue back to 'static before materializing.
        #[allow(unsafe_code)]
        let wip: Partial<'input, false> = unsafe {
            core::mem::transmute::<Partial<'static, false>, Partial<'input, false>>(
                Partial::alloc_owned::<T>().map_err(DeserializeError::reflect)?,
            )
        };
        let wip = wip
            .begin_deferred(Resolution::new())
            .map_err(DeserializeError::reflect)?;
        let partial = self.deserialize_into(wip)?;
        let partial = partial
            .finish_deferred()
            .map_err(DeserializeError::reflect)?;
        let heap_value: HeapValue<'input, false> =
            partial.build().map_err(DeserializeError::reflect)?;

        // SAFETY: HeapValue<'input, false> contains no borrowed data because BORROW=false.
        // The transmute only changes the phantom lifetime marker.
        #[allow(unsafe_code)]
        let heap_value: HeapValue<'static, false> = unsafe {
            core::mem::transmute::<HeapValue<'input, false>, HeapValue<'static, false>>(heap_value)
        };

        heap_value
            .materialize::<T>()
            .map_err(DeserializeError::reflect)
    }
}

impl<'input, const BORROW: bool, P> FormatDeserializer<'input, BORROW, P>
where
    P: FormatParser<'input>,
{
    /// Read the next event, returning an error if EOF is reached.
    #[inline]
    fn expect_event(
        &mut self,
        expected: &'static str,
    ) -> Result<ParseEvent<'input>, DeserializeError<P::Error>> {
        let event = self
            .parser
            .next_event()
            .map_err(DeserializeError::Parser)?
            .ok_or(DeserializeError::UnexpectedEof { expected })?;
        // Capture the span of the consumed event for error reporting
        self.last_span = self.parser.current_span();
        Ok(event)
    }

    /// Peek at the next event, returning an error if EOF is reached.
    #[inline]
    fn expect_peek(
        &mut self,
        expected: &'static str,
    ) -> Result<ParseEvent<'input>, DeserializeError<P::Error>> {
        self.parser
            .peek_event()
            .map_err(DeserializeError::Parser)?
            .ok_or(DeserializeError::UnexpectedEof { expected })
    }

    /// Push a step onto the current path (for error reporting).
    #[inline]
    fn push_path(&mut self, step: PathStep) {
        self.current_path.push(step);
    }

    /// Pop the last step from the current path.
    #[inline]
    fn pop_path(&mut self) {
        self.current_path.pop();
    }

    /// Get a clone of the current path (for attaching to errors).
    #[inline]
    fn path_clone(&self) -> Path {
        self.current_path.clone()
    }

    /// Main deserialization entry point - deserialize into a Partial.
    pub fn deserialize_into(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // Check for raw capture type (e.g., RawJson)
        // Raw capture types are tuple structs with a single Cow<str> field
        // If capture_raw returns None (e.g., streaming mode), fall through
        // and try normal deserialization (which will likely fail with a helpful error)
        if self.parser.raw_capture_shape() == Some(shape)
            && let Some(raw) = self
                .parser
                .capture_raw()
                .map_err(DeserializeError::Parser)?
        {
            // The raw type is a tuple struct like RawJson(Cow<str>)
            // Access field 0 (the Cow<str>) and set it
            wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
            wip = self.set_string_value(wip, Cow::Borrowed(raw))?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Check for container-level proxy
        let (wip_returned, has_proxy) = wip
            .begin_custom_deserialization_from_shape()
            .map_err(DeserializeError::reflect)?;
        wip = wip_returned;
        if has_proxy {
            wip = self.deserialize_into(wip)?;
            return wip.end().map_err(DeserializeError::reflect);
        }

        // Check for field-level proxy (opaque types with proxy attribute)
        if wip
            .parent_field()
            .and_then(|field| field.proxy_convert_in_fn())
            .is_some()
        {
            wip = wip
                .begin_custom_deserialization()
                .map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Check Def first for Option
        if matches!(&shape.def, Def::Option(_)) {
            return self.deserialize_option(wip);
        }

        // Check Def for Result - treat it as a 2-variant enum
        if matches!(&shape.def, Def::Result(_)) {
            return self.deserialize_result_as_enum(wip);
        }

        // Priority 1: Check for builder_shape (immutable collections like Bytes -> BytesMut)
        if shape.builder_shape.is_some() {
            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Priority 2: Check for smart pointers (Box, Arc, Rc)
        if matches!(&shape.def, Def::Pointer(_)) {
            return self.deserialize_pointer(wip);
        }

        // Priority 3: Check for .inner (transparent wrappers like NonZero)
        // Collections (List/Map/Set/Array) have .inner for variance but shouldn't use this path
        // Opaque scalars (like ULID) may have .inner for documentation but should NOT be
        // deserialized as transparent wrappers - they use hint_opaque_scalar instead
        let is_opaque_scalar =
            matches!(shape.def, Def::Scalar) && matches!(shape.ty, Type::User(UserType::Opaque));
        if shape.inner.is_some()
            && !is_opaque_scalar
            && !matches!(
                &shape.def,
                Def::List(_) | Def::Map(_) | Def::Set(_) | Def::Array(_)
            )
        {
            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Priority 4: Check for metadata-annotated types (like Spanned<T>)
        if is_spanned_shape(shape) {
            return self.deserialize_spanned(wip);
        }

        // Priority 5: Check the Type for structs and enums
        match &shape.ty {
            Type::User(UserType::Struct(struct_def)) => {
                if matches!(struct_def.kind, StructKind::Tuple | StructKind::TupleStruct) {
                    return self.deserialize_tuple(wip);
                }
                return self.deserialize_struct(wip);
            }
            Type::User(UserType::Enum(_)) => return self.deserialize_enum(wip),
            _ => {}
        }

        // Priority 6: Check Def for containers and scalars
        match &shape.def {
            Def::Scalar => self.deserialize_scalar(wip),
            Def::List(_) => self.deserialize_list(wip),
            Def::Map(_) => self.deserialize_map(wip),
            Def::Array(_) => self.deserialize_array(wip),
            Def::Set(_) => self.deserialize_set(wip),
            Def::DynamicValue(_) => self.deserialize_dynamic_value(wip),
            _ => Err(DeserializeError::Unsupported(format!(
                "unsupported shape def: {:?}",
                shape.def
            ))),
        }
    }

    fn deserialize_option(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Hint to non-self-describing parsers that an Option is expected
        self.parser.hint_option();

        let event = self.expect_peek("value for option")?;

        if matches!(event, ParseEvent::Scalar(ScalarValue::Null)) {
            // Consume the null
            let _ = self.expect_event("null")?;
            // Set to None (default)
            wip = wip.set_default().map_err(DeserializeError::reflect)?;
        } else {
            // Some(value)
            wip = wip.begin_some().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }
        Ok(wip)
    }

    fn deserialize_result_as_enum(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::StructKind;

        // Hint to non-self-describing parsers that a Result enum is expected
        // Result is encoded as a 2-variant enum: Ok (index 0) and Err (index 1)
        let variant_hints: Vec<crate::EnumVariantHint> = vec![
            crate::EnumVariantHint {
                name: "Ok",
                kind: StructKind::TupleStruct,
                field_count: 1,
            },
            crate::EnumVariantHint {
                name: "Err",
                kind: StructKind::TupleStruct,
                field_count: 1,
            },
        ];
        self.parser.hint_enum(&variant_hints);

        // Read the StructStart emitted by the parser after hint_enum
        let event = self.expect_event("struct start for Result")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start for Result variant",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Read the FieldKey with the variant name ("Ok" or "Err")
        let key_event = self.expect_event("variant key for Result")?;
        let variant_name = match key_event {
            ParseEvent::FieldKey(key) => key.name,
            other => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "field key with variant name",
                    got: format!("{other:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        // Select the appropriate variant and deserialize its content
        if variant_name == "Ok" {
            wip = wip.begin_ok().map_err(DeserializeError::reflect)?;
        } else if variant_name == "Err" {
            wip = wip.begin_err().map_err(DeserializeError::reflect)?;
        } else {
            return Err(DeserializeError::TypeMismatch {
                expected: "Ok or Err variant",
                got: alloc::format!("variant '{}'", variant_name),
                span: self.last_span,
                path: None,
            });
        }

        // Deserialize the variant's value (newtype pattern - single field)
        wip = self.deserialize_into(wip)?;
        wip = wip.end().map_err(DeserializeError::reflect)?;

        // Consume StructEnd
        let end_event = self.expect_event("struct end for Result")?;
        if !matches!(end_event, ParseEvent::StructEnd) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct end for Result variant",
                got: format!("{end_event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        Ok(wip)
    }

    fn deserialize_pointer(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::KnownPointer;

        let shape = wip.shape();
        let is_cow = if let Def::Pointer(ptr_def) = shape.def {
            matches!(ptr_def.known, Some(KnownPointer::Cow))
        } else {
            false
        };

        if is_cow {
            // Cow<str> - handle specially to preserve borrowing
            if let Def::Pointer(ptr_def) = shape.def
                && let Some(pointee) = ptr_def.pointee()
                && pointee.type_identifier == "str"
            {
                // Hint to non-self-describing parsers that a string is expected
                self.parser.hint_scalar_type(ScalarTypeHint::String);
                let event = self.expect_event("string for Cow<str>")?;
                match event {
                    ParseEvent::Scalar(ScalarValue::Str(s))
                    | ParseEvent::Scalar(ScalarValue::StringlyTyped(s)) => {
                        // Pass through the Cow as-is to preserve borrowing
                        wip = wip.set(s).map_err(DeserializeError::reflect)?;
                        return Ok(wip);
                    }
                    _ => {
                        return Err(DeserializeError::TypeMismatch {
                            expected: "string for Cow<str>",
                            got: format!("{event:?}"),
                            span: self.last_span,
                            path: None,
                        });
                    }
                }
            }
            // Cow<[u8]> - handle specially to preserve borrowing
            if let Def::Pointer(ptr_def) = shape.def
                && let Some(pointee) = ptr_def.pointee()
                && let Def::Slice(slice_def) = pointee.def
                && slice_def.t.type_identifier == "u8"
            {
                // Hint to non-self-describing parsers that bytes are expected
                self.parser.hint_scalar_type(ScalarTypeHint::Bytes);
                let event = self.expect_event("bytes for Cow<[u8]>")?;
                if let ParseEvent::Scalar(ScalarValue::Bytes(b)) = event {
                    // Pass through the Cow as-is to preserve borrowing
                    wip = wip.set(b).map_err(DeserializeError::reflect)?;
                    return Ok(wip);
                } else {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "bytes for Cow<[u8]>",
                        got: format!("{event:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
            // Other Cow types - use begin_inner
            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // &str - handle specially for zero-copy borrowing
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
            && ptr_def
                .pointee()
                .is_some_and(|p| p.type_identifier == "str")
        {
            // Hint to non-self-describing parsers that a string is expected
            self.parser.hint_scalar_type(ScalarTypeHint::String);
            let event = self.expect_event("string for &str")?;
            match event {
                ParseEvent::Scalar(ScalarValue::Str(s))
                | ParseEvent::Scalar(ScalarValue::StringlyTyped(s)) => {
                    return self.set_string_value(wip, s);
                }
                _ => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "string for &str",
                        got: format!("{event:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // &[u8] - handle specially for zero-copy borrowing
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
            && let Some(pointee) = ptr_def.pointee()
            && let Def::Slice(slice_def) = pointee.def
            && slice_def.t.type_identifier == "u8"
        {
            // Hint to non-self-describing parsers that bytes are expected
            self.parser.hint_scalar_type(ScalarTypeHint::Bytes);
            let event = self.expect_event("bytes for &[u8]")?;
            if let ParseEvent::Scalar(ScalarValue::Bytes(b)) = event {
                return self.set_bytes_value(wip, b);
            } else {
                return Err(DeserializeError::TypeMismatch {
                    expected: "bytes for &[u8]",
                    got: format!("{event:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        // Regular smart pointer (Box, Arc, Rc)
        wip = wip.begin_smart_ptr().map_err(DeserializeError::reflect)?;

        // Check if begin_smart_ptr set up a slice builder (for Arc<[T]>, Rc<[T]>, Box<[T]>)
        // In this case, we need to deserialize as a list manually
        let is_slice_builder = wip.is_building_smart_ptr_slice();

        if is_slice_builder {
            // Deserialize the list elements into the slice builder
            // We can't use deserialize_list() because it calls begin_list() which interferes
            // Hint to non-self-describing parsers that a sequence is expected
            self.parser.hint_sequence();
            let event = self.expect_event("value")?;

            // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
            // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
            let struct_mode = match event {
                ParseEvent::SequenceStart(_) => false,
                ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
                ParseEvent::StructStart(kind) => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "array",
                        got: kind.name().into(),
                        span: self.last_span,
                        path: None,
                    });
                }
                _ => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "sequence start for Arc<[T]>/Rc<[T]>/Box<[T]>",
                        got: format!("{event:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            };

            loop {
                let event = self.expect_peek("value")?;

                // Check for end of container
                if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                    self.expect_event("value")?;
                    break;
                }

                // In struct mode, skip FieldKey events
                if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
                    self.expect_event("value")?;
                    continue;
                }

                wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
                wip = self.deserialize_into(wip)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            }

            // Convert the slice builder to Arc/Rc/Box and mark as initialized
            wip = wip.end().map_err(DeserializeError::reflect)?;
            // DON'T call end() again - the caller (deserialize_struct) will do that
        } else {
            // Regular smart pointer with sized pointee
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }

        Ok(wip)
    }

    /// Check if a field matches the given name, namespace, and location constraints.
    ///
    /// This implements format-specific field matching for XML and KDL:
    ///
    /// Check if a type can be deserialized directly from a scalar value.
    ///
    /// This is used for KDL child nodes that contain only a single argument value,
    /// allowing `#[facet(kdl::child)]` to work on primitive types like `bool`, `u64`, `String`.
    fn is_scalar_compatible_type(shape: &facet_core::Shape) -> bool {
        match &shape.def {
            Def::Scalar => true,
            Def::Option(opt) => Self::is_scalar_compatible_type(opt.t),
            Def::Pointer(ptr) => ptr.pointee.is_some_and(Self::is_scalar_compatible_type),
            _ => {
                // Also check for transparent wrappers (newtypes)
                if !matches!(
                    &shape.def,
                    Def::List(_) | Def::Map(_) | Def::Set(_) | Def::Array(_)
                ) && let Some(inner) = shape.inner
                {
                    return Self::is_scalar_compatible_type(inner);
                }
                false
            }
        }
    }

    /// Deserialize a KDL child node that contains only a scalar argument into a scalar type.
    ///
    /// When a KDL node like `enabled #true` is parsed, it generates:
    /// - `StructStart`
    /// - `FieldKey("_node_name", Argument)` → `Scalar("enabled")`
    /// - `FieldKey("_arg", Argument)` → `Scalar(true)`  ← this is what we want
    /// - `StructEnd`
    ///
    /// This method consumes those events and extracts the scalar value.
    fn deserialize_kdl_child_scalar(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Consume the StructStart
        let event = self.expect_event("struct start for kdl child")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start for kdl child node",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Scan through the struct looking for _arg (single argument) or first argument
        let mut found_scalar: Option<ScalarValue<'input>> = None;

        loop {
            let event = self.expect_event("field or struct end for kdl child")?;
            match event {
                ParseEvent::StructEnd => break,
                ParseEvent::FieldKey(key) => {
                    // Check if this is the argument field we're looking for
                    if key.location == FieldLocationHint::Argument
                        && (key.name == "_arg" || key.name == "0")
                    {
                        // Next event should be the scalar value
                        let value_event = self.expect_event("scalar value for kdl child")?;
                        if let ParseEvent::Scalar(scalar) = value_event {
                            found_scalar = Some(scalar);
                        } else {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "scalar value for kdl::child primitive",
                                got: format!("{value_event:?}"),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    } else {
                        // Skip this field's value (could be _node_name, _arguments, etc.)
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end for kdl child",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // Now deserialize the scalar value into the target type
        if let Some(scalar) = found_scalar {
            // Handle Option<T> types - we need to wrap the value in Some
            if matches!(&wip.shape().def, Def::Option(_)) {
                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                wip = self.set_scalar(wip, scalar)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            } else {
                wip = self.set_scalar(wip, scalar)?;
            }
            Ok(wip)
        } else {
            Err(DeserializeError::TypeMismatch {
                expected: "argument value in kdl::child node",
                got: "no argument found".to_string(),
                span: self.last_span,
                path: None,
            })
        }
    }

    /// **XML matching:**
    /// - Text: Match fields with xml::text attribute (name is ignored - text content goes to the field)
    /// - Attributes: Only match if explicit xml::ns matches (no ns_all inheritance per XML spec)
    /// - Elements: Match if explicit xml::ns OR ns_all matches
    ///
    /// **KDL matching:**
    /// - Argument: Match fields with kdl::argument attribute
    /// - Property: Match fields with kdl::property attribute
    /// - Child: Match fields with kdl::child or kdl::children attribute
    ///
    /// **Default (KeyValue):** Match by name/alias only (backwards compatible)
    ///
    /// TODO: This function hardcodes knowledge of XML and KDL attributes.
    /// See <https://github.com/facet-rs/facet/issues/1506> for discussion on
    /// making this more extensible.
    fn field_matches_with_namespace(
        field: &facet_core::Field,
        name: &str,
        namespace: Option<&str>,
        location: FieldLocationHint,
        ns_all: Option<&str>,
    ) -> bool {
        // === XML/HTML: Fields with xml::attribute match only attributes
        if field.is_attribute() && !matches!(location, FieldLocationHint::Attribute) {
            return false;
        }

        // === XML/HTML: Fields with xml::element/elements match only child elements
        // === KDL: Fields with kdl::child/children match only child nodes
        if (field.is_element() || field.is_elements())
            && !matches!(location, FieldLocationHint::Child)
        {
            return false;
        }

        // === XML/HTML: Text location matches fields with text attribute ===
        // The name "_text" from the parser is ignored - we match by attribute presence
        if matches!(location, FieldLocationHint::Text) {
            return field.is_text();
        }

        // === XML/HTML: Tag location matches fields with html::tag or xml::tag attribute ===
        // The name "_tag" from the parser is ignored - we match by attribute presence
        // This allows custom elements to capture the element's tag name
        if matches!(location, FieldLocationHint::Tag) {
            return field.is_tag();
        }

        // === KDL: Node name matching for kdl::node_name attribute ===
        // The parser emits "_node_name" as the field key for node name
        if matches!(location, FieldLocationHint::Argument) && name == "_node_name" {
            return field.is_node_name();
        }

        // === KDL: Arguments (plural) matching for kdl::arguments attribute ===
        // The parser emits "_arguments" as the field key for all arguments as a sequence
        if matches!(location, FieldLocationHint::Argument) && name == "_arguments" {
            return field.is_arguments_plural();
        }

        // === KDL: Argument location matches fields with kdl::argument attribute ===
        // For kdl::argument (singular), we match by attribute presence, not by name
        // (arguments are positional, name in FieldKey is just "_arg" or index)
        // Skip fields that want plural (kdl::arguments) - they matched above
        // If no kdl::argument attr, fall through to name matching
        if matches!(location, FieldLocationHint::Argument) && field.is_argument() {
            // Don't match singular _arg to kdl::arguments fields
            if field.is_arguments_plural() {
                return false;
            }
            return true;
        }

        // === KDL: Property location matches fields with kdl::property attribute ===
        // For properties, we need BOTH the attribute AND name match
        // If no kdl::property attr, fall through to name matching
        if matches!(location, FieldLocationHint::Property) && field.is_property() {
            let name_matches = field.name == name || field.alias.iter().any(|alias| *alias == name);
            return name_matches;
        }

        // === Check name/alias ===
        let name_matches = field.name == name || field.alias.iter().any(|alias| *alias == name);

        if !name_matches {
            return false;
        }

        // === XML: Namespace matching ===
        // Get the expected namespace for this field
        let field_xml_ns = field
            .get_attr(Some("xml"), "ns")
            .and_then(|attr| attr.get_as::<&str>().copied());

        // CRITICAL: Attributes don't inherit ns_all (per XML spec)
        let expected_ns = if matches!(location, FieldLocationHint::Attribute) {
            field_xml_ns // Attributes: only explicit xml::ns
        } else {
            field_xml_ns.or(ns_all) // Elements: xml::ns OR ns_all
        };

        // Check if namespaces match
        match (namespace, expected_ns) {
            (Some(input_ns), Some(expected)) => input_ns == expected,
            (Some(_input_ns), None) => true, // Input has namespace, field doesn't require one - match
            (None, Some(_expected)) => false, // Input has no namespace, field requires one - NO match
            (None, None) => true,             // Neither has namespace - match
        }
    }

    /// Run validation on a field value.
    ///
    /// This checks for `validate::*` attributes on the field and runs
    /// the appropriate validators on the deserialized value.
    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn run_field_validators(
        &self,
        field: &facet_core::Field,
        wip: &Partial<'input, BORROW>,
    ) -> Result<(), DeserializeError<P::Error>> {
        use facet_core::ValidatorFn;

        // Get the data pointer from the current frame
        let Some(data_ptr) = wip.data_ptr() else {
            return Ok(());
        };

        // Check for validation attributes
        for attr in field.attributes.iter() {
            if attr.ns != Some("validate") {
                continue;
            }

            let validation_result: Result<(), String> = match attr.key {
                "custom" => {
                    // Custom validators store a ValidatorFn function pointer
                    let validator_fn = unsafe { *attr.data.ptr().get::<ValidatorFn>() };
                    unsafe { validator_fn(data_ptr) }
                }
                "min" => {
                    let min_val = unsafe { *attr.data.ptr().get::<i64>() };
                    self.validate_min(data_ptr, wip.shape(), min_val)
                }
                "max" => {
                    let max_val = unsafe { *attr.data.ptr().get::<i64>() };
                    self.validate_max(data_ptr, wip.shape(), max_val)
                }
                "min_length" => {
                    let min_len = unsafe { *attr.data.ptr().get::<usize>() };
                    self.validate_min_length(data_ptr, wip.shape(), min_len)
                }
                "max_length" => {
                    let max_len = unsafe { *attr.data.ptr().get::<usize>() };
                    self.validate_max_length(data_ptr, wip.shape(), max_len)
                }
                "email" => self.validate_email(data_ptr, wip.shape()),
                "url" => self.validate_url(data_ptr, wip.shape()),
                "regex" => {
                    let pattern = unsafe { *attr.data.ptr().get::<&'static str>() };
                    self.validate_regex(data_ptr, wip.shape(), pattern)
                }
                "contains" => {
                    let needle = unsafe { *attr.data.ptr().get::<&'static str>() };
                    self.validate_contains(data_ptr, wip.shape(), needle)
                }
                _ => Ok(()), // Unknown validator, skip
            };

            if let Err(message) = validation_result {
                return Err(DeserializeError::Validation {
                    field: field.name,
                    message,
                    span: self.last_span,
                    path: Some(self.current_path.clone()),
                });
            }
        }

        Ok(())
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_min(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        min_val: i64,
    ) -> Result<(), String> {
        use facet_core::ScalarType;
        let actual = match shape.scalar_type() {
            Some(ScalarType::I8) => (unsafe { *ptr.get::<i8>() }) as i64,
            Some(ScalarType::I16) => (unsafe { *ptr.get::<i16>() }) as i64,
            Some(ScalarType::I32) => (unsafe { *ptr.get::<i32>() }) as i64,
            Some(ScalarType::I64) => unsafe { *ptr.get::<i64>() },
            Some(ScalarType::U8) => (unsafe { *ptr.get::<u8>() }) as i64,
            Some(ScalarType::U16) => (unsafe { *ptr.get::<u16>() }) as i64,
            Some(ScalarType::U32) => (unsafe { *ptr.get::<u32>() }) as i64,
            Some(ScalarType::U64) => {
                let v = unsafe { *ptr.get::<u64>() };
                if v > i64::MAX as u64 {
                    return Ok(()); // Value too large to compare, assume valid
                }
                v as i64
            }
            _ => return Ok(()), // Not a numeric type, skip validation
        };
        if actual < min_val {
            Err(format!("must be >= {}, got {}", min_val, actual))
        } else {
            Ok(())
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_max(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        max_val: i64,
    ) -> Result<(), String> {
        use facet_core::ScalarType;
        let actual = match shape.scalar_type() {
            Some(ScalarType::I8) => (unsafe { *ptr.get::<i8>() }) as i64,
            Some(ScalarType::I16) => (unsafe { *ptr.get::<i16>() }) as i64,
            Some(ScalarType::I32) => (unsafe { *ptr.get::<i32>() }) as i64,
            Some(ScalarType::I64) => unsafe { *ptr.get::<i64>() },
            Some(ScalarType::U8) => (unsafe { *ptr.get::<u8>() }) as i64,
            Some(ScalarType::U16) => (unsafe { *ptr.get::<u16>() }) as i64,
            Some(ScalarType::U32) => (unsafe { *ptr.get::<u32>() }) as i64,
            Some(ScalarType::U64) => {
                let v = unsafe { *ptr.get::<u64>() };
                if v > i64::MAX as u64 {
                    return Err(format!("must be <= {}, got {}", max_val, v));
                }
                v as i64
            }
            _ => return Ok(()), // Not a numeric type, skip validation
        };
        if actual > max_val {
            Err(format!("must be <= {}, got {}", max_val, actual))
        } else {
            Ok(())
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_min_length(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        min_len: usize,
    ) -> Result<(), String> {
        let len = self.get_length(ptr, shape)?;
        if len < min_len {
            Err(format!("length must be >= {}, got {}", min_len, len))
        } else {
            Ok(())
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_max_length(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        max_len: usize,
    ) -> Result<(), String> {
        let len = self.get_length(ptr, shape)?;
        if len > max_len {
            Err(format!("length must be <= {}, got {}", max_len, len))
        } else {
            Ok(())
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn get_length(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
    ) -> Result<usize, String> {
        // Check if it's a String
        if shape.is_type::<String>() {
            let s = unsafe { ptr.get::<String>() };
            return Ok(s.len());
        }
        // Check if it's a &str
        if shape.is_type::<&str>() {
            let s = unsafe { *ptr.get::<&str>() };
            return Ok(s.len());
        }
        // For Vec and other list types, we'd need to check shape.def
        // For now, return 0 for unknown types
        Ok(0)
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_email(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
    ) -> Result<(), String> {
        let s = self.get_string(ptr, shape)?;
        if facet_validate::is_valid_email(s) {
            Ok(())
        } else {
            Err(format!("'{}' is not a valid email address", s))
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_url(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
    ) -> Result<(), String> {
        let s = self.get_string(ptr, shape)?;
        if facet_validate::is_valid_url(s) {
            Ok(())
        } else {
            Err(format!("'{}' is not a valid URL", s))
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_regex(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        pattern: &str,
    ) -> Result<(), String> {
        let s = self.get_string(ptr, shape)?;
        if facet_validate::matches_pattern(s, pattern) {
            Ok(())
        } else {
            Err(format!("'{}' does not match pattern '{}'", s, pattern))
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn validate_contains(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
        needle: &str,
    ) -> Result<(), String> {
        let s = self.get_string(ptr, shape)?;
        if s.contains(needle) {
            Ok(())
        } else {
            Err(format!("'{}' does not contain '{}'", s, needle))
        }
    }

    #[cfg(feature = "validate")]
    #[allow(unsafe_code)]
    fn get_string<'s>(
        &self,
        ptr: facet_core::PtrConst,
        shape: &'static facet_core::Shape,
    ) -> Result<&'s str, String> {
        if shape.is_type::<String>() {
            let s = unsafe { ptr.get::<String>() };
            return Ok(s.as_str());
        }
        if shape.is_type::<&str>() {
            let s = unsafe { *ptr.get::<&str>() };
            return Ok(s);
        }
        Err("expected string type".to_string())
    }

    fn deserialize_struct(
        &mut self,
        wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Get struct fields for lookup
        let struct_def = match &wip.shape().ty {
            Type::User(UserType::Struct(def)) => def,
            _ => {
                return Err(DeserializeError::Unsupported(format!(
                    "expected struct type but got {:?}",
                    wip.shape().ty
                )));
            }
        };

        // Check if we have any flattened fields
        let has_flatten = struct_def.fields.iter().any(|f| f.is_flattened());

        if has_flatten {
            // Check if any flatten field is an enum (requires solver)
            // or if there's nested flatten (flatten inside flatten) that isn't just a map
            let needs_solver = struct_def.fields.iter().any(|f| {
                if !f.is_flattened() {
                    return false;
                }
                // Get inner type, unwrapping Option if present
                let inner_shape = match f.shape().def {
                    Def::Option(opt) => opt.t,
                    _ => f.shape(),
                };
                match inner_shape.ty {
                    // Enum flatten needs solver
                    Type::User(UserType::Enum(_)) => true,
                    // Check for nested flatten (flatten field has its own flatten fields)
                    // Exclude flattened maps as they just catch unknown keys, not nested fields
                    Type::User(UserType::Struct(inner_struct)) => {
                        inner_struct.fields.iter().any(|inner_f| {
                            inner_f.is_flattened() && {
                                let inner_inner_shape = match inner_f.shape().def {
                                    Def::Option(opt) => opt.t,
                                    _ => inner_f.shape(),
                                };
                                // Maps don't create nested field structures
                                !matches!(inner_inner_shape.def, Def::Map(_))
                            }
                        })
                    }
                    _ => false,
                }
            });

            if needs_solver {
                self.deserialize_struct_with_flatten(wip)
            } else {
                // Simple single-level flatten - use the original approach
                self.deserialize_struct_single_flatten(wip)
            }
        } else {
            self.deserialize_struct_simple(wip)
        }
    }

    /// Deserialize a struct without flattened fields (simple case).
    fn deserialize_struct_simple(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::Characteristic;

        // Get struct fields for lookup (needed before hint)
        let struct_def = match &wip.shape().ty {
            Type::User(UserType::Struct(def)) => def,
            _ => {
                return Err(DeserializeError::Unsupported(format!(
                    "expected struct type but got {:?}",
                    wip.shape().ty
                )));
            }
        };

        // Hint to non-self-describing parsers how many fields to expect
        self.parser.hint_struct_fields(struct_def.fields.len());

        let struct_has_default = wip.shape().has_default_attr();

        // Expect StructStart, but for XML/HTML, a scalar means text-only element
        let event = self.expect_event("value")?;
        if let ParseEvent::Scalar(scalar) = &event {
            // For XML/HTML, a text-only element is emitted as a scalar.
            // If the struct has a text field, set it from the scalar.
            if let Some((idx, _field)) = struct_def
                .fields
                .iter()
                .enumerate()
                .find(|(_, f)| f.is_text())
            {
                wip = wip
                    .begin_nth_field(idx)
                    .map_err(DeserializeError::reflect)?;

                // Handle Option<T>
                let is_option = matches!(&wip.shape().def, Def::Option(_));
                if is_option {
                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                }

                wip = self.set_scalar(wip, scalar.clone())?;

                if is_option {
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }
                wip = wip.end().map_err(DeserializeError::reflect)?;

                // Set defaults for other fields
                for (other_idx, other_field) in struct_def.fields.iter().enumerate() {
                    if other_idx == idx {
                        continue;
                    }

                    let field_has_default = other_field.has_default();
                    let field_type_has_default =
                        other_field.shape().is(facet_core::Characteristic::Default);
                    let field_is_option = matches!(other_field.shape().def, Def::Option(_));

                    if field_has_default || (struct_has_default && field_type_has_default) {
                        wip = wip
                            .set_nth_field_to_default(other_idx)
                            .map_err(DeserializeError::reflect)?;
                    } else if field_is_option {
                        wip = wip
                            .begin_field(other_field.name)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else if other_field.should_skip_deserializing() {
                        wip = wip
                            .set_nth_field_to_default(other_idx)
                            .map_err(DeserializeError::reflect)?;
                    }
                    // If a field is required and not set, that's an error, but we'll
                    // leave that for the struct-level validation
                }

                return Ok(wip);
            }

            // No xml::text field - this is an error
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }
        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();

        // Extract container-level default namespace (xml::ns_all) for namespace-aware matching
        let ns_all = wip
            .shape()
            .attributes
            .iter()
            .find(|attr| attr.ns == Some("xml") && attr.key == "ns_all")
            .and_then(|attr| attr.get_as::<&str>().copied());

        // Track which fields have been set
        let num_fields = struct_def.fields.len();
        let mut fields_set = alloc::vec![false; num_fields];
        let mut ordered_field_index = 0usize;

        // Track xml::elements field state for collecting child elements into lists
        // When Some((idx, in_list)), we're collecting items into field at idx
        let mut elements_field_state: Option<(usize, bool)> = None;

        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => {
                    // End any open xml::elements field
                    // Note: begin_list() doesn't push a frame, so we only need to end the field
                    if let Some((_, true)) = elements_field_state {
                        wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                    }
                    break;
                }
                ParseEvent::OrderedField => {
                    // Non-self-describing formats emit OrderedField events in order
                    let idx = ordered_field_index;
                    ordered_field_index += 1;
                    if idx < num_fields {
                        // Track path for error reporting
                        self.push_path(PathStep::Field(idx as u32));

                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = match self.deserialize_into(wip) {
                            Ok(wip) => wip,
                            Err(e) => {
                                // Only add path if error doesn't already have one
                                // (inner errors already have more specific paths)
                                let result = if e.path().is_some() {
                                    e
                                } else {
                                    let path = self.path_clone();
                                    e.with_path(path)
                                };
                                self.pop_path();
                                return Err(result);
                            }
                        };
                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        self.pop_path();

                        fields_set[idx] = true;
                    }
                }
                ParseEvent::FieldKey(key) => {
                    // Look up field in struct fields (direct match)
                    // Exclude xml::elements fields - they accumulate repeated child elements
                    // and must be handled via find_elements_field_for_element below
                    let field_info = struct_def.fields.iter().enumerate().find(|(_, f)| {
                        !f.is_elements()
                            && Self::field_matches_with_namespace(
                                f,
                                key.name.as_ref(),
                                key.namespace.as_deref(),
                                key.location,
                                ns_all,
                            )
                    });

                    if let Some((idx, field)) = field_info {
                        // End any open xml::elements field before switching to a different field
                        // Note: begin_list() doesn't push a frame, so we only end the field
                        if let Some((elem_idx, true)) = elements_field_state
                            && elem_idx != idx
                        {
                            wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                            elements_field_state = None;
                        }

                        // Track path for error reporting
                        self.push_path(PathStep::Field(idx as u32));

                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;

                        // Special handling for kdl::child with scalar types
                        // When a KDL child node contains only a scalar argument (e.g., `enabled #true`),
                        // we need to extract the argument value instead of treating it as a struct.
                        let use_kdl_child_scalar = key.location == FieldLocationHint::Child
                            && field.has_attr(Some("kdl"), "child")
                            && Self::is_scalar_compatible_type(wip.shape())
                            && matches!(
                                self.expect_peek("value for kdl::child field"),
                                Ok(ParseEvent::StructStart(_))
                            );

                        wip = if use_kdl_child_scalar {
                            match self.deserialize_kdl_child_scalar(wip) {
                                Ok(wip) => wip,
                                Err(e) => {
                                    let result = if e.path().is_some() {
                                        e
                                    } else {
                                        let path = self.path_clone();
                                        e.with_path(path)
                                    };
                                    self.pop_path();
                                    return Err(result);
                                }
                            }
                        } else {
                            match self.deserialize_into(wip) {
                                Ok(wip) => wip,
                                Err(e) => {
                                    // Only add path if error doesn't already have one
                                    // (inner errors already have more specific paths)
                                    let result = if e.path().is_some() {
                                        e
                                    } else {
                                        let path = self.path_clone();
                                        e.with_path(path)
                                    };
                                    self.pop_path();
                                    return Err(result);
                                }
                            }
                        };

                        // Run validation on the field value before finalizing
                        #[cfg(feature = "validate")]
                        self.run_field_validators(field, &wip)?;

                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        self.pop_path();

                        fields_set[idx] = true;
                        continue;
                    }

                    // Check if this child element should go into an elements field
                    if key.location == FieldLocationHint::Child
                        && let Some((idx, field)) = self.find_elements_field_for_element(
                            struct_def.fields,
                            key.name.as_ref(),
                            key.namespace.as_deref(),
                            ns_all,
                        )
                    {
                        // Start or continue the list for this elements field
                        match elements_field_state {
                            None => {
                                // Start new list
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
                                elements_field_state = Some((idx, true));
                                fields_set[idx] = true;
                            }
                            Some((current_idx, true)) if current_idx != idx => {
                                // Switching to a different xml::elements field
                                // Note: begin_list() doesn't push a frame, so we only end the field
                                wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
                                elements_field_state = Some((idx, true));
                                fields_set[idx] = true;
                            }
                            Some((current_idx, true)) if current_idx == idx => {
                                // Continue adding to same list
                            }
                            _ => {}
                        }

                        // Add item to list
                        wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;

                        // For enum item types, we need to select the variant based on element name
                        let item_shape = Self::get_list_item_shape(field.shape());
                        if let Some(item_shape) = item_shape {
                            if let Type::User(UserType::Enum(enum_def)) = &item_shape.ty {
                                // Find matching variant (direct or custom_element fallback)
                                match Self::find_variant_for_element(enum_def, key.name.as_ref()) {
                                    Some(VariantMatch::Direct(variant_idx))
                                    | Some(VariantMatch::CustomElement(variant_idx)) => {
                                        wip = wip
                                            .select_nth_variant(variant_idx)
                                            .map_err(DeserializeError::reflect)?;
                                        // After selecting variant, deserialize the variant content
                                        // For custom elements, the _tag field will be matched
                                        // by FieldLocationHint::Tag
                                        wip = self.deserialize_enum_variant_content(wip)?;
                                    }
                                    None => {
                                        // No matching variant - deserialize directly
                                        wip = self.deserialize_into(wip)?;
                                    }
                                }
                            } else {
                                // Not an enum - deserialize directly
                                wip = self.deserialize_into(wip)?;
                            }
                        } else {
                            wip = self.deserialize_into(wip)?;
                        }

                        wip = wip.end().map_err(DeserializeError::reflect)?; // end list item
                        continue;
                    }

                    if deny_unknown_fields {
                        return Err(DeserializeError::UnknownField {
                            field: key.name.into_owned(),
                            span: self.last_span,
                            path: None,
                        });
                    } else {
                        // Unknown field - skip it
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // In deferred mode, skip validation - finish_deferred() will handle it.
        // This allows formats like TOML to reopen tables and set more fields later.
        if wip.is_deferred() {
            return Ok(wip);
        }

        // Apply defaults for missing fields
        // First, check if ALL non-elements fields are missing and the struct has a container-level
        // default. In that case, use the struct's Default impl directly.
        let all_non_elements_missing = struct_def
            .fields
            .iter()
            .enumerate()
            .all(|(idx, field)| !fields_set[idx] || field.is_elements());

        if struct_has_default && all_non_elements_missing && wip.shape().is(Characteristic::Default)
        {
            // Use the struct's Default impl for all fields at once
            wip = wip.set_default().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        for (idx, field) in struct_def.fields.iter().enumerate() {
            if fields_set[idx] {
                continue;
            }

            let field_has_default = field.has_default();
            let field_type_has_default = field.shape().is(Characteristic::Default);
            let field_is_option = matches!(field.shape().def, Def::Option(_));

            // elements fields with no items should get an empty list
            // begin_list() doesn't push a frame, so we just begin the field, begin the list,
            // then end the field (no end() for the list itself).
            if field.is_elements() {
                wip = wip
                    .begin_nth_field(idx)
                    .map_err(DeserializeError::reflect)?;
                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
                wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                continue;
            }

            if field_has_default || (struct_has_default && field_type_has_default) {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else if field_is_option {
                wip = wip
                    .begin_field(field.name)
                    .map_err(DeserializeError::reflect)?;
                wip = wip.set_default().map_err(DeserializeError::reflect)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            } else if field.should_skip_deserializing() {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else {
                return Err(DeserializeError::MissingField {
                    field: field.name,
                    type_name: wip.shape().type_identifier,
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }

    /// Find an elements field that can accept a child element with the given name.
    fn find_elements_field_for_element<'a>(
        &self,
        fields: &'a [facet_core::Field],
        element_name: &str,
        element_ns: Option<&str>,
        ns_all: Option<&str>,
    ) -> Option<(usize, &'a facet_core::Field)> {
        for (idx, field) in fields.iter().enumerate() {
            if !field.is_elements() {
                continue;
            }

            // Get the list item shape
            let item_shape = Self::get_list_item_shape(field.shape())?;

            // Check if the item type can accept this element
            if Self::shape_accepts_element(item_shape, element_name, element_ns, ns_all) {
                return Some((idx, field));
            }

            // Also check singularization: if element_name is the singular of field.name
            // This handles cases like: field `items: Vec<Item>` with `#[facet(kdl::children)]`
            // accepting child nodes named "item"
            #[cfg(feature = "singularize")]
            if facet_singularize::is_singular_of(element_name, field.name) {
                return Some((idx, field));
            }
        }
        None
    }

    /// Get the item shape from a list-like field shape.
    fn get_list_item_shape(shape: &facet_core::Shape) -> Option<&'static facet_core::Shape> {
        match &shape.def {
            Def::List(list_def) => Some(list_def.t()),
            _ => None,
        }
    }

    /// Check if a shape can accept an element with the given name.
    fn shape_accepts_element(
        shape: &facet_core::Shape,
        element_name: &str,
        _element_ns: Option<&str>,
        _ns_all: Option<&str>,
    ) -> bool {
        match &shape.ty {
            Type::User(UserType::Enum(enum_def)) => {
                // For enums, check if element name matches any variant
                let matches_variant = enum_def.variants.iter().any(|v| {
                    let display_name = Self::get_variant_display_name(v);
                    display_name.eq_ignore_ascii_case(element_name)
                });
                if matches_variant {
                    return true;
                }
                // Also check if enum has a custom_element fallback variant that can accept any element
                enum_def.variants.iter().any(|v| v.is_custom_element())
            }
            Type::User(UserType::Struct(struct_def)) => {
                // If the struct has a kdl::node_name field, it can accept any element name
                // since the name will be captured into that field
                if struct_def.fields.iter().any(|f| f.is_node_name()) {
                    return true;
                }
                // Similarly, if the struct has a tag field (for HTML/XML custom elements),
                // it can accept any element name
                if struct_def.fields.iter().any(|f| f.is_tag()) {
                    return true;
                }
                // Otherwise, check if element name matches struct's name
                // Use case-insensitive comparison since serializers may normalize case
                // (e.g., KDL serializer lowercases "Server" to "server")
                let display_name = Self::get_shape_display_name(shape);
                display_name.eq_ignore_ascii_case(element_name)
            }
            _ => {
                // For other types, use type identifier with case-insensitive comparison
                shape.type_identifier.eq_ignore_ascii_case(element_name)
            }
        }
    }

    /// Get the display name for a variant (respecting rename attribute).
    fn get_variant_display_name(variant: &facet_core::Variant) -> &'static str {
        if let Some(attr) = variant.get_builtin_attr("rename")
            && let Some(&renamed) = attr.get_as::<&str>()
        {
            return renamed;
        }
        variant.name
    }

    /// Get the display name for a shape (respecting rename attribute).
    fn get_shape_display_name(shape: &facet_core::Shape) -> &'static str {
        if let Some(renamed) = shape.get_builtin_attr_value::<&str>("rename") {
            return renamed;
        }
        shape.type_identifier
    }

    /// Find the variant index for an enum that matches the given element name.
    ///
    /// First tries to find an exact match by name/rename. If no match is found,
    /// falls back to the `#[facet(html::custom_element)]` or `#[facet(xml::custom_element)]`
    /// variant if present.
    fn find_variant_for_element(
        enum_def: &facet_core::EnumType,
        element_name: &str,
    ) -> Option<VariantMatch> {
        // First try direct name match
        if let Some(idx) = enum_def.variants.iter().position(|v| {
            let display_name = Self::get_variant_display_name(v);
            display_name == element_name
        }) {
            return Some(VariantMatch::Direct(idx));
        }

        // Fall back to custom_element variant if present
        if let Some(idx) = enum_def.variants.iter().position(|v| v.is_custom_element()) {
            return Some(VariantMatch::CustomElement(idx));
        }

        None
    }

    /// Deserialize a struct with single-level flattened fields (original approach).
    /// This handles simple flatten cases where there's no nested flatten or enum flatten.
    fn deserialize_struct_single_flatten(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use alloc::collections::BTreeMap;
        use facet_core::Characteristic;
        use facet_reflect::Resolution;

        // Get struct fields for lookup
        let struct_type_name = wip.shape().type_identifier;
        let struct_def = match &wip.shape().ty {
            Type::User(UserType::Struct(def)) => def,
            _ => {
                return Err(DeserializeError::Unsupported(format!(
                    "expected struct type but got {:?}",
                    wip.shape().ty
                )));
            }
        };

        let struct_has_default = wip.shape().has_default_attr();

        // Expect StructStart, but for XML/HTML, a scalar means text-only element
        let event = self.expect_event("value")?;
        if let ParseEvent::Scalar(scalar) = &event {
            // For XML/HTML, a text-only element is emitted as a scalar.
            // If the struct has a text field, set it from the scalar and default the rest.
            if let Some((idx, _field)) = struct_def
                .fields
                .iter()
                .enumerate()
                .find(|(_, f)| f.is_text())
            {
                wip = wip
                    .begin_nth_field(idx)
                    .map_err(DeserializeError::reflect)?;

                // Handle Option<T>
                let is_option = matches!(&wip.shape().def, Def::Option(_));
                if is_option {
                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                }

                wip = self.set_scalar(wip, scalar.clone())?;

                if is_option {
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }
                wip = wip.end().map_err(DeserializeError::reflect)?;

                // Set defaults for other fields (including flattened ones)
                for (other_idx, other_field) in struct_def.fields.iter().enumerate() {
                    if other_idx == idx {
                        continue;
                    }

                    let field_has_default = other_field.has_default();
                    let field_type_has_default =
                        other_field.shape().is(facet_core::Characteristic::Default);
                    let field_is_option = matches!(other_field.shape().def, Def::Option(_));

                    if field_has_default || (struct_has_default && field_type_has_default) {
                        wip = wip
                            .set_nth_field_to_default(other_idx)
                            .map_err(DeserializeError::reflect)?;
                    } else if field_is_option {
                        wip = wip
                            .begin_field(other_field.name)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else if other_field.should_skip_deserializing() {
                        // Skip fields that are marked for skip deserializing
                        continue;
                    } else {
                        return Err(DeserializeError::MissingField {
                            field: other_field.name,
                            type_name: struct_type_name,
                            span: self.last_span,
                            path: None,
                        });
                    }
                }

                return Ok(wip);
            }
        }

        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }
        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();

        // Extract container-level default namespace (xml::ns_all) for namespace-aware matching
        let ns_all = wip
            .shape()
            .attributes
            .iter()
            .find(|attr| attr.ns == Some("xml") && attr.key == "ns_all")
            .and_then(|attr| attr.get_as::<&str>().copied());

        // Track which fields have been set
        let num_fields = struct_def.fields.len();
        let mut fields_set = alloc::vec![false; num_fields];

        // Build flatten info: for each flattened field, get its inner struct fields
        // and track which inner fields have been set
        let mut flatten_info: alloc::vec::Vec<
            Option<(&'static [facet_core::Field], alloc::vec::Vec<bool>)>,
        > = alloc::vec![None; num_fields];

        // Track which fields are DynamicValue flattens (like facet_value::Value)
        let mut dynamic_value_flattens: alloc::vec::Vec<bool> = alloc::vec![false; num_fields];

        // Track flattened map field index (for collecting unknown keys)
        // Can be either:
        // - (outer_idx, None) for a directly flattened map
        // - (outer_idx, Some(inner_idx)) for a map nested inside a flattened struct
        let mut flatten_map_idx: Option<(usize, Option<usize>)> = None;

        // Track field names across flattened structs to detect duplicates
        let mut flatten_field_names: BTreeMap<&str, usize> = BTreeMap::new();

        for (idx, field) in struct_def.fields.iter().enumerate() {
            if field.is_flattened() {
                // Handle Option<T> flatten by unwrapping to inner type
                let inner_shape = match field.shape().def {
                    Def::Option(opt) => opt.t,
                    _ => field.shape(),
                };

                // Check if this is a DynamicValue flatten (like facet_value::Value)
                if matches!(inner_shape.def, Def::DynamicValue(_)) {
                    dynamic_value_flattens[idx] = true;
                } else if matches!(inner_shape.def, Def::Map(_)) {
                    // Flattened map - collects unknown keys
                    flatten_map_idx = Some((idx, None));
                } else if let Type::User(UserType::Struct(inner_def)) = &inner_shape.ty {
                    let inner_fields = inner_def.fields;
                    let inner_set = alloc::vec![false; inner_fields.len()];
                    flatten_info[idx] = Some((inner_fields, inner_set));

                    // Check for duplicate field names across flattened structs
                    for inner_field in inner_fields.iter() {
                        let field_name = inner_field.rename.unwrap_or(inner_field.name);
                        if let Some(_prev_idx) = flatten_field_names.insert(field_name, idx) {
                            return Err(DeserializeError::Unsupported(format!(
                                "duplicate field `{}` in flattened structs",
                                field_name
                            )));
                        }
                    }

                    // Also check for nested flattened maps inside this struct
                    // (e.g., GlobalAttrs has a flattened HashMap for unknown attributes)
                    if flatten_map_idx.is_none() {
                        for (inner_idx, inner_field) in inner_fields.iter().enumerate() {
                            if inner_field.is_flattened() {
                                let inner_inner_shape = match inner_field.shape().def {
                                    Def::Option(opt) => opt.t,
                                    _ => inner_field.shape(),
                                };
                                if matches!(inner_inner_shape.def, Def::Map(_)) {
                                    flatten_map_idx = Some((idx, Some(inner_idx)));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Enter deferred mode for flatten handling (if not already in deferred mode)
        let already_deferred = wip.is_deferred();
        if !already_deferred {
            let resolution = Resolution::new();
            wip = wip
                .begin_deferred(resolution)
                .map_err(DeserializeError::reflect)?;
        }

        // Track xml::elements field state for collecting child elements into lists
        // (field_idx, is_open)
        let mut elements_field_state: Option<(usize, bool)> = None;

        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => {
                    // End any open xml::elements field
                    if let Some((_, true)) = elements_field_state {
                        wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                    }
                    break;
                }
                ParseEvent::FieldKey(key) => {
                    // First, look up field in direct struct fields (non-flattened, non-elements)
                    // Exclude xml::elements fields - they accumulate repeated child elements
                    // and must be handled via find_elements_field_for_element below
                    let direct_field_info = struct_def.fields.iter().enumerate().find(|(_, f)| {
                        !f.is_flattened()
                            && !f.is_elements()
                            && Self::field_matches_with_namespace(
                                f,
                                key.name.as_ref(),
                                key.namespace.as_deref(),
                                key.location,
                                ns_all,
                            )
                    });

                    if let Some((idx, _field)) = direct_field_info {
                        // End any open xml::elements field before switching to a different field
                        if let Some((elem_idx, true)) = elements_field_state
                            && elem_idx != idx
                        {
                            wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                            elements_field_state = None;
                        }

                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_into(wip)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                        fields_set[idx] = true;
                        continue;
                    }

                    // Check if this child element or text node should go into an xml::elements field
                    // This handles both child elements and text nodes in mixed content
                    if matches!(
                        key.location,
                        FieldLocationHint::Child | FieldLocationHint::Text
                    ) && let Some((idx, field)) = self.find_elements_field_for_element(
                        struct_def.fields,
                        key.name.as_ref(),
                        key.namespace.as_deref(),
                        ns_all,
                    ) {
                        // Start or continue the list for this elements field
                        match elements_field_state {
                            None => {
                                // Start new list
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
                                elements_field_state = Some((idx, true));
                                fields_set[idx] = true;
                            }
                            Some((current_idx, true)) if current_idx != idx => {
                                // Switching to a different xml::elements field
                                wip = wip.end().map_err(DeserializeError::reflect)?; // end field only
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
                                elements_field_state = Some((idx, true));
                                fields_set[idx] = true;
                            }
                            Some((current_idx, true)) if current_idx == idx => {
                                // Continue adding to same list
                            }
                            _ => {}
                        }

                        // Add item to list
                        wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;

                        // For enum item types, we need to select the variant based on element name
                        let item_shape = Self::get_list_item_shape(field.shape());
                        if let Some(item_shape) = item_shape {
                            if let Type::User(UserType::Enum(enum_def)) = &item_shape.ty {
                                // Find matching variant (direct or custom_element fallback)
                                match Self::find_variant_for_element(enum_def, key.name.as_ref()) {
                                    Some(VariantMatch::Direct(variant_idx))
                                    | Some(VariantMatch::CustomElement(variant_idx)) => {
                                        wip = wip
                                            .select_nth_variant(variant_idx)
                                            .map_err(DeserializeError::reflect)?;
                                        // After selecting variant, deserialize the variant content
                                        // For custom elements, the _tag field will be matched
                                        // by FieldLocationHint::Tag
                                        wip = self.deserialize_enum_variant_content(wip)?;
                                    }
                                    None => {
                                        // No matching variant - deserialize directly
                                        wip = self.deserialize_into(wip)?;
                                    }
                                }
                            } else {
                                // Not an enum - deserialize directly
                                wip = self.deserialize_into(wip)?;
                            }
                        } else {
                            wip = self.deserialize_into(wip)?;
                        }

                        wip = wip.end().map_err(DeserializeError::reflect)?; // end list item
                        continue;
                    }

                    // Check flattened fields for a match
                    let mut found_flatten = false;
                    for (flatten_idx, field) in struct_def.fields.iter().enumerate() {
                        if !field.is_flattened() {
                            continue;
                        }
                        if let Some((inner_fields, inner_set)) = flatten_info[flatten_idx].as_mut()
                        {
                            let inner_match =
                                inner_fields.iter().enumerate().find(|(inner_idx, f)| {
                                    // Nested flattened map is handled separately, even if its name
                                    // matches the key name it must be skipped.
                                    let is_flatten_map =
                                        Some((flatten_idx, Some(*inner_idx))) == flatten_map_idx;

                                    !is_flatten_map
                                        && Self::field_matches_with_namespace(
                                            f,
                                            key.name.as_ref(),
                                            key.namespace.as_deref(),
                                            key.location,
                                            ns_all,
                                        )
                                });

                            if let Some((inner_idx, _inner_field)) = inner_match {
                                // Check if flatten field is Option - if so, wrap in Some
                                let is_option = matches!(field.shape().def, Def::Option(_));
                                wip = wip
                                    .begin_nth_field(flatten_idx)
                                    .map_err(DeserializeError::reflect)?;
                                if is_option {
                                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                                }
                                wip = wip
                                    .begin_nth_field(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = self.deserialize_into(wip)?;
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                                if is_option {
                                    wip = wip.end().map_err(DeserializeError::reflect)?;
                                }
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                                inner_set[inner_idx] = true;
                                fields_set[flatten_idx] = true;
                                found_flatten = true;
                                break;
                            }
                        }
                    }

                    if found_flatten {
                        continue;
                    }

                    // Check if this unknown field should go to a DynamicValue flatten
                    let mut found_dynamic = false;
                    for (flatten_idx, _field) in struct_def.fields.iter().enumerate() {
                        if !dynamic_value_flattens[flatten_idx] {
                            continue;
                        }

                        // This is a DynamicValue flatten - insert the field into it
                        // First, ensure the DynamicValue is initialized as an object
                        let is_option =
                            matches!(struct_def.fields[flatten_idx].shape().def, Def::Option(_));

                        // Navigate to the DynamicValue field
                        wip = wip
                            .begin_nth_field(flatten_idx)
                            .map_err(DeserializeError::reflect)?;
                        if is_option {
                            wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                        }
                        // Initialize or re-enter the DynamicValue as an object.
                        // begin_map() is idempotent - it returns Ok if already in Object state.
                        // We always call it because in deferred mode inside collections (like HashMap),
                        // the frame might not be stored/restored, so we can't rely on fields_set alone.
                        wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                        fields_set[flatten_idx] = true;

                        // Insert the key-value pair into the object
                        wip = wip
                            .begin_object_entry(key.name.as_ref())
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_into(wip)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        // Navigate back out (Note: we close the map when we're done with ALL fields, not per-field)
                        if is_option {
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }
                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        found_dynamic = true;
                        break;
                    }

                    if found_dynamic {
                        continue;
                    }

                    // Skip _tag fields that have no matching is_tag() field - they should be silently ignored
                    // (Tag location hint is used by custom elements to capture the element name,
                    // but for regular elements it should just be dropped, not added to extra attributes)
                    if key.location == FieldLocationHint::Tag {
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                        continue;
                    }

                    // Check if this unknown field should go to a flattened map
                    // flatten_map_idx is (outer_idx, Option<inner_idx>):
                    // - (outer_idx, None): direct flattened map at struct_def.fields[outer_idx]
                    // - (outer_idx, Some(inner_idx)): nested map inside a flattened struct
                    //
                    // For nested maps, we only insert if the value is a scalar. This is important
                    // for HTML/XML where child elements also appear as object keys, but should not
                    // be inserted into an attribute map (which expects String values).
                    let should_insert_into_map = if let Some((_, inner_idx_opt)) = flatten_map_idx {
                        if inner_idx_opt.is_some() {
                            // Nested case: only insert if value is a scalar
                            matches!(
                                self.parser.peek_event().ok().flatten(),
                                Some(ParseEvent::Scalar(_))
                            )
                        } else {
                            // Direct case: always insert
                            true
                        }
                    } else {
                        false
                    };

                    if should_insert_into_map {
                        let (outer_idx, inner_idx_opt) = flatten_map_idx.unwrap();
                        let outer_field = &struct_def.fields[outer_idx];
                        let outer_is_option = matches!(outer_field.shape().def, Def::Option(_));

                        // Navigate to the outer field first
                        if !fields_set[outer_idx] {
                            // First time - need to initialize
                            wip = wip
                                .begin_nth_field(outer_idx)
                                .map_err(DeserializeError::reflect)?;
                            if outer_is_option {
                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                            }

                            if let Some(inner_idx) = inner_idx_opt {
                                // Nested case: navigate to the inner map field
                                let inner_field = flatten_info[outer_idx]
                                    .as_ref()
                                    .map(|(fields, _)| &fields[inner_idx])
                                    .expect("inner field should exist");
                                let inner_is_option =
                                    matches!(inner_field.shape().def, Def::Option(_));

                                wip = wip
                                    .begin_nth_field(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                                if inner_is_option {
                                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                                }
                                // Initialize the map
                                wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                            } else {
                                // Direct case: initialize the map
                                wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                            }
                            fields_set[outer_idx] = true;
                        } else {
                            // Already initialized - navigate to it
                            wip = wip
                                .begin_nth_field(outer_idx)
                                .map_err(DeserializeError::reflect)?;
                            if outer_is_option {
                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                            }

                            if let Some(inner_idx) = inner_idx_opt {
                                // Nested case: navigate to the inner map field
                                let inner_field = flatten_info[outer_idx]
                                    .as_ref()
                                    .map(|(fields, _)| &fields[inner_idx])
                                    .expect("inner field should exist");
                                let inner_is_option =
                                    matches!(inner_field.shape().def, Def::Option(_));

                                wip = wip
                                    .begin_nth_field(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                                if inner_is_option {
                                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                                }
                                // In deferred mode, the map frame might not be stored/restored,
                                // so we always need to call begin_map() to re-enter it
                                wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                            } else {
                                // Direct case: in deferred mode (e.g., within an array element),
                                // we need to re-enter the map even if already initialized
                                wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                            }
                        }

                        // Insert the key-value pair into the map using begin_key/begin_value
                        // Clone the key to an owned String since we need it beyond the parse event lifetime
                        let key_owned: alloc::string::String = key.name.clone().into_owned();
                        // First: push key frame
                        wip = wip.begin_key().map_err(DeserializeError::reflect)?;
                        // Set the key (it's a string)
                        wip = wip.set(key_owned).map_err(DeserializeError::reflect)?;
                        // Pop key frame
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                        // Push value frame
                        wip = wip.begin_value().map_err(DeserializeError::reflect)?;
                        // Deserialize value
                        wip = self.deserialize_into(wip)?;
                        // Pop value frame
                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        // Navigate back out
                        if let Some(inner_idx) = inner_idx_opt {
                            // Nested case: need to pop inner field frames too
                            let inner_field = flatten_info[outer_idx]
                                .as_ref()
                                .map(|(fields, _)| &fields[inner_idx])
                                .expect("inner field should exist");
                            let inner_is_option = matches!(inner_field.shape().def, Def::Option(_));

                            if inner_is_option {
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                            }
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }

                        if outer_is_option {
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }
                        wip = wip.end().map_err(DeserializeError::reflect)?;

                        // Mark the nested map field as set so defaults won't overwrite it
                        if let Some(inner_idx) = inner_idx_opt
                            && let Some((_, inner_set)) = flatten_info[outer_idx].as_mut()
                        {
                            inner_set[inner_idx] = true;
                        }

                        continue;
                    }

                    if deny_unknown_fields {
                        return Err(DeserializeError::UnknownField {
                            field: key.name.into_owned(),
                            span: self.last_span,
                            path: None,
                        });
                    } else {
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // Apply defaults for missing fields
        for (idx, field) in struct_def.fields.iter().enumerate() {
            if field.is_flattened() {
                // Handle DynamicValue flattens that received no fields
                if dynamic_value_flattens[idx] && !fields_set[idx] {
                    let is_option = matches!(field.shape().def, Def::Option(_));

                    if is_option {
                        // Option<DynamicValue> with no fields -> set to None
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else {
                        // DynamicValue with no fields -> initialize as empty object
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        // Initialize as object (for DynamicValue, begin_map creates an object)
                        wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                        // The map is now initialized and empty, just end the field
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    }
                    continue;
                }

                // Handle flattened map that received no unknown keys
                // Only applies to direct flattened maps (outer_idx, None), not nested ones
                if flatten_map_idx == Some((idx, None)) && !fields_set[idx] {
                    let is_option = matches!(field.shape().def, Def::Option(_));
                    let field_has_default = field.has_default();
                    let field_type_has_default =
                        field.shape().is(facet_core::Characteristic::Default);

                    if is_option {
                        // Option<HashMap> with no fields -> set to None
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else if field_has_default || (struct_has_default && field_type_has_default) {
                        // Has default - use it
                        wip = wip
                            .set_nth_field_to_default(idx)
                            .map_err(DeserializeError::reflect)?;
                    } else {
                        // No default - initialize as empty map
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.begin_map().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    }
                    continue;
                }

                if let Some((inner_fields, inner_set)) = flatten_info[idx].as_ref() {
                    let any_inner_set = inner_set.iter().any(|&s| s);
                    let is_option = matches!(field.shape().def, Def::Option(_));

                    if any_inner_set {
                        // Some inner fields were set - apply defaults to missing ones
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        if is_option {
                            wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                        }
                        for (inner_idx, inner_field) in inner_fields.iter().enumerate() {
                            if inner_set[inner_idx] {
                                continue;
                            }
                            let inner_has_default = inner_field.has_default();
                            let inner_type_has_default =
                                inner_field.shape().is(Characteristic::Default);
                            let inner_is_option = matches!(inner_field.shape().def, Def::Option(_));

                            if inner_has_default || inner_type_has_default {
                                wip = wip
                                    .set_nth_field_to_default(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                            } else if inner_is_option {
                                wip = wip
                                    .begin_nth_field(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = wip.set_default().map_err(DeserializeError::reflect)?;
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                            } else if inner_field.should_skip_deserializing() {
                                wip = wip
                                    .set_nth_field_to_default(inner_idx)
                                    .map_err(DeserializeError::reflect)?;
                            } else {
                                return Err(DeserializeError::TypeMismatch {
                                    expected: "field to be present or have default",
                                    got: format!("missing field '{}'", inner_field.name),
                                    span: self.last_span,
                                    path: None,
                                });
                            }
                        }
                        if is_option {
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else if is_option {
                        // No inner fields set and field is Option - set to None
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else {
                        // No inner fields set - try to default the whole flattened field
                        let field_has_default = field.has_default();
                        let field_type_has_default = field.shape().is(Characteristic::Default);
                        if field_has_default || (struct_has_default && field_type_has_default) {
                            wip = wip
                                .set_nth_field_to_default(idx)
                                .map_err(DeserializeError::reflect)?;
                        } else {
                            let all_inner_can_default = inner_fields.iter().all(|f| {
                                f.has_default()
                                    || f.shape().is(Characteristic::Default)
                                    || matches!(f.shape().def, Def::Option(_))
                                    || f.should_skip_deserializing()
                            });
                            if all_inner_can_default {
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                for (inner_idx, inner_field) in inner_fields.iter().enumerate() {
                                    let inner_has_default = inner_field.has_default();
                                    let inner_type_has_default =
                                        inner_field.shape().is(Characteristic::Default);
                                    let inner_is_option =
                                        matches!(inner_field.shape().def, Def::Option(_));

                                    if inner_has_default || inner_type_has_default {
                                        wip = wip
                                            .set_nth_field_to_default(inner_idx)
                                            .map_err(DeserializeError::reflect)?;
                                    } else if inner_is_option {
                                        wip = wip
                                            .begin_nth_field(inner_idx)
                                            .map_err(DeserializeError::reflect)?;
                                        wip =
                                            wip.set_default().map_err(DeserializeError::reflect)?;
                                        wip = wip.end().map_err(DeserializeError::reflect)?;
                                    } else if inner_field.should_skip_deserializing() {
                                        wip = wip
                                            .set_nth_field_to_default(inner_idx)
                                            .map_err(DeserializeError::reflect)?;
                                    }
                                }
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                            } else {
                                return Err(DeserializeError::TypeMismatch {
                                    expected: "field to be present or have default",
                                    got: format!("missing flattened field '{}'", field.name),
                                    span: self.last_span,
                                    path: None,
                                });
                            }
                        }
                    }
                }
                continue;
            }

            if fields_set[idx] {
                continue;
            }

            let field_has_default = field.has_default();
            let field_type_has_default = field.shape().is(Characteristic::Default);
            let field_is_option = matches!(field.shape().def, Def::Option(_));

            if field_has_default || (struct_has_default && field_type_has_default) {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else if field_is_option {
                wip = wip
                    .begin_field(field.name)
                    .map_err(DeserializeError::reflect)?;
                wip = wip.set_default().map_err(DeserializeError::reflect)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            } else if field.should_skip_deserializing() {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else {
                return Err(DeserializeError::TypeMismatch {
                    expected: "field to be present or have default",
                    got: format!("missing field '{}'", field.name),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        // Finish deferred mode (only if we started it)
        if !already_deferred {
            wip = wip.finish_deferred().map_err(DeserializeError::reflect)?;
        }

        Ok(wip)
    }

    /// Deserialize a struct with flattened fields using facet-solver.
    ///
    /// This uses the solver's Schema/Resolution to handle arbitrarily nested
    /// flatten structures by looking up the full path for each field.
    /// It also handles flattened enums by using probing to collect keys first,
    /// then using the Solver to disambiguate between resolutions.
    fn deserialize_struct_with_flatten(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use alloc::collections::BTreeSet;
        use facet_core::Characteristic;
        use facet_reflect::Resolution;
        use facet_solver::{PathSegment, Schema, Solver};

        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();

        // Build the schema for this type - this recursively expands all flatten fields
        let schema = Schema::build_auto(wip.shape())
            .map_err(|e| DeserializeError::Unsupported(format!("failed to build schema: {e}")))?;

        // Check if we have multiple resolutions (i.e., flattened enums)
        let resolutions = schema.resolutions();
        if resolutions.is_empty() {
            return Err(DeserializeError::Unsupported(
                "schema has no resolutions".into(),
            ));
        }

        // ========== PASS 1: Probe to collect all field keys ==========
        let probe = self
            .parser
            .begin_probe()
            .map_err(DeserializeError::Parser)?;
        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;

        // Feed keys to solver to narrow down resolutions
        let mut solver = Solver::new(&schema);
        for ev in &evidence {
            solver.see_key(ev.name.clone());
        }

        // Get the resolved configuration
        let config_handle = solver
            .finish()
            .map_err(|e| DeserializeError::Unsupported(format!("solver failed: {e}")))?;
        let resolution = config_handle.resolution();

        // ========== PASS 2: Parse the struct with resolved paths ==========
        // Expect StructStart
        let event = self.expect_event("value")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Enter deferred mode for flatten handling (if not already in deferred mode)
        let already_deferred = wip.is_deferred();
        if !already_deferred {
            let reflect_resolution = Resolution::new();
            wip = wip
                .begin_deferred(reflect_resolution)
                .map_err(DeserializeError::reflect)?;
        }

        // Track which fields have been set (by serialized name - uses 'static str from resolution)
        let mut fields_set: BTreeSet<&'static str> = BTreeSet::new();

        // Track currently open path segments: (field_name, is_option, is_variant)
        // The is_variant flag indicates if we've selected a variant at this level
        let mut open_segments: alloc::vec::Vec<(&str, bool, bool)> = alloc::vec::Vec::new();

        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => break,
                ParseEvent::FieldKey(key) => {
                    // Look up field in the resolution
                    if let Some(field_info) = resolution.field(key.name.as_ref()) {
                        let segments = field_info.path.segments();

                        // Check if this path ends with a Variant segment (externally-tagged enum)
                        let ends_with_variant = segments
                            .last()
                            .is_some_and(|s| matches!(s, PathSegment::Variant(_, _)));

                        // Extract field names from the path (excluding trailing Variant)
                        let field_segments: alloc::vec::Vec<&str> = segments
                            .iter()
                            .filter_map(|s| match s {
                                PathSegment::Field(name) => Some(*name),
                                PathSegment::Variant(_, _) => None,
                            })
                            .collect();

                        // Find common prefix with currently open segments
                        let common_len = open_segments
                            .iter()
                            .zip(field_segments.iter())
                            .take_while(|((name, _, _), b)| *name == **b)
                            .count();

                        // Close segments that are no longer needed (in reverse order)
                        while open_segments.len() > common_len {
                            let (_, is_option, _) = open_segments.pop().unwrap();
                            if is_option {
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                            }
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }

                        // Open new segments
                        for &segment in &field_segments[common_len..] {
                            wip = wip
                                .begin_field(segment)
                                .map_err(DeserializeError::reflect)?;
                            let is_option = matches!(wip.shape().def, Def::Option(_));
                            if is_option {
                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                            }
                            open_segments.push((segment, is_option, false));
                        }

                        if ends_with_variant {
                            // For externally-tagged enums: select variant and deserialize content
                            if let Some(PathSegment::Variant(_, variant_name)) = segments.last() {
                                wip = wip
                                    .select_variant_named(variant_name)
                                    .map_err(DeserializeError::reflect)?;
                                // Deserialize the variant's struct content (the nested object)
                                wip = self.deserialize_variant_struct_fields(wip)?;
                            }
                        } else {
                            // Regular field: deserialize into it
                            wip = self.deserialize_into(wip)?;
                        }

                        // Close segments we just opened (we're done with this field)
                        while open_segments.len() > common_len {
                            let (_, is_option, _) = open_segments.pop().unwrap();
                            if is_option {
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                            }
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }

                        // Store the static serialized_name from the resolution
                        fields_set.insert(field_info.serialized_name);
                        continue;
                    }

                    if deny_unknown_fields {
                        return Err(DeserializeError::UnknownField {
                            field: key.name.into_owned(),
                            span: self.last_span,
                            path: None,
                        });
                    } else {
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // Close any remaining open segments
        while let Some((_, is_option, _)) = open_segments.pop() {
            if is_option {
                wip = wip.end().map_err(DeserializeError::reflect)?;
            }
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }

        // Handle missing fields - apply defaults
        // Get all fields sorted by path depth (deepest first for proper default handling)
        let all_fields = resolution.deserialization_order();

        // Track which top-level flatten fields have had any sub-fields set
        let mut touched_top_fields: BTreeSet<&str> = BTreeSet::new();
        for field_name in &fields_set {
            if let Some(info) = resolution.field(field_name)
                && let Some(PathSegment::Field(top)) = info.path.segments().first()
            {
                touched_top_fields.insert(*top);
            }
        }

        for field_info in all_fields {
            if fields_set.contains(field_info.serialized_name) {
                continue;
            }

            // Skip fields that end with Variant - these are handled by enum deserialization
            let ends_with_variant = field_info
                .path
                .segments()
                .last()
                .is_some_and(|s| matches!(s, PathSegment::Variant(_, _)));
            if ends_with_variant {
                continue;
            }

            let path_segments: alloc::vec::Vec<&str> = field_info
                .path
                .segments()
                .iter()
                .filter_map(|s| match s {
                    PathSegment::Field(name) => Some(*name),
                    PathSegment::Variant(_, _) => None,
                })
                .collect();

            // Check if this field's parent was touched
            let first_segment = path_segments.first().copied();
            let parent_touched = first_segment
                .map(|s| touched_top_fields.contains(s))
                .unwrap_or(false);

            // If parent wasn't touched at all, we might default the whole parent
            // For now, handle individual field defaults
            let field_has_default = field_info.field.has_default();
            let field_type_has_default = field_info.value_shape.is(Characteristic::Default);
            let field_is_option = matches!(field_info.value_shape.def, Def::Option(_));

            if field_has_default
                || field_type_has_default
                || field_is_option
                || field_info.field.should_skip_deserializing()
            {
                // Navigate to the field and set default
                for &segment in &path_segments[..path_segments.len().saturating_sub(1)] {
                    wip = wip
                        .begin_field(segment)
                        .map_err(DeserializeError::reflect)?;
                    if matches!(wip.shape().def, Def::Option(_)) {
                        wip = wip.begin_some().map_err(DeserializeError::reflect)?;
                    }
                }

                if let Some(&last) = path_segments.last() {
                    wip = wip.begin_field(last).map_err(DeserializeError::reflect)?;
                    wip = wip.set_default().map_err(DeserializeError::reflect)?;
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }

                // Close the path we opened
                for _ in 0..path_segments.len().saturating_sub(1) {
                    // Need to check if we're in an option
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }
            } else if !parent_touched && path_segments.len() > 1 {
                // Parent wasn't touched and field has no default - this is OK if the whole
                // parent can be defaulted (handled by deferred mode)
                continue;
            } else if field_info.required {
                return Err(DeserializeError::TypeMismatch {
                    expected: "field to be present or have default",
                    got: format!("missing field '{}'", field_info.serialized_name),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        // Finish deferred mode (only if we started it)
        if !already_deferred {
            wip = wip.finish_deferred().map_err(DeserializeError::reflect)?;
        }

        Ok(wip)
    }

    /// Deserialize the struct fields of a variant.
    /// Expects the variant to already be selected.
    fn deserialize_variant_struct_fields(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::StructKind;

        let variant = wip
            .selected_variant()
            .ok_or_else(|| DeserializeError::TypeMismatch {
                expected: "selected variant",
                got: "no variant selected".into(),
                span: self.last_span,
                path: None,
            })?;

        let variant_fields = variant.data.fields;
        let kind = variant.data.kind;

        // Handle based on variant kind
        match kind {
            StructKind::TupleStruct if variant_fields.len() == 1 => {
                // Single-element tuple variant (newtype): deserialize the inner value directly
                wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
                wip = self.deserialize_into(wip)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
                return Ok(wip);
            }
            StructKind::TupleStruct | StructKind::Tuple => {
                // Multi-element tuple variant - not yet supported in this context
                return Err(DeserializeError::Unsupported(
                    "multi-element tuple variants in flatten not yet supported".into(),
                ));
            }
            StructKind::Unit => {
                // Unit variant - nothing to deserialize
                return Ok(wip);
            }
            StructKind::Struct => {
                // Struct variant - fall through to struct deserialization below
            }
        }

        // Struct variant: deserialize as a struct with named fields
        // Expect StructStart for the variant content
        let event = self.expect_event("value")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct start for variant content",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Track which fields have been set
        let num_fields = variant_fields.len();
        let mut fields_set = alloc::vec![false; num_fields];

        // Process all fields
        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => break,
                ParseEvent::FieldKey(key) => {
                    // Look up field in variant's fields
                    let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
                        Self::field_matches_with_namespace(
                            f,
                            key.name.as_ref(),
                            key.namespace.as_deref(),
                            key.location,
                            None,
                        )
                    });

                    if let Some((idx, _field)) = field_info {
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_into(wip)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                        fields_set[idx] = true;
                    } else {
                        // Unknown field - skip
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // Apply defaults for missing fields
        for (idx, field) in variant_fields.iter().enumerate() {
            if fields_set[idx] {
                continue;
            }

            let field_has_default = field.has_default();
            let field_type_has_default = field.shape().is(facet_core::Characteristic::Default);
            let field_is_option = matches!(field.shape().def, Def::Option(_));

            if field_has_default || field_type_has_default {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else if field_is_option {
                wip = wip
                    .begin_nth_field(idx)
                    .map_err(DeserializeError::reflect)?;
                wip = wip.set_default().map_err(DeserializeError::reflect)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            } else if field.should_skip_deserializing() {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else {
                return Err(DeserializeError::TypeMismatch {
                    expected: "field to be present or have default",
                    got: format!("missing field '{}'", field.name),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }

    /// Deserialize into a type with span metadata (like `Spanned<T>`).
    ///
    /// This handles structs that have:
    /// - One or more non-metadata fields (the actual values to deserialize)
    /// - A field with `#[facet(metadata = span)]` to store source location
    ///
    /// The metadata field is populated with a default span since most format parsers
    /// don't track source locations.
    fn deserialize_spanned(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // Find the span metadata field and non-metadata fields
        let Type::User(UserType::Struct(struct_def)) = &shape.ty else {
            return Err(DeserializeError::Unsupported(format!(
                "expected struct with span metadata, found {}",
                shape.type_identifier
            )));
        };

        let span_field = struct_def
            .fields
            .iter()
            .find(|f| f.metadata_kind() == Some("span"))
            .ok_or_else(|| {
                DeserializeError::Unsupported(format!(
                    "expected struct with span metadata field, found {}",
                    shape.type_identifier
                ))
            })?;

        let value_fields: alloc::vec::Vec<_> = struct_def
            .fields
            .iter()
            .filter(|f| !f.is_metadata())
            .collect();

        // Deserialize all non-metadata fields transparently
        // For the common case (Spanned<T> with a single "value" field), this is just one field
        for field in value_fields {
            wip = wip
                .begin_field(field.name)
                .map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }

        // Set the span metadata field to default
        // Most format parsers don't track source spans, so we use a default (unknown) span
        wip = wip
            .begin_field(span_field.name)
            .map_err(DeserializeError::reflect)?;
        wip = wip.set_default().map_err(DeserializeError::reflect)?;
        wip = wip.end().map_err(DeserializeError::reflect)?;

        Ok(wip)
    }

    fn deserialize_tuple(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Get field count for tuple hints (needed for non-self-describing formats like postcard)
        let field_count = match &wip.shape().ty {
            Type::User(UserType::Struct(def)) => def.fields.len(),
            _ => 0, // Unit type or unknown - will be handled below
        };

        // Hint to non-self-describing parsers how many fields to expect
        // Tuples are like positional structs, so we use hint_struct_fields
        self.parser.hint_struct_fields(field_count);

        let event = self.expect_peek("value")?;

        // Special case: newtype structs (single-field tuple structs) can accept scalar values
        // directly without requiring a sequence wrapper. This enables patterns like:
        //   struct Wrapper(i32);
        //   toml: "value = 42"  ->  Wrapper(42)
        if field_count == 1 && matches!(event, ParseEvent::Scalar(_)) {
            // Unwrap into field "0" and deserialize the scalar
            wip = wip.begin_field("0").map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        let event = self.expect_event("value")?;

        // Accept either SequenceStart (JSON arrays) or StructStart (for XML elements or
        // non-self-describing formats like postcard where tuples are positional structs)
        let struct_mode = match event {
            ParseEvent::SequenceStart(_) => false,
            // Ambiguous containers (XML elements) always use struct mode
            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
            // For non-self-describing formats, StructStart(Object) is valid for tuples
            // because hint_struct_fields was called and tuples are positional structs
            ParseEvent::StructStart(_) if !self.parser.is_self_describing() => true,
            // For self-describing formats like TOML/JSON, objects with numeric keys
            // (e.g., { "0" = true, "1" = 1 }) are valid tuple representations
            ParseEvent::StructStart(ContainerKind::Object) => true,
            ParseEvent::StructStart(kind) => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "array",
                    got: kind.name().into(),
                    span: self.last_span,
                    path: None,
                });
            }
            _ => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "sequence start for tuple",
                    got: format!("{event:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        let mut index = 0usize;
        loop {
            let event = self.expect_peek("value")?;

            // Check for end of container
            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                self.expect_event("value")?;
                break;
            }

            // In struct mode, skip FieldKey events
            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
                self.expect_event("value")?;
                continue;
            }

            // Select field by index
            let field_name = alloc::string::ToString::to_string(&index);
            wip = wip
                .begin_field(&field_name)
                .map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            index += 1;
        }

        Ok(wip)
    }

    fn deserialize_enum(
        &mut self,
        wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // Hint to non-self-describing parsers what variant metadata to expect
        if let Type::User(UserType::Enum(enum_def)) = &shape.ty {
            let variant_hints: Vec<crate::EnumVariantHint> = enum_def
                .variants
                .iter()
                .map(|v| crate::EnumVariantHint {
                    name: v.name,
                    kind: v.data.kind,
                    field_count: v.data.fields.len(),
                })
                .collect();
            self.parser.hint_enum(&variant_hints);
        }

        // Check for different tagging modes
        let tag_attr = shape.get_tag_attr();
        let content_attr = shape.get_content_attr();
        let is_numeric = shape.is_numeric();
        let is_untagged = shape.is_untagged();

        if is_numeric {
            return self.deserialize_numeric_enum(wip);
        }

        // Determine tagging mode
        if is_untagged {
            return self.deserialize_enum_untagged(wip);
        }

        if let (Some(tag_key), Some(content_key)) = (tag_attr, content_attr) {
            // Adjacently tagged: {"t": "VariantName", "c": {...}}
            return self.deserialize_enum_adjacently_tagged(wip, tag_key, content_key);
        }

        if let Some(tag_key) = tag_attr {
            // Internally tagged: {"type": "VariantName", ...fields...}
            return self.deserialize_enum_internally_tagged(wip, tag_key);
        }

        // Externally tagged (default): {"VariantName": {...}} or just "VariantName"
        self.deserialize_enum_externally_tagged(wip)
    }

    fn deserialize_enum_externally_tagged(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let event = self.expect_peek("value")?;

        // Check for unit variant (just a string)
        if let ParseEvent::Scalar(
            ScalarValue::Str(variant_name) | ScalarValue::StringlyTyped(variant_name),
        ) = &event
        {
            self.expect_event("value")?;
            wip = wip
                .select_variant_named(variant_name)
                .map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Otherwise expect a struct { VariantName: ... }
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "string or struct for enum",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        self.expect_event("value")?; // consume StructStart

        // Get the variant name
        let event = self.expect_event("value")?;
        let variant_name = match event {
            ParseEvent::FieldKey(key) => key.name,
            other => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "variant name",
                    got: format!("{other:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        wip = wip
            .select_variant_named(&variant_name)
            .map_err(DeserializeError::reflect)?;

        // Deserialize the variant content
        wip = self.deserialize_enum_variant_content(wip)?;

        // Consume StructEnd
        let event = self.expect_event("value")?;
        if !matches!(event, ParseEvent::StructEnd) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct end after enum variant",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        Ok(wip)
    }

    fn deserialize_enum_internally_tagged(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        tag_key: &str,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::Characteristic;

        // Step 1: Probe to find the tag value (handles out-of-order fields)
        let probe = self
            .parser
            .begin_probe()
            .map_err(DeserializeError::Parser)?;
        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;

        let variant_name = Self::find_tag_value(&evidence, tag_key)
            .ok_or_else(|| DeserializeError::TypeMismatch {
                expected: "tag field in internally tagged enum",
                got: format!("missing '{tag_key}' field"),
                span: self.last_span,
                path: None,
            })?
            .to_string();

        // Step 2: Consume StructStart
        let event = self.expect_event("value")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct for internally tagged enum",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Step 3: Select the variant
        wip = wip
            .select_variant_named(&variant_name)
            .map_err(DeserializeError::reflect)?;

        // Get the selected variant info
        let variant = wip
            .selected_variant()
            .ok_or_else(|| DeserializeError::TypeMismatch {
                expected: "selected variant",
                got: "no variant selected".into(),
                span: self.last_span,
                path: None,
            })?;

        let variant_fields = variant.data.fields;

        // Check if this is a unit variant (no fields)
        if variant_fields.is_empty() || variant.data.kind == StructKind::Unit {
            // Consume remaining fields in the object
            loop {
                let event = self.expect_event("value")?;
                match event {
                    ParseEvent::StructEnd => break,
                    ParseEvent::FieldKey(_) => {
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                    other => {
                        return Err(DeserializeError::TypeMismatch {
                            expected: "field key or struct end",
                            got: format!("{other:?}"),
                            span: self.last_span,
                            path: None,
                        });
                    }
                }
            }
            return Ok(wip);
        }

        // Track which fields have been set
        let num_fields = variant_fields.len();
        let mut fields_set = alloc::vec![false; num_fields];

        // Step 4: Process all fields (they can come in any order now)
        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => break,
                ParseEvent::FieldKey(key) => {
                    // Skip the tag field - already used
                    if key.name.as_ref() == tag_key {
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                        continue;
                    }

                    // Look up field in variant's fields
                    // Uses namespace-aware matching when namespace is present
                    let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
                        Self::field_matches_with_namespace(
                            f,
                            key.name.as_ref(),
                            key.namespace.as_deref(),
                            key.location,
                            None, // Enums don't have ns_all
                        )
                    });

                    if let Some((idx, _field)) = field_info {
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_into(wip)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                        fields_set[idx] = true;
                    } else {
                        // Unknown field - skip
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // Apply defaults for missing fields
        for (idx, field) in variant_fields.iter().enumerate() {
            if fields_set[idx] {
                continue;
            }

            let field_has_default = field.has_default();
            let field_type_has_default = field.shape().is(Characteristic::Default);
            let field_is_option = matches!(field.shape().def, Def::Option(_));

            if field_has_default || field_type_has_default {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else if field_is_option {
                wip = wip
                    .begin_nth_field(idx)
                    .map_err(DeserializeError::reflect)?;
                wip = wip.set_default().map_err(DeserializeError::reflect)?;
                wip = wip.end().map_err(DeserializeError::reflect)?;
            } else if field.should_skip_deserializing() {
                wip = wip
                    .set_nth_field_to_default(idx)
                    .map_err(DeserializeError::reflect)?;
            } else {
                return Err(DeserializeError::TypeMismatch {
                    expected: "field to be present or have default",
                    got: format!("missing field '{}'", field.name),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }

    /// Helper to find a tag value from field evidence.
    fn find_tag_value<'a>(
        evidence: &'a [crate::FieldEvidence<'input>],
        tag_key: &str,
    ) -> Option<&'a str> {
        evidence
            .iter()
            .find(|e| e.name == tag_key)
            .and_then(|e| match &e.scalar_value {
                Some(ScalarValue::Str(s) | ScalarValue::StringlyTyped(s)) => Some(s.as_ref()),
                _ => None,
            })
    }

    /// Helper to collect all evidence from a probe stream.
    fn collect_evidence<S: crate::ProbeStream<'input, Error = P::Error>>(
        mut probe: S,
    ) -> Result<alloc::vec::Vec<crate::FieldEvidence<'input>>, P::Error> {
        let mut evidence = alloc::vec::Vec::new();
        while let Some(ev) = probe.next()? {
            evidence.push(ev);
        }
        Ok(evidence)
    }

    fn deserialize_enum_adjacently_tagged(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        tag_key: &str,
        content_key: &str,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Step 1: Probe to find the tag value (handles out-of-order fields)
        let probe = self
            .parser
            .begin_probe()
            .map_err(DeserializeError::Parser)?;
        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;

        let variant_name = Self::find_tag_value(&evidence, tag_key)
            .ok_or_else(|| DeserializeError::TypeMismatch {
                expected: "tag field in adjacently tagged enum",
                got: format!("missing '{tag_key}' field"),
                span: self.last_span,
                path: None,
            })?
            .to_string();

        // Step 2: Consume StructStart
        let event = self.expect_event("value")?;
        if !matches!(event, ParseEvent::StructStart(_)) {
            return Err(DeserializeError::TypeMismatch {
                expected: "struct for adjacently tagged enum",
                got: format!("{event:?}"),
                span: self.last_span,
                path: None,
            });
        }

        // Step 3: Select the variant
        wip = wip
            .select_variant_named(&variant_name)
            .map_err(DeserializeError::reflect)?;

        // Step 4: Process fields in any order
        let mut content_seen = false;
        loop {
            let event = self.expect_event("value")?;
            match event {
                ParseEvent::StructEnd => break,
                ParseEvent::FieldKey(key) => {
                    if key.name.as_ref() == tag_key {
                        // Skip the tag field - already used
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    } else if key.name.as_ref() == content_key {
                        // Deserialize the content
                        wip = self.deserialize_enum_variant_content(wip)?;
                        content_seen = true;
                    } else {
                        // Unknown field - skip
                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
                    }
                }
                other => {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "field key or struct end",
                        got: format!("{other:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }
            }
        }

        // If no content field was present, it's a unit variant (already selected above)
        if !content_seen {
            // Check if the variant expects content
            let variant = wip.selected_variant();
            if let Some(v) = variant
                && v.data.kind != StructKind::Unit
                && !v.data.fields.is_empty()
            {
                return Err(DeserializeError::TypeMismatch {
                    expected: "content field for non-unit variant",
                    got: format!("missing '{content_key}' field"),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }

    fn deserialize_enum_variant_content(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_core::Characteristic;

        // Get the selected variant's info
        let variant = wip
            .selected_variant()
            .ok_or_else(|| DeserializeError::TypeMismatch {
                expected: "selected variant",
                got: "no variant selected".into(),
                span: self.last_span,
                path: None,
            })?;

        let variant_kind = variant.data.kind;
        let variant_fields = variant.data.fields;

        match variant_kind {
            StructKind::Unit => {
                // Unit variant - normally nothing to deserialize
                // But some formats (like TOML with [VariantName]) might emit an empty struct
                // Check if there's a StructStart that we need to consume
                let event = self.expect_peek("value")?;
                if matches!(event, ParseEvent::StructStart(_)) {
                    self.expect_event("value")?; // consume StructStart
                    // Expect immediate StructEnd for empty struct
                    let end_event = self.expect_event("value")?;
                    if !matches!(end_event, ParseEvent::StructEnd) {
                        return Err(DeserializeError::TypeMismatch {
                            expected: "empty struct for unit variant",
                            got: format!("{end_event:?}"),
                            span: self.last_span,
                            path: None,
                        });
                    }
                }
                Ok(wip)
            }
            StructKind::Tuple | StructKind::TupleStruct => {
                if variant_fields.len() == 1 {
                    // Newtype variant - content is the single field's value
                    wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
                    wip = self.deserialize_into(wip)?;
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                } else {
                    // Multi-field tuple variant - expect array or struct (for XML/TOML with numeric keys)
                    let event = self.expect_event("value")?;

                    // Accept SequenceStart (JSON arrays), ambiguous StructStart (XML elements),
                    // or Object StructStart (TOML/JSON with numeric keys like "0", "1")
                    let struct_mode = match event {
                        ParseEvent::SequenceStart(_) => false,
                        ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
                        // Accept objects with numeric keys as valid tuple representations
                        ParseEvent::StructStart(ContainerKind::Object) => true,
                        ParseEvent::StructStart(kind) => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "array",
                                got: kind.name().into(),
                                span: self.last_span,
                                path: None,
                            });
                        }
                        _ => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "sequence for tuple variant",
                                got: format!("{event:?}"),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    };

                    let mut idx = 0;
                    while idx < variant_fields.len() {
                        // In struct mode, skip FieldKey events
                        if struct_mode {
                            let event = self.expect_peek("value")?;
                            if matches!(event, ParseEvent::FieldKey(_)) {
                                self.expect_event("value")?;
                                continue;
                            }
                        }

                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_into(wip)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                        idx += 1;
                    }

                    let event = self.expect_event("value")?;
                    if !matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                        return Err(DeserializeError::TypeMismatch {
                            expected: "sequence end for tuple variant",
                            got: format!("{event:?}"),
                            span: self.last_span,
                            path: None,
                        });
                    }
                }
                Ok(wip)
            }
            StructKind::Struct => {
                // Struct variant - expect object with fields
                let event = self.expect_event("value")?;
                if !matches!(event, ParseEvent::StructStart(_)) {
                    return Err(DeserializeError::TypeMismatch {
                        expected: "struct for struct variant",
                        got: format!("{event:?}"),
                        span: self.last_span,
                        path: None,
                    });
                }

                let num_fields = variant_fields.len();
                let mut fields_set = alloc::vec![false; num_fields];
                let mut ordered_field_index = 0usize;

                loop {
                    let event = self.expect_event("value")?;
                    match event {
                        ParseEvent::StructEnd => break,
                        ParseEvent::OrderedField => {
                            // Non-self-describing formats emit OrderedField events in order
                            let idx = ordered_field_index;
                            ordered_field_index += 1;
                            if idx < num_fields {
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = self.deserialize_into(wip)?;
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                                fields_set[idx] = true;
                            }
                        }
                        ParseEvent::FieldKey(key) => {
                            // Uses namespace-aware matching when namespace is present
                            let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
                                Self::field_matches_with_namespace(
                                    f,
                                    key.name.as_ref(),
                                    key.namespace.as_deref(),
                                    key.location,
                                    None, // Enums don't have ns_all
                                )
                            });

                            if let Some((idx, _field)) = field_info {
                                wip = wip
                                    .begin_nth_field(idx)
                                    .map_err(DeserializeError::reflect)?;
                                wip = self.deserialize_into(wip)?;
                                wip = wip.end().map_err(DeserializeError::reflect)?;
                                fields_set[idx] = true;
                            } else {
                                // Unknown field - skip
                                self.parser.skip_value().map_err(DeserializeError::Parser)?;
                            }
                        }
                        other => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "field key, ordered field, or struct end",
                                got: format!("{other:?}"),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    }
                }

                // Apply defaults for missing fields
                for (idx, field) in variant_fields.iter().enumerate() {
                    if fields_set[idx] {
                        continue;
                    }

                    let field_has_default = field.has_default();
                    let field_type_has_default = field.shape().is(Characteristic::Default);
                    let field_is_option = matches!(field.shape().def, Def::Option(_));

                    if field_has_default || field_type_has_default {
                        wip = wip
                            .set_nth_field_to_default(idx)
                            .map_err(DeserializeError::reflect)?;
                    } else if field_is_option {
                        wip = wip
                            .begin_nth_field(idx)
                            .map_err(DeserializeError::reflect)?;
                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
                        wip = wip.end().map_err(DeserializeError::reflect)?;
                    } else if field.should_skip_deserializing() {
                        wip = wip
                            .set_nth_field_to_default(idx)
                            .map_err(DeserializeError::reflect)?;
                    } else {
                        return Err(DeserializeError::TypeMismatch {
                            expected: "field to be present or have default",
                            got: format!("missing field '{}'", field.name),
                            span: self.last_span,
                            path: None,
                        });
                    }
                }

                Ok(wip)
            }
        }
    }

    fn deserialize_numeric_enum(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let event = self.parser.peek_event().map_err(DeserializeError::Parser)?;

        if let Some(ParseEvent::Scalar(scalar)) = event {
            let span = self.last_span;
            wip = match scalar {
                ScalarValue::I64(discriminant) => {
                    wip.select_variant(discriminant)
                        .map_err(|error| DeserializeError::Reflect {
                            error,
                            span,
                            path: None,
                        })?
                }
                ScalarValue::U64(discriminant) => {
                    wip.select_variant(discriminant as i64).map_err(|error| {
                        DeserializeError::Reflect {
                            error,
                            span,
                            path: None,
                        }
                    })?
                }
                ScalarValue::Str(str_discriminant)
                | ScalarValue::StringlyTyped(str_discriminant) => {
                    let discriminant =
                        str_discriminant
                            .parse()
                            .map_err(|_| DeserializeError::TypeMismatch {
                                expected: "String representing an integer (i64)",
                                got: str_discriminant.to_string(),
                                span: self.last_span,
                                path: None,
                            })?;
                    wip.select_variant(discriminant)
                        .map_err(|error| DeserializeError::Reflect {
                            error,
                            span,
                            path: None,
                        })?
                }
                _ => {
                    return Err(DeserializeError::Unsupported(
                        "Unexpected ScalarValue".to_string(),
                    ));
                }
            };
            self.parser.next_event().map_err(DeserializeError::Parser)?;
            Ok(wip)
        } else {
            Err(DeserializeError::Unsupported(
                "Expected integer value".to_string(),
            ))
        }
    }

    fn deserialize_enum_untagged(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        use facet_solver::VariantsByFormat;

        let shape = wip.shape();
        let variants_by_format = VariantsByFormat::from_shape(shape).ok_or_else(|| {
            DeserializeError::Unsupported("expected enum type for untagged".into())
        })?;

        let event = self.expect_peek("value")?;

        match &event {
            ParseEvent::Scalar(scalar) => {
                // Try unit variants for null
                if matches!(scalar, ScalarValue::Null)
                    && let Some(variant) = variants_by_format.unit_variants.first()
                {
                    wip = wip
                        .select_variant_named(variant.name)
                        .map_err(DeserializeError::reflect)?;
                    // Consume the null
                    self.expect_event("value")?;
                    return Ok(wip);
                }

                // Try unit variants for string values (match variant name)
                // This handles untagged enums with only unit variants like:
                // #[facet(untagged)] enum Color { Red, Green, Blue }
                // which deserialize from "Red", "Green", "Blue"
                if let ScalarValue::Str(s) | ScalarValue::StringlyTyped(s) = scalar {
                    // For StringlyTyped, handle "null" specially - it should match
                    // unit variants named "Null" (case-insensitive) since stringly
                    // formats like XML don't have a native null type.
                    let is_stringly_null = matches!(scalar, ScalarValue::StringlyTyped(_))
                        && s.as_ref().eq_ignore_ascii_case("null");

                    for variant in &variants_by_format.unit_variants {
                        // Match against variant name or rename attribute
                        let variant_display_name = variant
                            .get_builtin_attr("rename")
                            .and_then(|attr| attr.get_as::<&str>().copied())
                            .unwrap_or(variant.name);

                        // For StringlyTyped("null"), match any variant named "Null" or "null"
                        let matches = if is_stringly_null {
                            variant_display_name.eq_ignore_ascii_case("null")
                        } else {
                            s.as_ref() == variant_display_name
                        };

                        if matches {
                            wip = wip
                                .select_variant_named(variant.name)
                                .map_err(DeserializeError::reflect)?;
                            // Consume the string
                            self.expect_event("value")?;
                            return Ok(wip);
                        }
                    }
                }

                // ┌─────────────────────────────────────────────────────────────────┐
                // │ UNTAGGED ENUM SCALAR VARIANT DISCRIMINATION                       │
                // └─────────────────────────────────────────────────────────────────┘
                //
                // For untagged enums, we try to match scalar values against variant
                // types. Since we can't backtrack parser state, we use the first
                // variant that matches.
                //
                // ## Regular Scalars (I64, Str, Bool, etc.)
                //
                // For typed scalars, we simply try variants in definition order.
                // The first matching variant wins. This is predictable and matches
                // user expectations based on how they defined their enum.
                //
                // ## StringlyTyped Scalars (from XML and other text-based formats)
                //
                // StringlyTyped represents a value that arrived as text but may
                // encode a more specific type. For example, XML `<value>42</value>`
                // produces StringlyTyped("42"), which could be:
                //   - A String (any text is valid)
                //   - A u64 (if it parses as a number)
                //   - NOT a bool (doesn't parse as true/false)
                //
                // The problem: String always matches StringlyTyped, so if String
                // comes first in the enum definition, it would always win.
                //
                // Solution: Two-tier matching for StringlyTyped:
                //
                //   **Tier 1 (Parseable types)**: Try non-string types that can
                //   parse the value (u64, i32, bool, IpAddr, etc.). First match wins.
                //
                //   **Tier 2 (String fallback)**: If no parseable type matched,
                //   fall back to String/Str/CowStr variants.
                //
                // This ensures StringlyTyped("42") matches Number(u64) over
                // String(String), regardless of definition order, while still
                // allowing String as a catch-all fallback.
                //
                // Example:
                //   #[facet(untagged)]
                //   enum Value {
                //       Text(String),    // Tier 2: fallback
                //       Number(u64),     // Tier 1: parseable
                //       Flag(bool),      // Tier 1: parseable
                //   }
                //
                //   StringlyTyped("42")    → Number(42)   (parses as u64)
                //   StringlyTyped("true")  → Flag(true)   (parses as bool)
                //   StringlyTyped("hello") → Text(hello)  (fallback to String)

                let is_stringly_typed = matches!(scalar, ScalarValue::StringlyTyped(_));

                // Tier 1: Try variants that match the scalar type
                // For StringlyTyped, skip string types (they're Tier 2 fallback)
                for (variant, inner_shape) in &variants_by_format.scalar_variants {
                    // For StringlyTyped, defer String-like types to Tier 2
                    if is_stringly_typed
                        && let Some(st) = inner_shape.scalar_type()
                        && matches!(
                            st,
                            facet_core::ScalarType::String
                                | facet_core::ScalarType::Str
                                | facet_core::ScalarType::CowStr
                        )
                    {
                        continue;
                    }

                    if self.scalar_matches_shape(scalar, inner_shape) {
                        wip = wip
                            .select_variant_named(variant.name)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_enum_variant_content(wip)?;
                        return Ok(wip);
                    }
                }

                // Tier 2: For StringlyTyped, try string types as fallback
                if is_stringly_typed {
                    for (variant, inner_shape) in &variants_by_format.scalar_variants {
                        if let Some(st) = inner_shape.scalar_type()
                            && matches!(
                                st,
                                facet_core::ScalarType::String
                                    | facet_core::ScalarType::Str
                                    | facet_core::ScalarType::CowStr
                            )
                            && self.scalar_matches_shape(scalar, inner_shape)
                        {
                            wip = wip
                                .select_variant_named(variant.name)
                                .map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_enum_variant_content(wip)?;
                            return Ok(wip);
                        }
                    }
                }

                // Try other scalar variants that don't match primitive types.
                // This handles cases like newtype variants wrapping enums with #[facet(rename)]:
                //   #[facet(untagged)]
                //   enum EditionOrWorkspace {
                //       Edition(Edition),  // Edition is an enum with #[facet(rename = "2024")]
                //       Workspace(WorkspaceRef),
                //   }
                // When deserializing "2024", Edition doesn't match as a primitive scalar,
                // but it CAN be deserialized from the string via its renamed unit variants.
                for (variant, inner_shape) in &variants_by_format.scalar_variants {
                    if !self.scalar_matches_shape(scalar, inner_shape) {
                        wip = wip
                            .select_variant_named(variant.name)
                            .map_err(DeserializeError::reflect)?;
                        // Try to deserialize - if this fails, it will bubble up as an error.
                        // TODO: Implement proper variant trying with backtracking for better error messages
                        wip = self.deserialize_enum_variant_content(wip)?;
                        return Ok(wip);
                    }
                }

                Err(DeserializeError::TypeMismatch {
                    expected: "matching untagged variant for scalar",
                    got: format!("{:?}", scalar),
                    span: self.last_span,
                    path: None,
                })
            }
            ParseEvent::StructStart(_) => {
                // For struct input, use solve_variant for proper field-based matching
                match crate::solve_variant(shape, &mut self.parser) {
                    Ok(Some(outcome)) => {
                        // Successfully identified which variant matches based on fields
                        let resolution = outcome.resolution();
                        // For top-level untagged enum, there should be exactly one variant selection
                        let variant_name = resolution
                            .variant_selections()
                            .first()
                            .map(|vs| vs.variant_name)
                            .ok_or_else(|| {
                                DeserializeError::Unsupported(
                                    "solved resolution has no variant selection".into(),
                                )
                            })?;
                        wip = wip
                            .select_variant_named(variant_name)
                            .map_err(DeserializeError::reflect)?;
                        wip = self.deserialize_enum_variant_content(wip)?;
                        Ok(wip)
                    }
                    Ok(None) => {
                        // No variant matched - fall back to trying the first struct variant
                        // (we can't backtrack parser state to try multiple variants)
                        if let Some(variant) = variants_by_format.struct_variants.first() {
                            wip = wip
                                .select_variant_named(variant.name)
                                .map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_enum_variant_content(wip)?;
                            Ok(wip)
                        } else {
                            Err(DeserializeError::Unsupported(
                                "no struct variant found for untagged enum with struct input"
                                    .into(),
                            ))
                        }
                    }
                    Err(_) => Err(DeserializeError::Unsupported(
                        "failed to solve variant for untagged enum".into(),
                    )),
                }
            }
            ParseEvent::SequenceStart(_) => {
                // For sequence input, use first tuple variant
                if let Some((variant, _arity)) = variants_by_format.tuple_variants.first() {
                    wip = wip
                        .select_variant_named(variant.name)
                        .map_err(DeserializeError::reflect)?;
                    wip = self.deserialize_enum_variant_content(wip)?;
                    return Ok(wip);
                }

                Err(DeserializeError::Unsupported(
                    "no tuple variant found for untagged enum with sequence input".into(),
                ))
            }
            _ => Err(DeserializeError::TypeMismatch {
                expected: "scalar, struct, or sequence for untagged enum",
                got: format!("{:?}", event),
                span: self.last_span,
                path: None,
            }),
        }
    }

    fn scalar_matches_shape(
        &self,
        scalar: &ScalarValue<'input>,
        shape: &'static facet_core::Shape,
    ) -> bool {
        use facet_core::ScalarType;

        let Some(scalar_type) = shape.scalar_type() else {
            // Not a scalar type - check for Option wrapping null
            if matches!(scalar, ScalarValue::Null) {
                return matches!(shape.def, Def::Option(_));
            }
            return false;
        };

        match scalar {
            ScalarValue::Bool(_) => matches!(scalar_type, ScalarType::Bool),
            ScalarValue::Char(_) => matches!(scalar_type, ScalarType::Char),
            ScalarValue::I64(val) => {
                // I64 matches signed types directly
                if matches!(
                    scalar_type,
                    ScalarType::I8
                        | ScalarType::I16
                        | ScalarType::I32
                        | ScalarType::I64
                        | ScalarType::I128
                        | ScalarType::ISize
                ) {
                    return true;
                }

                // I64 can also match unsigned types if the value is non-negative and in range
                // This handles TOML's requirement to represent all integers as i64
                if *val >= 0 {
                    let uval = *val as u64;
                    match scalar_type {
                        ScalarType::U8 => uval <= u8::MAX as u64,
                        ScalarType::U16 => uval <= u16::MAX as u64,
                        ScalarType::U32 => uval <= u32::MAX as u64,
                        ScalarType::U64 | ScalarType::U128 | ScalarType::USize => true,
                        _ => false,
                    }
                } else {
                    false
                }
            }
            ScalarValue::U64(_) => matches!(
                scalar_type,
                ScalarType::U8
                    | ScalarType::U16
                    | ScalarType::U32
                    | ScalarType::U64
                    | ScalarType::U128
                    | ScalarType::USize
            ),
            ScalarValue::U128(_) => matches!(scalar_type, ScalarType::U128 | ScalarType::I128),
            ScalarValue::I128(_) => matches!(scalar_type, ScalarType::I128 | ScalarType::U128),
            ScalarValue::F64(_) => matches!(scalar_type, ScalarType::F32 | ScalarType::F64),
            ScalarValue::Str(s) => {
                // String scalars match string types directly
                if matches!(
                    scalar_type,
                    ScalarType::String | ScalarType::Str | ScalarType::CowStr | ScalarType::Char
                ) {
                    return true;
                }
                // For other scalar types, check if the shape has a parse function
                // and if so, try parsing the string to see if it would succeed.
                // This enables untagged enums to correctly match string values like "4.625"
                // to the appropriate variant (f64 vs i64).
                // See #1615 for discussion of this double-parse pattern.
                #[allow(unsafe_code)]
                if shape.vtable.has_parse()
                    && shape
                        .layout
                        .sized_layout()
                        .is_ok_and(|layout| layout.size() <= 128)
                {
                    // Attempt to parse - this is a probe, not the actual deserialization
                    let mut temp = [0u8; 128];
                    let temp_ptr = facet_core::PtrMut::new(temp.as_mut_ptr());
                    // SAFETY: temp buffer is properly aligned and sized for this shape
                    if let Some(Ok(())) = unsafe { shape.call_parse(s.as_ref(), temp_ptr) } {
                        // Parse succeeded - drop the temp value
                        // SAFETY: we just successfully parsed into temp_ptr
                        unsafe { shape.call_drop_in_place(temp_ptr) };
                        return true;
                    }
                }
                false
            }
            ScalarValue::Bytes(_) => {
                // Bytes don't have a ScalarType - would need to check for Vec<u8> or [u8]
                false
            }
            ScalarValue::Null => {
                // Null matches Unit type
                matches!(scalar_type, ScalarType::Unit)
            }
            ScalarValue::StringlyTyped(s) => {
                // StringlyTyped can match any scalar type - it will be parsed.
                // Use the same logic as Str: check if parse would succeed.
                #[allow(unsafe_code)]
                if shape.vtable.has_parse()
                    && shape
                        .layout
                        .sized_layout()
                        .is_ok_and(|layout| layout.size() <= 128)
                {
                    // Attempt to parse - this is a probe, not the actual deserialization
                    let mut temp = [0u8; 128];
                    let temp_ptr = facet_core::PtrMut::new(temp.as_mut_ptr());
                    // SAFETY: temp buffer is properly aligned and sized for this shape
                    if let Some(Ok(())) = unsafe { shape.call_parse(s.as_ref(), temp_ptr) } {
                        // Parse succeeded - drop the temp value
                        // SAFETY: we just successfully parsed into temp_ptr
                        unsafe { shape.call_drop_in_place(temp_ptr) };
                        return true;
                    }
                }
                // StringlyTyped also matches string types directly
                matches!(
                    scalar_type,
                    ScalarType::String | ScalarType::Str | ScalarType::CowStr | ScalarType::Char
                )
            }
        }
    }

    fn deserialize_list(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Hint to non-self-describing parsers that a sequence is expected
        self.parser.hint_sequence();

        let event = self.expect_event("value")?;

        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
        // In struct mode, we skip FieldKey events and treat values as sequence items
        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
        let struct_mode = match event {
            ParseEvent::SequenceStart(_) => false,
            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
            ParseEvent::StructStart(kind) => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "array",
                    got: kind.name().into(),
                    span: self.last_span,
                    path: None,
                });
            }
            _ => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "sequence start",
                    got: format!("{event:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        // Initialize the list
        wip = wip.begin_list().map_err(DeserializeError::reflect)?;

        loop {
            let event = self.expect_peek("value")?;

            // Check for end of container
            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                self.expect_event("value")?;
                break;
            }

            // In struct mode, skip FieldKey events (they're just labels for items)
            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
                self.expect_event("value")?;
                continue;
            }

            wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }

        Ok(wip)
    }

    fn deserialize_array(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Get the fixed array length from the type definition
        let array_len = match &wip.shape().def {
            Def::Array(array_def) => array_def.n,
            _ => {
                return Err(DeserializeError::Unsupported(
                    "deserialize_array called on non-array type".into(),
                ));
            }
        };

        // Hint to non-self-describing parsers that a fixed-size array is expected
        // (unlike hint_sequence, this doesn't read a length prefix)
        self.parser.hint_array(array_len);

        let event = self.expect_event("value")?;

        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
        let struct_mode = match event {
            ParseEvent::SequenceStart(_) => false,
            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
            ParseEvent::StructStart(kind) => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "array",
                    got: kind.name().into(),
                    span: self.last_span,
                    path: None,
                });
            }
            _ => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "sequence start for array",
                    got: format!("{event:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        // Transition to Array tracker state. This is important for empty arrays
        // like [u8; 0] which have no elements to initialize but still need
        // their tracker state set correctly for require_full_initialization to pass.
        wip = wip.begin_array().map_err(DeserializeError::reflect)?;

        let mut index = 0usize;
        loop {
            let event = self.expect_peek("value")?;

            // Check for end of container
            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                self.expect_event("value")?;
                break;
            }

            // In struct mode, skip FieldKey events
            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
                self.expect_event("value")?;
                continue;
            }

            wip = wip
                .begin_nth_field(index)
                .map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            index += 1;
        }

        Ok(wip)
    }

    fn deserialize_set(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Hint to non-self-describing parsers that a sequence is expected
        self.parser.hint_sequence();

        let event = self.expect_event("value")?;

        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
        let struct_mode = match event {
            ParseEvent::SequenceStart(_) => false,
            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
            ParseEvent::StructStart(kind) => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "array",
                    got: kind.name().into(),
                    span: self.last_span,
                    path: None,
                });
            }
            _ => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "sequence start for set",
                    got: format!("{event:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        };

        // Initialize the set
        wip = wip.begin_set().map_err(DeserializeError::reflect)?;

        loop {
            let event = self.expect_peek("value")?;

            // Check for end of container
            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
                self.expect_event("value")?;
                break;
            }

            // In struct mode, skip FieldKey events
            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
                self.expect_event("value")?;
                continue;
            }

            wip = wip.begin_set_item().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_into(wip)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
        }

        Ok(wip)
    }

    fn deserialize_map(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // For non-self-describing formats, hint that a map is expected
        self.parser.hint_map();

        let event = self.expect_event("value")?;

        // Initialize the map
        wip = wip.begin_map().map_err(DeserializeError::reflect)?;

        // Handle both self-describing (StructStart) and non-self-describing (SequenceStart) formats
        match event {
            ParseEvent::StructStart(_) => {
                // Self-describing format (e.g., JSON): maps are represented as objects
                loop {
                    let event = self.expect_event("value")?;
                    match event {
                        ParseEvent::StructEnd => break,
                        ParseEvent::FieldKey(key) => {
                            // Begin key
                            wip = wip.begin_key().map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_map_key(wip, key.name)?;
                            wip = wip.end().map_err(DeserializeError::reflect)?;

                            // Begin value
                            wip = wip.begin_value().map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_into(wip)?;
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }
                        other => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "field key or struct end for map",
                                got: format!("{other:?}"),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    }
                }
            }
            ParseEvent::SequenceStart(_) => {
                // Non-self-describing format (e.g., postcard): maps are sequences of key-value pairs
                loop {
                    let event = self.expect_peek("value")?;
                    match event {
                        ParseEvent::SequenceEnd => {
                            self.expect_event("value")?;
                            break;
                        }
                        ParseEvent::OrderedField => {
                            self.expect_event("value")?;

                            // Deserialize key
                            wip = wip.begin_key().map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_into(wip)?;
                            wip = wip.end().map_err(DeserializeError::reflect)?;

                            // Deserialize value
                            wip = wip.begin_value().map_err(DeserializeError::reflect)?;
                            wip = self.deserialize_into(wip)?;
                            wip = wip.end().map_err(DeserializeError::reflect)?;
                        }
                        other => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "ordered field or sequence end for map",
                                got: format!("{other:?}"),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    }
                }
            }
            other => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "struct start or sequence start for map",
                    got: format!("{other:?}"),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }

    fn deserialize_scalar(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        // Hint to non-self-describing parsers what scalar type is expected
        let shape = wip.shape();

        // First, try hint_opaque_scalar for types that may have format-specific
        // binary representations (e.g., UUID as 16 raw bytes in postcard)
        let opaque_handled = match shape.type_identifier {
            // Standard primitives are never opaque
            "bool" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32"
            | "i64" | "i128" | "isize" | "f32" | "f64" | "String" | "&str" | "char" => false,
            // For all other scalar types, ask the parser if it handles them specially
            _ => self.parser.hint_opaque_scalar(shape.type_identifier, shape),
        };

        // If the parser didn't handle the opaque type, fall back to standard hints
        if !opaque_handled {
            let hint = match shape.type_identifier {
                "bool" => Some(ScalarTypeHint::Bool),
                "u8" => Some(ScalarTypeHint::U8),
                "u16" => Some(ScalarTypeHint::U16),
                "u32" => Some(ScalarTypeHint::U32),
                "u64" => Some(ScalarTypeHint::U64),
                "u128" => Some(ScalarTypeHint::U128),
                "usize" => Some(ScalarTypeHint::Usize),
                "i8" => Some(ScalarTypeHint::I8),
                "i16" => Some(ScalarTypeHint::I16),
                "i32" => Some(ScalarTypeHint::I32),
                "i64" => Some(ScalarTypeHint::I64),
                "i128" => Some(ScalarTypeHint::I128),
                "isize" => Some(ScalarTypeHint::Isize),
                "f32" => Some(ScalarTypeHint::F32),
                "f64" => Some(ScalarTypeHint::F64),
                "String" | "&str" => Some(ScalarTypeHint::String),
                "char" => Some(ScalarTypeHint::Char),
                // For unknown scalar types, check if they implement FromStr
                // (e.g., camino::Utf8PathBuf, types not handled by hint_opaque_scalar)
                _ if shape.is_from_str() => Some(ScalarTypeHint::String),
                _ => None,
            };
            if let Some(hint) = hint {
                self.parser.hint_scalar_type(hint);
            }
        }

        let event = self.expect_event("value")?;

        match event {
            ParseEvent::Scalar(scalar) => {
                wip = self.set_scalar(wip, scalar)?;
                Ok(wip)
            }
            ParseEvent::StructStart(container_kind) => {
                Err(DeserializeError::ExpectedScalarGotStruct {
                    expected_shape: shape,
                    got_container: container_kind,
                    span: self.last_span,
                    path: None,
                })
            }
            other => Err(DeserializeError::TypeMismatch {
                expected: "scalar value",
                got: format!("{other:?}"),
                span: self.last_span,
                path: None,
            }),
        }
    }

    fn set_scalar(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        scalar: ScalarValue<'input>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();
        // Capture the span for error reporting - this is where the scalar value was parsed
        let span = self.last_span;
        let reflect_err = |e: ReflectError| DeserializeError::Reflect {
            error: e,
            span,
            path: None,
        };

        match scalar {
            ScalarValue::Null => {
                wip = wip.set_default().map_err(&reflect_err)?;
            }
            ScalarValue::Bool(b) => {
                wip = wip.set(b).map_err(&reflect_err)?;
            }
            ScalarValue::Char(c) => {
                wip = wip.set(c).map_err(&reflect_err)?;
            }
            ScalarValue::I64(n) => {
                // Handle signed types
                if shape.type_identifier == "i8" {
                    wip = wip.set(n as i8).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i16" {
                    wip = wip.set(n as i16).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i32" {
                    wip = wip.set(n as i32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i64" {
                    wip = wip.set(n).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i128" {
                    wip = wip.set(n as i128).map_err(&reflect_err)?;
                } else if shape.type_identifier == "isize" {
                    wip = wip.set(n as isize).map_err(&reflect_err)?;
                // Handle unsigned types (I64 can fit in unsigned if non-negative)
                } else if shape.type_identifier == "u8" {
                    wip = wip.set(n as u8).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u16" {
                    wip = wip.set(n as u16).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u32" {
                    wip = wip.set(n as u32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u64" {
                    wip = wip.set(n as u64).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u128" {
                    wip = wip.set(n as u128).map_err(&reflect_err)?;
                } else if shape.type_identifier == "usize" {
                    wip = wip.set(n as usize).map_err(&reflect_err)?;
                // Handle floats
                } else if shape.type_identifier == "f32" {
                    wip = wip.set(n as f32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "f64" {
                    wip = wip.set(n as f64).map_err(&reflect_err)?;
                // Handle String - stringify the number
                } else if shape.type_identifier == "String" {
                    wip = wip
                        .set(alloc::string::ToString::to_string(&n))
                        .map_err(&reflect_err)?;
                } else {
                    wip = wip.set(n).map_err(&reflect_err)?;
                }
            }
            ScalarValue::U64(n) => {
                // Handle unsigned types
                if shape.type_identifier == "u8" {
                    wip = wip.set(n as u8).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u16" {
                    wip = wip.set(n as u16).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u32" {
                    wip = wip.set(n as u32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u64" {
                    wip = wip.set(n).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u128" {
                    wip = wip.set(n as u128).map_err(&reflect_err)?;
                } else if shape.type_identifier == "usize" {
                    wip = wip.set(n as usize).map_err(&reflect_err)?;
                // Handle signed types (U64 can fit in signed if small enough)
                } else if shape.type_identifier == "i8" {
                    wip = wip.set(n as i8).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i16" {
                    wip = wip.set(n as i16).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i32" {
                    wip = wip.set(n as i32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i64" {
                    wip = wip.set(n as i64).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i128" {
                    wip = wip.set(n as i128).map_err(&reflect_err)?;
                } else if shape.type_identifier == "isize" {
                    wip = wip.set(n as isize).map_err(&reflect_err)?;
                // Handle floats
                } else if shape.type_identifier == "f32" {
                    wip = wip.set(n as f32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "f64" {
                    wip = wip.set(n as f64).map_err(&reflect_err)?;
                // Handle String - stringify the number
                } else if shape.type_identifier == "String" {
                    wip = wip
                        .set(alloc::string::ToString::to_string(&n))
                        .map_err(&reflect_err)?;
                } else {
                    wip = wip.set(n).map_err(&reflect_err)?;
                }
            }
            ScalarValue::U128(n) => {
                // Handle u128 scalar
                if shape.type_identifier == "u128" {
                    wip = wip.set(n).map_err(&reflect_err)?;
                } else if shape.type_identifier == "i128" {
                    wip = wip.set(n as i128).map_err(&reflect_err)?;
                } else {
                    // For smaller types, truncate (caller should have used correct hint)
                    wip = wip.set(n as u64).map_err(&reflect_err)?;
                }
            }
            ScalarValue::I128(n) => {
                // Handle i128 scalar
                if shape.type_identifier == "i128" {
                    wip = wip.set(n).map_err(&reflect_err)?;
                } else if shape.type_identifier == "u128" {
                    wip = wip.set(n as u128).map_err(&reflect_err)?;
                } else {
                    // For smaller types, truncate (caller should have used correct hint)
                    wip = wip.set(n as i64).map_err(&reflect_err)?;
                }
            }
            ScalarValue::F64(n) => {
                if shape.type_identifier == "f32" {
                    wip = wip.set(n as f32).map_err(&reflect_err)?;
                } else if shape.type_identifier == "f64" {
                    wip = wip.set(n).map_err(&reflect_err)?;
                } else if shape.vtable.has_try_from() && shape.inner.is_some() {
                    // For opaque types with try_from (like NotNan, OrderedFloat), use
                    // begin_inner() + set + end() to trigger conversion
                    let inner_shape = shape.inner.unwrap();
                    wip = wip.begin_inner().map_err(&reflect_err)?;
                    if inner_shape.is_type::<f32>() {
                        wip = wip.set(n as f32).map_err(&reflect_err)?;
                    } else {
                        wip = wip.set(n).map_err(&reflect_err)?;
                    }
                    wip = wip.end().map_err(&reflect_err)?;
                } else if shape.vtable.has_parse() {
                    // For types that support parsing (like Decimal), convert to string
                    // and use parse_from_str to preserve their parsing semantics
                    wip = wip
                        .parse_from_str(&alloc::string::ToString::to_string(&n))
                        .map_err(&reflect_err)?;
                } else {
                    wip = wip.set(n).map_err(&reflect_err)?;
                }
            }
            ScalarValue::Str(s) => {
                // Try parse_from_str first if the type supports it
                if shape.vtable.has_parse() {
                    wip = wip.parse_from_str(s.as_ref()).map_err(&reflect_err)?;
                } else {
                    wip = self.set_string_value(wip, s)?;
                }
            }
            ScalarValue::Bytes(b) => {
                // First try parse_from_bytes if the type supports it (e.g., UUID from 16 bytes)
                if shape.vtable.has_parse_bytes() {
                    wip = wip.parse_from_bytes(b.as_ref()).map_err(&reflect_err)?;
                } else {
                    // Fall back to setting as Vec<u8>
                    wip = wip.set(b.into_owned()).map_err(&reflect_err)?;
                }
            }
            ScalarValue::StringlyTyped(s) => {
                // Stringly-typed values from XML need to be parsed based on target type.
                //
                // For DynamicValue (like facet_value::Value), we need to detect the type
                // by trying to parse as null, bool, number, then falling back to string.
                //
                // For concrete types with has_parse(), use parse_from_str.
                // For string types, use set_string_value.
                if matches!(shape.def, facet_core::Def::DynamicValue(_)) {
                    // Try to detect the type for DynamicValue
                    let text = s.as_ref();
                    if text.eq_ignore_ascii_case("null") {
                        wip = wip.set_default().map_err(&reflect_err)?;
                    } else if let Ok(b) = text.parse::<bool>() {
                        wip = wip.set(b).map_err(&reflect_err)?;
                    } else if let Ok(n) = text.parse::<i64>() {
                        wip = wip.set(n).map_err(&reflect_err)?;
                    } else if let Ok(n) = text.parse::<u64>() {
                        wip = wip.set(n).map_err(&reflect_err)?;
                    } else if let Ok(n) = text.parse::<f64>() {
                        wip = wip.set(n).map_err(&reflect_err)?;
                    } else {
                        // Fall back to string
                        wip = self.set_string_value(wip, s)?;
                    }
                } else if shape.vtable.has_parse() {
                    wip = wip.parse_from_str(s.as_ref()).map_err(&reflect_err)?;
                } else {
                    wip = self.set_string_value(wip, s)?;
                }
            }
        }

        Ok(wip)
    }

    /// Set a string value, handling `&str`, `Cow<str>`, and `String` appropriately.
    fn set_string_value(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        s: Cow<'input, str>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // Check if target is &str (shared reference to str)
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
            && ptr_def
                .pointee()
                .is_some_and(|p| p.type_identifier == "str")
        {
            // In owned mode, we cannot borrow from input at all
            if !BORROW {
                return Err(DeserializeError::CannotBorrow {
                    message: "cannot deserialize into &str when borrowing is disabled - use String or Cow<str> instead".into(),
                });
            }
            match s {
                Cow::Borrowed(borrowed) => {
                    wip = wip.set(borrowed).map_err(DeserializeError::reflect)?;
                    return Ok(wip);
                }
                Cow::Owned(_) => {
                    return Err(DeserializeError::CannotBorrow {
                        message: "cannot borrow &str from string containing escape sequences - use String or Cow<str> instead".into(),
                    });
                }
            }
        }

        // Check if target is Cow<str>
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::Cow))
            && ptr_def
                .pointee()
                .is_some_and(|p| p.type_identifier == "str")
        {
            wip = wip.set(s).map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Default: convert to owned String
        wip = wip.set(s.into_owned()).map_err(DeserializeError::reflect)?;
        Ok(wip)
    }

    /// Set a bytes value with proper handling for borrowed vs owned data.
    ///
    /// This handles `&[u8]`, `Cow<[u8]>`, and `Vec<u8>` appropriately based on
    /// whether borrowing is enabled and whether the data is borrowed or owned.
    fn set_bytes_value(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        b: Cow<'input, [u8]>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // Helper to check if a shape is a byte slice ([u8])
        let is_byte_slice = |pointee: &facet_core::Shape| matches!(pointee.def, Def::Slice(slice_def) if slice_def.t.type_identifier == "u8");

        // Check if target is &[u8] (shared reference to byte slice)
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
            && ptr_def.pointee().is_some_and(is_byte_slice)
        {
            // In owned mode, we cannot borrow from input at all
            if !BORROW {
                return Err(DeserializeError::CannotBorrow {
                    message: "cannot deserialize into &[u8] when borrowing is disabled - use Vec<u8> or Cow<[u8]> instead".into(),
                });
            }
            match b {
                Cow::Borrowed(borrowed) => {
                    wip = wip.set(borrowed).map_err(DeserializeError::reflect)?;
                    return Ok(wip);
                }
                Cow::Owned(_) => {
                    return Err(DeserializeError::CannotBorrow {
                        message: "cannot borrow &[u8] from owned bytes - use Vec<u8> or Cow<[u8]> instead".into(),
                    });
                }
            }
        }

        // Check if target is Cow<[u8]>
        if let Def::Pointer(ptr_def) = shape.def
            && matches!(ptr_def.known, Some(KnownPointer::Cow))
            && ptr_def.pointee().is_some_and(is_byte_slice)
        {
            wip = wip.set(b).map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Default: convert to owned Vec<u8>
        wip = wip.set(b.into_owned()).map_err(DeserializeError::reflect)?;
        Ok(wip)
    }

    /// Deserialize a map key from a string.
    ///
    /// Format parsers typically emit string keys, but the target map might have non-string key types
    /// (e.g., integers, enums). This function parses the string key into the appropriate type:
    /// - String types: set directly
    /// - Enum unit variants: use select_variant_named
    /// - Integer types: parse the string as a number
    /// - Transparent newtypes: descend into the inner type
    fn deserialize_map_key(
        &mut self,
        mut wip: Partial<'input, BORROW>,
        key: Cow<'input, str>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        let shape = wip.shape();

        // For transparent types (like UserId(String)), we need to use begin_inner
        // to set the inner value. But NOT for pointer types like &str or Cow<str>
        // which are handled directly.
        let is_pointer = matches!(shape.def, Def::Pointer(_));
        if shape.inner.is_some() && !is_pointer {
            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
            wip = self.deserialize_map_key(wip, key)?;
            wip = wip.end().map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Check if target is an enum - use select_variant_named for unit variants
        if let Type::User(UserType::Enum(_)) = &shape.ty {
            wip = wip
                .select_variant_named(&key)
                .map_err(DeserializeError::reflect)?;
            return Ok(wip);
        }

        // Check if target is a numeric type - parse the string key as a number
        if let Type::Primitive(PrimitiveType::Numeric(num_ty)) = &shape.ty {
            match num_ty {
                NumericType::Integer { signed } => {
                    if *signed {
                        let n: i64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
                            expected: "valid integer for map key",
                            got: format!("string '{}'", key),
                            span: self.last_span,
                            path: None,
                        })?;
                        // Use set for each size - the Partial handles type conversion
                        wip = wip.set(n).map_err(DeserializeError::reflect)?;
                    } else {
                        let n: u64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
                            expected: "valid unsigned integer for map key",
                            got: format!("string '{}'", key),
                            span: self.last_span,
                            path: None,
                        })?;
                        wip = wip.set(n).map_err(DeserializeError::reflect)?;
                    }
                    return Ok(wip);
                }
                NumericType::Float => {
                    let n: f64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
                        expected: "valid float for map key",
                        got: format!("string '{}'", key),
                        span: self.last_span,
                        path: None,
                    })?;
                    wip = wip.set(n).map_err(DeserializeError::reflect)?;
                    return Ok(wip);
                }
            }
        }

        // Default: treat as string
        wip = self.set_string_value(wip, key)?;
        Ok(wip)
    }

    /// Deserialize any value into a DynamicValue type (e.g., facet_value::Value).
    ///
    /// This handles all value types by inspecting the parse events and calling
    /// the appropriate methods on the Partial, which delegates to the DynamicValue vtable.
    fn deserialize_dynamic_value(
        &mut self,
        mut wip: Partial<'input, BORROW>,
    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
        self.parser.hint_dynamic_value();
        let event = self.expect_peek("value for dynamic value")?;

        match event {
            ParseEvent::Scalar(_) => {
                // Consume the scalar
                let event = self.expect_event("scalar")?;
                if let ParseEvent::Scalar(scalar) = event {
                    // Use set_scalar which already handles all scalar types
                    wip = self.set_scalar(wip, scalar)?;
                }
            }
            ParseEvent::SequenceStart(_) => {
                // Array/list
                self.expect_event("sequence start")?; // consume '['
                wip = wip.begin_list().map_err(DeserializeError::reflect)?;

                loop {
                    let event = self.expect_peek("value or end")?;
                    if matches!(event, ParseEvent::SequenceEnd) {
                        self.expect_event("sequence end")?;
                        break;
                    }

                    wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
                    wip = self.deserialize_dynamic_value(wip)?;
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }
            }
            ParseEvent::StructStart(_) => {
                // Object/map/table
                self.expect_event("struct start")?; // consume '{'
                wip = wip.begin_map().map_err(DeserializeError::reflect)?;

                loop {
                    let event = self.expect_peek("field key or end")?;
                    if matches!(event, ParseEvent::StructEnd) {
                        self.expect_event("struct end")?;
                        break;
                    }

                    // Parse the key
                    let key_event = self.expect_event("field key")?;
                    let key = match key_event {
                        ParseEvent::FieldKey(field_key) => field_key.name.into_owned(),
                        _ => {
                            return Err(DeserializeError::TypeMismatch {
                                expected: "field key",
                                got: format!("{:?}", key_event),
                                span: self.last_span,
                                path: None,
                            });
                        }
                    };

                    // Begin the object entry and deserialize the value
                    wip = wip
                        .begin_object_entry(&key)
                        .map_err(DeserializeError::reflect)?;
                    wip = self.deserialize_dynamic_value(wip)?;
                    wip = wip.end().map_err(DeserializeError::reflect)?;
                }
            }
            _ => {
                return Err(DeserializeError::TypeMismatch {
                    expected: "scalar, sequence, or struct",
                    got: format!("{:?}", event),
                    span: self.last_span,
                    path: None,
                });
            }
        }

        Ok(wip)
    }
}

/// Error produced by [`FormatDeserializer`].
#[derive(Debug)]
pub enum DeserializeError<E> {
    /// Error emitted by the format-specific parser.
    Parser(E),
    /// Reflection error from Partial operations.
    Reflect {
        /// The underlying reflection error.
        error: ReflectError,
        /// Source span where the error occurred (if available).
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Type mismatch during deserialization.
    TypeMismatch {
        /// The expected type or token.
        expected: &'static str,
        /// The actual type or token that was encountered.
        got: String,
        /// Source span where the mismatch occurred (if available).
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Unsupported type or operation.
    Unsupported(String),
    /// Unknown field encountered when deny_unknown_fields is set.
    UnknownField {
        /// The unknown field name.
        field: String,
        /// Source span where the unknown field was found (if available).
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Cannot borrow string from input (e.g., escaped string into &str).
    CannotBorrow {
        /// Description of why borrowing failed.
        message: String,
    },
    /// Required field missing from input.
    MissingField {
        /// The field that is missing.
        field: &'static str,
        /// The type that contains the field.
        type_name: &'static str,
        /// Source span where the struct was being parsed (if available).
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Expected a scalar value but got a struct/object.
    ///
    /// This typically happens when a format-specific mapping expects a scalar
    /// (like a KDL property `name=value`) but receives a child node instead
    /// (like KDL node with arguments `name "value"`).
    ExpectedScalarGotStruct {
        /// The shape that was expected (provides access to type info and attributes).
        expected_shape: &'static facet_core::Shape,
        /// The container kind that was received (Object, Array, Element).
        got_container: crate::ContainerKind,
        /// Source span where the mismatch occurred (if available).
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Field validation failed.
    #[cfg(feature = "validate")]
    Validation {
        /// The field that failed validation.
        field: &'static str,
        /// The validation error message.
        message: String,
        /// Source span where the invalid value was found.
        span: Option<facet_reflect::Span>,
        /// Path through the type structure where the error occurred.
        path: Option<Path>,
    },
    /// Unexpected end of input.
    UnexpectedEof {
        /// What was expected before EOF.
        expected: &'static str,
    },
}

impl<E: fmt::Display> fmt::Display for DeserializeError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DeserializeError::Parser(err) => write!(f, "{err}"),
            DeserializeError::Reflect { error, .. } => write!(f, "{error}"),
            DeserializeError::TypeMismatch { expected, got, .. } => {
                write!(f, "type mismatch: expected {expected}, got {got}")
            }
            DeserializeError::Unsupported(msg) => write!(f, "unsupported: {msg}"),
            DeserializeError::UnknownField { field, .. } => write!(f, "unknown field: {field}"),
            DeserializeError::CannotBorrow { message } => write!(f, "{message}"),
            DeserializeError::MissingField {
                field, type_name, ..
            } => {
                write!(f, "missing field `{field}` in type `{type_name}`")
            }
            DeserializeError::ExpectedScalarGotStruct {
                expected_shape,
                got_container,
                ..
            } => {
                write!(
                    f,
                    "expected `{}` value, got {}",
                    expected_shape.type_identifier,
                    got_container.name()
                )
            }
            #[cfg(feature = "validate")]
            DeserializeError::Validation { field, message, .. } => {
                write!(f, "validation failed for field `{field}`: {message}")
            }
            DeserializeError::UnexpectedEof { expected } => {
                write!(f, "unexpected end of input, expected {expected}")
            }
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for DeserializeError<E> {}

impl<E> DeserializeError<E> {
    /// Create a Reflect error without span or path information.
    #[inline]
    pub fn reflect(error: ReflectError) -> Self {
        DeserializeError::Reflect {
            error,
            span: None,
            path: None,
        }
    }

    /// Create a Reflect error with span information.
    #[inline]
    pub fn reflect_with_span(error: ReflectError, span: facet_reflect::Span) -> Self {
        DeserializeError::Reflect {
            error,
            span: Some(span),
            path: None,
        }
    }

    /// Create a Reflect error with span and path information.
    #[inline]
    pub fn reflect_with_context(
        error: ReflectError,
        span: Option<facet_reflect::Span>,
        path: Path,
    ) -> Self {
        DeserializeError::Reflect {
            error,
            span,
            path: Some(path),
        }
    }

    /// Get the path where the error occurred, if available.
    pub fn path(&self) -> Option<&Path> {
        match self {
            DeserializeError::Reflect { path, .. } => path.as_ref(),
            DeserializeError::TypeMismatch { path, .. } => path.as_ref(),
            DeserializeError::UnknownField { path, .. } => path.as_ref(),
            DeserializeError::MissingField { path, .. } => path.as_ref(),
            DeserializeError::ExpectedScalarGotStruct { path, .. } => path.as_ref(),
            _ => None,
        }
    }

    /// Add path information to an error (consumes and returns the modified error).
    pub fn with_path(self, new_path: Path) -> Self {
        match self {
            DeserializeError::Reflect { error, span, .. } => DeserializeError::Reflect {
                error,
                span,
                path: Some(new_path),
            },
            DeserializeError::TypeMismatch {
                expected,
                got,
                span,
                ..
            } => DeserializeError::TypeMismatch {
                expected,
                got,
                span,
                path: Some(new_path),
            },
            DeserializeError::UnknownField { field, span, .. } => DeserializeError::UnknownField {
                field,
                span,
                path: Some(new_path),
            },
            DeserializeError::MissingField {
                field,
                type_name,
                span,
                ..
            } => DeserializeError::MissingField {
                field,
                type_name,
                span,
                path: Some(new_path),
            },
            DeserializeError::ExpectedScalarGotStruct {
                expected_shape,
                got_container,
                span,
                ..
            } => DeserializeError::ExpectedScalarGotStruct {
                expected_shape,
                got_container,
                span,
                path: Some(new_path),
            },
            // Other variants don't have path fields
            other => other,
        }
    }
}

#[cfg(feature = "miette")]
impl<E: miette::Diagnostic + 'static> miette::Diagnostic for DeserializeError<E> {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        match self {
            DeserializeError::Parser(e) => e.code(),
            DeserializeError::TypeMismatch { .. } => Some(Box::new("facet::type_mismatch")),
            DeserializeError::MissingField { .. } => Some(Box::new("facet::missing_field")),
            _ => None,
        }
    }

    fn severity(&self) -> Option<miette::Severity> {
        match self {
            DeserializeError::Parser(e) => e.severity(),
            _ => Some(miette::Severity::Error),
        }
    }

    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        match self {
            DeserializeError::Parser(e) => e.help(),
            DeserializeError::TypeMismatch { expected, .. } => {
                Some(Box::new(format!("expected {expected}")))
            }
            DeserializeError::MissingField { field, .. } => Some(Box::new(format!(
                "add `{field}` to your input, or mark the field as optional with #[facet(default)]"
            ))),
            _ => None,
        }
    }

    fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        match self {
            DeserializeError::Parser(e) => e.url(),
            _ => None,
        }
    }

    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        match self {
            DeserializeError::Parser(e) => e.source_code(),
            _ => None,
        }
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        match self {
            DeserializeError::Parser(e) => e.labels(),
            DeserializeError::Reflect {
                span: Some(span),
                error,
                ..
            } => {
                // Use a shorter label for parse failures
                let label = match error {
                    facet_reflect::ReflectError::ParseFailed { shape, .. } => {
                        alloc::format!("invalid value for `{}`", shape.type_identifier)
                    }
                    _ => error.to_string(),
                };
                Some(Box::new(core::iter::once(miette::LabeledSpan::at(
                    *span, label,
                ))))
            }
            DeserializeError::TypeMismatch {
                span: Some(span),
                expected,
                ..
            } => Some(Box::new(core::iter::once(miette::LabeledSpan::at(
                *span,
                format!("expected {expected}"),
            )))),
            DeserializeError::UnknownField {
                span: Some(span), ..
            } => Some(Box::new(core::iter::once(miette::LabeledSpan::at(
                *span,
                "unknown field",
            )))),
            DeserializeError::MissingField {
                span: Some(span),
                field,
                ..
            } => Some(Box::new(core::iter::once(miette::LabeledSpan::at(
                *span,
                format!("missing field '{field}'"),
            )))),
            DeserializeError::ExpectedScalarGotStruct {
                span: Some(span),
                got_container,
                ..
            } => Some(Box::new(core::iter::once(miette::LabeledSpan::at(
                *span,
                format!("got {} here", got_container.name()),
            )))),
            _ => None,
        }
    }

    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
        match self {
            DeserializeError::Parser(e) => e.related(),
            _ => None,
        }
    }

    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
        match self {
            DeserializeError::Parser(e) => e.diagnostic_source(),
            _ => None,
        }
    }
}