facet-reflect 0.44.4

Build and manipulate values of arbitrary Facet types at runtime while respecting invariants - safe runtime reflection
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
//! Partial value construction for dynamic reflection
//!
//! This module provides APIs for incrementally building values through reflection,
//! particularly useful when deserializing data from external formats like JSON or YAML.
//!
//! # Overview
//!
//! The `Partial` type (formerly known as `Wip` - Work In Progress) allows you to:
//! - Allocate memory for a value based on its `Shape`
//! - Initialize fields incrementally in a type-safe manner
//! - Handle complex nested structures including structs, enums, collections, and smart pointers
//! - Build the final value once all required fields are initialized
//!
//! **Note**: This is the only API for partial value construction. The previous `TypedPartial`
//! wrapper has been removed in favor of using `Partial` directly.
//!
//! # Basic Usage
//!
//! ```no_run
//! # use facet_reflect::Partial;
//! # use facet_core::{Shape, Facet};
//! # fn example<T: Facet<'static>>() -> Result<(), Box<dyn std::error::Error>> {
//! // Allocate memory for a struct
//! let mut partial = Partial::alloc::<T>()?;
//!
//! // Set simple fields
//! partial = partial.set_field("name", "Alice")?;
//! partial = partial.set_field("age", 30u32)?;
//!
//! // Work with nested structures
//! partial = partial.begin_field("address")?;
//! partial = partial.set_field("street", "123 Main St")?;
//! partial = partial.set_field("city", "Springfield")?;
//! partial = partial.end()?;
//!
//! // Build the final value
//! let value = partial.build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Chaining Style
//!
//! The API supports method chaining for cleaner code:
//!
//! ```no_run
//! # use facet_reflect::Partial;
//! # use facet_core::{Shape, Facet};
//! # fn example<T: Facet<'static>>() -> Result<(), Box<dyn std::error::Error>> {
//! let value = Partial::alloc::<T>()?
//!     .set_field("name", "Bob")?
//!     .begin_field("scores")?
//!         .set(vec![95, 87, 92])?
//!     .end()?
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Working with Collections
//!
//! ```no_run
//! # use facet_reflect::Partial;
//! # use facet_core::{Shape, Facet};
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut partial = Partial::alloc::<Vec<String>>()?;
//!
//! // Add items to a list
//! partial = partial.begin_list_item()?;
//! partial = partial.set("first")?;
//! partial = partial.end()?;
//!
//! partial = partial.begin_list_item()?;
//! partial = partial.set("second")?;
//! partial = partial.end()?;
//!
//! let vec = partial.build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Working with Maps
//!
//! ```no_run
//! # use facet_reflect::Partial;
//! # use facet_core::{Shape, Facet};
//! # use std::collections::HashMap;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut partial = Partial::alloc::<HashMap<String, i32>>()?;
//!
//! // Insert key-value pairs
//! partial = partial.begin_key()?;
//! partial = partial.set("score")?;
//! partial = partial.end()?;
//! partial = partial.begin_value()?;
//! partial = partial.set(100i32)?;
//! partial = partial.end()?;
//!
//! let map = partial.build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Safety and Memory Management
//!
//! The `Partial` type ensures memory safety by:
//! - Tracking initialization state of all fields
//! - Preventing use-after-build through state tracking
//! - Properly handling drop semantics for partially initialized values
//! - Supporting both owned and borrowed values through lifetime parameters

use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};

mod arena;
mod iset;
mod rope;
pub(crate) mod typeplan;
pub use typeplan::{DeserStrategy, NodeId, TypePlan, TypePlanCore};

mod partial_api;

use crate::{ReflectErrorKind, TrackerKind, trace};
use facet_core::Facet;
use facet_path::{Path, PathStep};

use core::marker::PhantomData;

mod heap_value;
pub use heap_value::*;

use facet_core::{
    Def, EnumType, Field, PtrMut, PtrUninit, Shape, SliceBuilderVTable, Type, UserType, Variant,
};
use iset::ISet;
use rope::ListRope;
use typeplan::{FieldDefault, FieldInitPlan, FillRule};

/// State of a partial value
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PartialState {
    /// Partial is active and can be modified
    Active,

    /// Partial has been successfully built and cannot be reused
    Built,
}

/// Mode of operation for frame management.
///
/// In `Strict` mode, frames must be fully initialized before being popped.
/// In `Deferred` mode, frames can be stored when popped and restored on re-entry,
/// with final validation happening in `finish_deferred()`.
enum FrameMode {
    /// Strict mode: frames must be fully initialized before popping.
    Strict {
        /// Stack of frames for nested initialization.
        stack: Vec<Frame>,
    },

    /// Deferred mode: frames are stored when popped, can be re-entered.
    Deferred {
        /// Stack of frames for nested initialization.
        stack: Vec<Frame>,

        /// The frame depth when deferred mode was started.
        /// Path calculations are relative to this depth.
        start_depth: usize,

        /// Frames saved when popped, keyed by their path (derived from frame stack).
        /// When we re-enter a path, we restore the stored frame.
        /// Uses the full `Path` type which includes the root shape for proper type anchoring.
        stored_frames: BTreeMap<Path, Frame>,
    },
}

impl FrameMode {
    /// Get a reference to the frame stack.
    const fn stack(&self) -> &Vec<Frame> {
        match self {
            FrameMode::Strict { stack } | FrameMode::Deferred { stack, .. } => stack,
        }
    }

    /// Get a mutable reference to the frame stack.
    const fn stack_mut(&mut self) -> &mut Vec<Frame> {
        match self {
            FrameMode::Strict { stack } | FrameMode::Deferred { stack, .. } => stack,
        }
    }

    /// Check if we're in deferred mode.
    const fn is_deferred(&self) -> bool {
        matches!(self, FrameMode::Deferred { .. })
    }

    /// Get the start depth if in deferred mode.
    const fn start_depth(&self) -> Option<usize> {
        match self {
            FrameMode::Deferred { start_depth, .. } => Some(*start_depth),
            FrameMode::Strict { .. } => None,
        }
    }
}

/// A type-erased, heap-allocated, partially-initialized value.
///
/// [Partial] keeps track of the state of initialiation of the underlying
/// value: if we're building `struct S { a: u32, b: String }`, we may
/// have initialized `a`, or `b`, or both, or neither.
///
/// [Partial] allows navigating down nested structs and initializing them
/// progressively: [Partial::begin_field] pushes a frame onto the stack,
/// which then has to be initialized, and popped off with [Partial::end].
///
/// If [Partial::end] is called but the current frame isn't fully initialized,
/// an error is returned: in other words, if you navigate down to a field,
/// you have to fully initialize it one go. You can't go back up and back down
/// to it again.
pub struct Partial<'facet, const BORROW: bool = true> {
    /// Frame management mode (strict or deferred) and associated state.
    mode: FrameMode,

    /// current state of the Partial
    state: PartialState,

    /// Precomputed deserialization plan for the root type.
    /// Built once at allocation time, navigated in parallel with value construction.
    /// Each Frame holds a NodeId (index) into this plan's arenas.
    root_plan: Arc<TypePlanCore>,

    /// PhantomData marker for the 'facet lifetime.
    /// This is covariant in 'facet, which is safe because 'facet represents
    /// the lifetime of borrowed data FROM the input (deserialization source).
    /// A Partial<'long, ...> can be safely treated as Partial<'short, ...>
    /// because it only needs borrowed data to live at least as long as 'short.
    _marker: PhantomData<&'facet ()>,
}

#[derive(Clone, Copy, Debug)]
pub(crate) enum MapInsertState {
    /// Not currently inserting
    Idle,

    /// Pushing key - memory allocated, waiting for initialization
    PushingKey {
        /// Temporary storage for the key being built
        key_ptr: PtrUninit,
        /// Whether the key has been fully initialized
        key_initialized: bool,
        /// Whether the key's TrackedBuffer frame is still on the stack.
        /// When true, the frame handles cleanup. When false (after end()),
        /// the Map tracker owns the buffer and must clean it up.
        key_frame_on_stack: bool,
    },

    /// Pushing value after key is done
    PushingValue {
        /// Temporary storage for the key that was built (always initialized)
        key_ptr: PtrUninit,
        /// Temporary storage for the value being built
        value_ptr: Option<PtrUninit>,
        /// Whether the value has been fully initialized
        value_initialized: bool,
        /// Whether the value's TrackedBuffer frame is still on the stack.
        /// When true, the frame handles cleanup. When false (after end()),
        /// the Map tracker owns the buffer and must clean it up.
        value_frame_on_stack: bool,
        /// Whether the key's frame was stored in deferred mode.
        /// When true, the stored frame handles cleanup. When false,
        /// the Map tracker owns the key buffer and must clean it up.
        key_frame_stored: bool,
    },
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum FrameOwnership {
    /// This frame owns the allocation and should deallocate it on drop
    Owned,

    /// This frame points to a field/element within a parent's allocation.
    /// The parent's `iset[field_idx]` was CLEARED when this frame was created.
    /// On drop: deinit if initialized, but do NOT deallocate.
    /// On successful end(): parent's `iset[field_idx]` will be SET.
    Field { field_idx: usize },

    /// Temporary buffer tracked by parent's MapInsertState.
    /// Used by begin_key(), begin_value() for map insertions.
    /// Safe to drop on deinit - parent's cleanup respects is_init propagation.
    TrackedBuffer,

    /// Pointer into existing collection entry (Value object, Option inner, etc.)
    /// Used by begin_object_entry() on existing key, begin_some() re-entry.
    /// NOT safe to drop on deinit - parent collection has no per-entry tracking
    /// and would try to drop the freed value again (double-free).
    BorrowedInPlace,

    /// Pointer to externally-owned memory (e.g., caller's stack via MaybeUninit).
    /// Used by `from_raw()` for stack-friendly deserialization.
    /// On drop: deinit if initialized (drop partially constructed values), but do NOT deallocate.
    /// The caller owns the memory and is responsible for its lifetime.
    External,

    /// Points into a stable rope chunk for list element building.
    /// Used by `begin_list_item()` for building Vec elements.
    /// The memory is stable (won't move during Vec growth),
    /// so frames inside can be stored for deferred processing.
    /// On successful end(): element is tracked for later finalization.
    /// On list frame end(): all elements are moved into the real Vec.
    /// On drop/failure: the rope chunk handles cleanup.
    RopeSlot,
}

impl FrameOwnership {
    /// Returns true if this frame is responsible for deallocating its memory.
    ///
    /// Both `Owned` and `TrackedBuffer` frames allocated their memory and need
    /// to deallocate it. `Field`, `BorrowedInPlace`, and `External` frames borrow from
    /// parent, existing structures, or caller-provided memory.
    const fn needs_dealloc(&self) -> bool {
        matches!(self, FrameOwnership::Owned | FrameOwnership::TrackedBuffer)
    }
}

/// Immutable pairing of a shape with its actual allocation size.
///
/// This ensures that the shape and allocated size are always in sync and cannot
/// drift apart, preventing the class of bugs where a frame's shape doesn't match
/// what was actually allocated (see issue #1568).
pub(crate) struct AllocatedShape {
    shape: &'static Shape,
    allocated_size: usize,
}

impl AllocatedShape {
    pub(crate) const fn new(shape: &'static Shape, allocated_size: usize) -> Self {
        Self {
            shape,
            allocated_size,
        }
    }

    pub(crate) const fn shape(&self) -> &'static Shape {
        self.shape
    }

    pub(crate) const fn allocated_size(&self) -> usize {
        self.allocated_size
    }
}

/// Points somewhere in a partially-initialized value. If we're initializing
/// `a.b.c`, then the first frame would point to the beginning of `a`, the
/// second to the beginning of the `b` field of `a`, etc.
///
/// A frame can point to a complex data structure, like a struct or an enum:
/// it keeps track of whether a variant was selected, which fields are initialized,
/// etc. and is able to drop & deinitialize
#[must_use]
pub(crate) struct Frame {
    /// Address of the value being initialized
    pub(crate) data: PtrUninit,

    /// Shape of the value being initialized, paired with the actual allocation size
    pub(crate) allocated: AllocatedShape,

    /// Whether this frame's data is fully initialized
    pub(crate) is_init: bool,

    /// Tracks building mode and partial initialization state
    pub(crate) tracker: Tracker,

    /// Whether this frame owns the allocation or is just a field pointer
    pub(crate) ownership: FrameOwnership,

    /// Whether this frame is for a custom deserialization pipeline
    pub(crate) using_custom_deserialization: bool,

    /// Container-level proxy definition (from `#[facet(proxy = ...)]` on the shape).
    /// Used during custom deserialization to convert from proxy type to target type.
    pub(crate) shape_level_proxy: Option<&'static facet_core::ProxyDef>,

    /// Index of the precomputed TypePlan node for this frame's type.
    /// This is navigated in parallel with the value - when we begin_nth_field,
    /// the new frame gets the index for that field's child plan node.
    /// Use `plan.node(type_plan)` to get the actual `&TypePlanNode`.
    /// Always present - TypePlan is built for what we actually deserialize into
    /// (including proxies).
    pub(crate) type_plan: typeplan::NodeId,
}

#[derive(Debug)]
pub(crate) enum Tracker {
    /// Simple scalar value - no partial initialization tracking needed.
    /// Whether it's initialized is tracked by `Frame::is_init`.
    Scalar,

    /// Partially initialized array
    Array {
        /// Track which array elements are initialized (up to 63 elements)
        iset: ISet,
        /// If we're pushing another frame, this is set to the array index
        current_child: Option<usize>,
    },

    /// Partially initialized struct/tuple-struct etc.
    Struct {
        /// fields need to be individually tracked — we only
        /// support up to 63 fields.
        iset: ISet,
        /// if we're pushing another frame, this is set to the index of the struct field
        current_child: Option<usize>,
    },

    /// Smart pointer being initialized.
    /// Whether it's initialized is tracked by `Frame::is_init`.
    SmartPointer {
        /// Whether we're currently building the inner value
        building_inner: bool,
        /// Pending inner value pointer to be moved with new_into_fn on finalization.
        /// Deferred processing requires keeping the inner value's memory stable,
        /// so we delay the new_into_fn() call until the SmartPointer frame is finalized.
        /// None = no pending inner, Some = inner value ready to be moved into SmartPointer.
        pending_inner: Option<PtrUninit>,
    },

    /// We're initializing an `Arc<[T]>`, `Box<[T]>`, `Rc<[T]>`, etc.
    ///
    /// We're using the slice builder API to construct the slice
    SmartPointerSlice {
        /// The slice builder vtable
        vtable: &'static SliceBuilderVTable,

        /// Whether we're currently building an item to push
        building_item: bool,

        /// Current element index being built (for path derivation in deferred mode)
        current_child: Option<usize>,
    },

    /// Transparent inner type wrapper (`NonZero<T>`, ByteString, etc.)
    /// Used to distinguish inner frames from their parent for deferred path tracking.
    Inner {
        /// Whether we're currently building the inner value
        building_inner: bool,
    },

    /// Partially initialized enum (but we picked a variant,
    /// so it's not Uninit)
    Enum {
        /// Variant chosen for the enum
        variant: &'static Variant,
        /// Index of the variant in the enum's variants array
        variant_idx: usize,
        /// tracks enum fields (for the given variant)
        data: ISet,
        /// If we're pushing another frame, this is set to the field index
        current_child: Option<usize>,
    },

    /// Partially initialized list (Vec, etc.)
    /// Whether it's initialized is tracked by `Frame::is_init`.
    List {
        /// If we're pushing another frame for an element, this is the element index
        current_child: Option<usize>,
        /// Stable rope storage for elements during list building.
        /// A rope is a list of fixed-size chunks - chunks never reallocate, only new
        /// chunks are added. This keeps element pointers stable, enabling deferred
        /// frame processing for nested structs inside Vec elements.
        /// On finalization, elements are moved into the real Vec.
        rope: Option<ListRope>,
    },

    /// Partially initialized map (HashMap, BTreeMap, etc.)
    /// Whether it's initialized is tracked by `Frame::is_init`.
    Map {
        /// State of the current insertion operation
        insert_state: MapInsertState,
        /// Pending key-value entries to be inserted on map finalization.
        /// Deferred processing requires keeping buffers alive until finish_deferred(),
        /// so we delay actual insertion until the map frame is finalized.
        /// Each entry is (key_ptr, value_ptr) - both are initialized and owned by this tracker.
        pending_entries: Vec<(PtrUninit, PtrUninit)>,
        /// The current entry index, used for building unique paths for deferred frame storage.
        /// Incremented each time we start a new key (in begin_key).
        /// This allows inner frames of different map entries to have distinct paths.
        current_entry_index: Option<usize>,
        /// Whether we're currently building a key (true) or value (false).
        /// Used to determine whether to push MapKey or MapValue to the path.
        building_key: bool,
    },

    /// Partially initialized set (HashSet, BTreeSet, etc.)
    /// Whether it's initialized is tracked by `Frame::is_init`.
    Set {
        /// If we're pushing another frame for an element
        current_child: bool,
    },

    /// Option being initialized with Some(inner_value)
    Option {
        /// Whether we're currently building the inner value
        building_inner: bool,
        /// Pending inner value pointer to be moved with init_some on finalization.
        /// Deferred processing requires keeping the inner value's memory stable,
        /// so we delay the init_some() call until the Option frame is finalized.
        /// None = no pending inner, Some = inner value ready to be moved into Option.
        pending_inner: Option<PtrUninit>,
    },

    /// Result being initialized with Ok or Err
    Result {
        /// Whether we're building Ok (true) or Err (false)
        is_ok: bool,
        /// Whether we're currently building the inner value
        building_inner: bool,
    },

    /// Dynamic value (e.g., facet_value::Value) being initialized
    DynamicValue {
        /// What kind of dynamic value we're building
        state: DynamicValueState,
    },
}

/// State for building a dynamic value
#[derive(Debug)]
#[allow(dead_code)] // Some variants are for future use (object support)
pub(crate) enum DynamicValueState {
    /// Not yet initialized - will be set to scalar, array, or object
    Uninit,
    /// Initialized as a scalar (null, bool, number, string, bytes)
    Scalar,
    /// Initialized as an array, currently building an element
    Array {
        building_element: bool,
        /// Pending elements to be inserted during finalization (deferred mode)
        pending_elements: alloc::vec::Vec<PtrUninit>,
    },
    /// Initialized as an object
    Object {
        insert_state: DynamicObjectInsertState,
        /// Pending entries to be inserted during finalization (deferred mode)
        pending_entries: alloc::vec::Vec<(alloc::string::String, PtrUninit)>,
    },
}

/// State for inserting into a dynamic object
#[derive(Debug)]
#[allow(dead_code)] // For future use (object support)
pub(crate) enum DynamicObjectInsertState {
    /// Idle - ready for a new key-value pair
    Idle,
    /// Currently building the value for a key
    BuildingValue {
        /// The key for the current entry
        key: alloc::string::String,
    },
}

impl Tracker {
    const fn kind(&self) -> TrackerKind {
        match self {
            Tracker::Scalar => TrackerKind::Scalar,
            Tracker::Array { .. } => TrackerKind::Array,
            Tracker::Struct { .. } => TrackerKind::Struct,
            Tracker::SmartPointer { .. } => TrackerKind::SmartPointer,
            Tracker::SmartPointerSlice { .. } => TrackerKind::SmartPointerSlice,
            Tracker::Enum { .. } => TrackerKind::Enum,
            Tracker::List { .. } => TrackerKind::List,
            Tracker::Map { .. } => TrackerKind::Map,
            Tracker::Set { .. } => TrackerKind::Set,
            Tracker::Option { .. } => TrackerKind::Option,
            Tracker::Result { .. } => TrackerKind::Result,
            Tracker::DynamicValue { .. } => TrackerKind::DynamicValue,
            Tracker::Inner { .. } => TrackerKind::Inner,
        }
    }

    /// Set the current_child index for trackers that support it
    const fn set_current_child(&mut self, idx: usize) {
        match self {
            Tracker::Struct { current_child, .. }
            | Tracker::Enum { current_child, .. }
            | Tracker::Array { current_child, .. } => {
                *current_child = Some(idx);
            }
            _ => {}
        }
    }

    /// Clear the current_child index for trackers that support it
    fn clear_current_child(&mut self) {
        match self {
            Tracker::Struct { current_child, .. }
            | Tracker::Enum { current_child, .. }
            | Tracker::Array { current_child, .. }
            | Tracker::List { current_child, .. } => {
                *current_child = None;
            }
            Tracker::Set { current_child } => {
                *current_child = false;
            }
            _ => {}
        }
    }
}

impl Frame {
    fn new(
        data: PtrUninit,
        allocated: AllocatedShape,
        ownership: FrameOwnership,
        type_plan: typeplan::NodeId,
    ) -> Self {
        // For empty structs (structs with 0 fields), start as initialized since there's nothing to initialize
        // This includes empty tuples () which are zero-sized types with no fields to initialize
        let is_init = matches!(
            allocated.shape().ty,
            Type::User(UserType::Struct(struct_type)) if struct_type.fields.is_empty()
        );

        Self {
            data,
            allocated,
            is_init,
            tracker: Tracker::Scalar,
            ownership,
            using_custom_deserialization: false,
            shape_level_proxy: None,
            type_plan,
        }
    }

    /// Deinitialize any initialized field: calls `drop_in_place` but does not free any
    /// memory even if the frame owns that memory.
    ///
    /// After this call, `is_init` will be false and `tracker` will be [Tracker::Scalar].
    fn deinit(&mut self) {
        // For BorrowedInPlace frames, we must NOT drop. These point into existing
        // collection entries (Value objects, Option inners) where the parent has no
        // per-entry tracking. Dropping here would cause double-free when parent drops.
        //
        // For RopeSlot frames, we must NOT drop. These point into a ListRope chunk
        // owned by the parent List's tracker. The rope handles cleanup of all elements.
        //
        // For TrackedBuffer frames, we CAN drop. These are temporary buffers where
        // the parent's MapInsertState tracks initialization via is_init propagation.
        if matches!(
            self.ownership,
            FrameOwnership::BorrowedInPlace | FrameOwnership::RopeSlot
        ) {
            self.is_init = false;
            self.tracker = Tracker::Scalar;
            return;
        }

        // Field frames are responsible for their value during cleanup.
        // The ownership model ensures no double-free:
        // - begin_field: parent's iset[idx] is cleared (parent relinquishes responsibility)
        // - end: parent's iset[idx] is set (parent reclaims responsibility), frame is popped
        // So if Field frame is still on stack during cleanup, parent's iset[idx] is false,
        // meaning the parent won't drop this field - the Field frame must do it.

        match &mut self.tracker {
            Tracker::Scalar => {
                // Simple scalar - drop if initialized
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::Array { iset, .. } => {
                // Drop initialized array elements
                if let Type::Sequence(facet_core::SequenceType::Array(array_def)) =
                    self.allocated.shape().ty
                {
                    let element_layout = array_def.t.layout.sized_layout().ok();
                    if let Some(layout) = element_layout {
                        for idx in 0..array_def.n {
                            if iset.get(idx) {
                                let offset = layout.size() * idx;
                                let element_ptr = unsafe { self.data.field_init(offset) };
                                unsafe { array_def.t.call_drop_in_place(element_ptr) };
                            }
                        }
                    }
                }
            }
            Tracker::Struct { iset, .. } => {
                // Drop initialized struct fields
                if let Type::User(UserType::Struct(struct_type)) = self.allocated.shape().ty {
                    if iset.all_set(struct_type.fields.len()) {
                        unsafe {
                            self.allocated
                                .shape()
                                .call_drop_in_place(self.data.assume_init())
                        };
                    } else {
                        for (idx, field) in struct_type.fields.iter().enumerate() {
                            if iset.get(idx) {
                                // This field was initialized, drop it
                                let field_ptr = unsafe { self.data.field_init(field.offset) };
                                unsafe { field.shape().call_drop_in_place(field_ptr) };
                            }
                        }
                    }
                }
            }
            Tracker::Enum { variant, data, .. } => {
                // Drop initialized enum variant fields
                for (idx, field) in variant.data.fields.iter().enumerate() {
                    if data.get(idx) {
                        // This field was initialized, drop it
                        let field_ptr = unsafe { self.data.field_init(field.offset) };
                        unsafe { field.shape().call_drop_in_place(field_ptr) };
                    }
                }
            }
            Tracker::SmartPointer { pending_inner, .. } => {
                // If there's a pending inner value, drop it
                if let Some(inner_ptr) = pending_inner
                    && let Def::Pointer(ptr_def) = self.allocated.shape().def
                    && let Some(inner_shape) = ptr_def.pointee
                {
                    unsafe {
                        inner_shape.call_drop_in_place(PtrMut::new(inner_ptr.as_mut_byte_ptr()))
                    };
                }
                // Drop the initialized SmartPointer
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::SmartPointerSlice { vtable, .. } => {
                // Free the slice builder
                let builder_ptr = unsafe { self.data.assume_init() };
                unsafe {
                    (vtable.free_fn)(builder_ptr);
                }
            }
            Tracker::List { rope, .. } => {
                // Drain any rope elements first. `is_init` only indicates that the Vec
                // has been allocated (via `init_in_place_with_capacity`); elements pushed
                // via `begin_list_item` live in the rope until `drain_rope_into_vec` moves
                // them into the Vec. A successful drain leaves `rope = None` (via `.take()`),
                // so if we see `rope = Some(..)` here the elements inside were never moved
                // into the Vec and they're still owned by the rope. Drop them now.
                if let Some(mut rope) = rope.take()
                    && let Def::List(list_def) = self.allocated.shape().def
                {
                    let element_shape = list_def.t;
                    unsafe {
                        rope.drain_into(|ptr| {
                            element_shape.call_drop_in_place(PtrMut::new(ptr.as_ptr()));
                        });
                    }
                }

                // Now drop the Vec (and whatever elements it already owns).
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::Map {
                insert_state,
                pending_entries,
                ..
            } => {
                // Drop the initialized Map
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }

                // Clean up pending entries (key-value pairs that haven't been inserted yet)
                if let Def::Map(map_def) = self.allocated.shape().def {
                    for (key_ptr, value_ptr) in pending_entries.drain(..) {
                        // Drop and deallocate key
                        unsafe { map_def.k().call_drop_in_place(key_ptr.assume_init()) };
                        if let Ok(key_layout) = map_def.k().layout.sized_layout()
                            && key_layout.size() > 0
                        {
                            unsafe { alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_layout) };
                        }
                        // Drop and deallocate value
                        unsafe { map_def.v().call_drop_in_place(value_ptr.assume_init()) };
                        if let Ok(value_layout) = map_def.v().layout.sized_layout()
                            && value_layout.size() > 0
                        {
                            unsafe {
                                alloc::alloc::dealloc(value_ptr.as_mut_byte_ptr(), value_layout)
                            };
                        }
                    }
                }

                // Clean up key/value buffers based on whether their TrackedBuffer frames
                // are still on the stack. If a frame is on the stack, it handles cleanup.
                // If a frame was already popped (via end()), we own the buffer and must clean it.
                match insert_state {
                    MapInsertState::PushingKey {
                        key_ptr,
                        key_initialized,
                        key_frame_on_stack,
                    } => {
                        // Only clean up if the frame was already popped.
                        // If key_frame_on_stack is true, the TrackedBuffer frame above us
                        // will handle dropping and deallocating the key buffer.
                        if !*key_frame_on_stack
                            && let Def::Map(map_def) = self.allocated.shape().def
                        {
                            // Drop the key if it was initialized
                            if *key_initialized {
                                unsafe { map_def.k().call_drop_in_place(key_ptr.assume_init()) };
                            }
                            // Deallocate the key buffer
                            if let Ok(key_layout) = map_def.k().layout.sized_layout()
                                && key_layout.size() > 0
                            {
                                unsafe {
                                    alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_layout)
                                };
                            }
                        }
                    }
                    MapInsertState::PushingValue {
                        key_ptr,
                        value_ptr,
                        value_initialized,
                        value_frame_on_stack,
                        key_frame_stored,
                    } => {
                        if let Def::Map(map_def) = self.allocated.shape().def {
                            // Only clean up key if the key frame was NOT stored.
                            // If key_frame_stored is true, the stored frame handles cleanup.
                            if !*key_frame_stored {
                                unsafe { map_def.k().call_drop_in_place(key_ptr.assume_init()) };
                                if let Ok(key_layout) = map_def.k().layout.sized_layout()
                                    && key_layout.size() > 0
                                {
                                    unsafe {
                                        alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_layout)
                                    };
                                }
                            }

                            // Only clean up value if the frame was already popped.
                            // If value_frame_on_stack is true, the TrackedBuffer frame above us
                            // will handle dropping and deallocating the value buffer.
                            if !*value_frame_on_stack && let Some(value_ptr) = value_ptr {
                                // Drop the value if it was initialized
                                if *value_initialized {
                                    unsafe {
                                        map_def.v().call_drop_in_place(value_ptr.assume_init())
                                    };
                                }
                                // Deallocate the value buffer
                                if let Ok(value_layout) = map_def.v().layout.sized_layout()
                                    && value_layout.size() > 0
                                {
                                    unsafe {
                                        alloc::alloc::dealloc(
                                            value_ptr.as_mut_byte_ptr(),
                                            value_layout,
                                        )
                                    };
                                }
                            }
                        }
                    }
                    MapInsertState::Idle => {}
                }
            }
            Tracker::Set { .. } => {
                // Drop the initialized Set
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::Option {
                building_inner,
                pending_inner,
            } => {
                // Clean up pending inner value if it was never finalized
                let had_pending = pending_inner.is_some();
                if let Some(inner_ptr) = pending_inner.take()
                    && let Def::Option(option_def) = self.allocated.shape().def
                {
                    // Drop the inner value
                    unsafe { option_def.t.call_drop_in_place(inner_ptr.assume_init()) };
                    // Deallocate the inner buffer
                    if let Ok(layout) = option_def.t.layout.sized_layout()
                        && layout.size() > 0
                    {
                        unsafe { alloc::alloc::dealloc(inner_ptr.as_mut_byte_ptr(), layout) };
                    }
                }
                // If we're building the inner value, it will be handled by the Option vtable
                // No special cleanup needed here as the Option will either be properly
                // initialized or remain uninitialized
                if !*building_inner && !had_pending {
                    // Option is fully initialized (no pending), drop it normally
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::Result { building_inner, .. } => {
                // If we're building the inner value, it will be handled by the Result vtable
                // No special cleanup needed here as the Result will either be properly
                // initialized or remain uninitialized
                if !*building_inner {
                    // Result is fully initialized, drop it normally
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
            Tracker::DynamicValue { state } => {
                // Clean up pending_entries if this is an Object
                if let DynamicValueState::Object {
                    pending_entries, ..
                } = state
                {
                    // Drop and deallocate any pending values that weren't inserted
                    if let Def::DynamicValue(dyn_def) = self.allocated.shape().def {
                        let value_shape = self.allocated.shape(); // Value entries are same shape
                        for (_key, value_ptr) in pending_entries.drain(..) {
                            // Drop the value
                            unsafe {
                                value_shape.call_drop_in_place(value_ptr.assume_init());
                            }
                            // Deallocate the value buffer
                            if let Ok(layout) = value_shape.layout.sized_layout()
                                && layout.size() > 0
                            {
                                unsafe {
                                    alloc::alloc::dealloc(value_ptr.as_mut_byte_ptr(), layout);
                                }
                            }
                        }
                        // Note: keys are Strings and will be dropped when pending_entries is dropped
                        let _ = dyn_def; // silence unused warning
                    }
                }

                // Clean up pending_elements if this is an Array
                if let DynamicValueState::Array {
                    pending_elements, ..
                } = state
                {
                    // Drop and deallocate any pending elements that weren't inserted
                    let element_shape = self.allocated.shape(); // Array elements are same shape
                    for element_ptr in pending_elements.drain(..) {
                        // Drop the element
                        unsafe {
                            element_shape.call_drop_in_place(element_ptr.assume_init());
                        }
                        // Deallocate the element buffer
                        if let Ok(layout) = element_shape.layout.sized_layout()
                            && layout.size() > 0
                        {
                            unsafe {
                                alloc::alloc::dealloc(element_ptr.as_mut_byte_ptr(), layout);
                            }
                        }
                    }
                }

                // Drop if initialized
                if self.is_init {
                    let result = unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                    if result.is_none() {
                        // This would be a bug - DynamicValue should always have drop_in_place
                        panic!(
                            "DynamicValue type {} has no drop_in_place implementation",
                            self.allocated.shape()
                        );
                    }
                }
            }
            Tracker::Inner { .. } => {
                // Inner wrapper - drop if initialized
                if self.is_init {
                    unsafe {
                        self.allocated
                            .shape()
                            .call_drop_in_place(self.data.assume_init())
                    };
                }
            }
        }

        self.is_init = false;
        self.tracker = Tracker::Scalar;
    }

    /// Deinitialize any initialized value for REPLACEMENT purposes.
    ///
    /// Unlike `deinit()` which is used during error cleanup, this method is used when
    /// we're about to overwrite a value with a new one (e.g., in `set_shape`).
    ///
    /// The difference is important for Field frames with simple trackers:
    /// - During cleanup: parent struct will drop all initialized fields, so Field frames skip dropping
    /// - During replacement: we're about to overwrite, so we MUST drop the old value
    ///
    /// For BorrowedInPlace frames: same logic applies - we must drop when replacing.
    fn deinit_for_replace(&mut self) {
        // For BorrowedInPlace frames, deinit() skips dropping (parent owns on cleanup).
        // But when REPLACING a value, we must drop the old value first.
        if matches!(self.ownership, FrameOwnership::BorrowedInPlace) && self.is_init {
            unsafe {
                self.allocated
                    .shape()
                    .call_drop_in_place(self.data.assume_init());
            }

            // CRITICAL: For DynamicValue (e.g., facet_value::Value), the parent Object's
            // HashMap entry still points to this location. If we just drop and leave garbage,
            // the parent will try to drop that garbage when it's cleaned up, causing
            // use-after-free. We must reinitialize to a safe default (Null) so the parent
            // can safely drop it later.
            if let Def::DynamicValue(dyn_def) = &self.allocated.shape().def {
                unsafe {
                    (dyn_def.vtable.set_null)(self.data);
                }
                // Keep is_init = true since we just initialized it to Null
                self.tracker = Tracker::DynamicValue {
                    state: DynamicValueState::Scalar,
                };
                return;
            }

            self.is_init = false;
            self.tracker = Tracker::Scalar;
            return;
        }

        // Field frames handle their own cleanup in deinit() - no special handling needed here.

        // All other cases: use normal deinit
        self.deinit();
    }

    /// This must be called after (fully) initializing a value.
    ///
    /// This sets `is_init` to `true` to indicate the value is initialized.
    /// Composite types (structs, enums, etc.) might be handled differently.
    ///
    /// # Safety
    ///
    /// This should only be called when `self.data` has been actually initialized.
    const unsafe fn mark_as_init(&mut self) {
        self.is_init = true;
    }

    /// Deallocate the memory associated with this frame, if it owns it.
    ///
    /// The memory has to be deinitialized first, see [Frame::deinit]
    fn dealloc(self) {
        // Only deallocate if this frame owns its memory
        if !self.ownership.needs_dealloc() {
            return;
        }

        // If we need to deallocate, the frame must be deinitialized first
        if self.is_init {
            unreachable!("a frame has to be deinitialized before being deallocated")
        }

        // Deallocate using the actual allocated size (not derived from shape)
        if self.allocated.allocated_size() > 0 {
            // Use the shape for alignment, but the stored size for the actual allocation
            if let Ok(layout) = self.allocated.shape().layout.sized_layout() {
                let actual_layout = core::alloc::Layout::from_size_align(
                    self.allocated.allocated_size(),
                    layout.align(),
                )
                .expect("allocated_size must be valid");
                unsafe { alloc::alloc::dealloc(self.data.as_mut_byte_ptr(), actual_layout) };
            }
        }
    }

    /// Fill in defaults for any unset fields that have default values.
    ///
    /// This handles:
    /// - Container-level defaults (when no fields set and struct has Default impl)
    /// - Fields with `#[facet(default = ...)]` - uses the explicit default function
    /// - Fields with `#[facet(default)]` - uses the type's Default impl
    /// - `Option<T>` fields - default to None
    ///
    /// Returns Ok(()) if successful, or an error if a field has `#[facet(default)]`
    /// but no default implementation is available.
    fn fill_defaults(&mut self) -> Result<(), ReflectErrorKind> {
        // First, check if we need to upgrade from Scalar to Struct tracker
        // This happens when no fields were visited at all in deferred mode
        if !self.is_init
            && matches!(self.tracker, Tracker::Scalar)
            && let Type::User(UserType::Struct(struct_type)) = self.allocated.shape().ty
        {
            // If no fields were visited and the container has a default, use it
            // SAFETY: We're about to initialize the entire struct with its default value
            if unsafe { self.allocated.shape().call_default_in_place(self.data) }.is_some() {
                self.is_init = true;
                return Ok(());
            }
            // Otherwise initialize the struct tracker with empty iset
            self.tracker = Tracker::Struct {
                iset: ISet::new(struct_type.fields.len()),
                current_child: None,
            };
        }

        // Handle Option types with Scalar tracker - default to None
        // This happens in deferred mode when an Option field was never touched
        if !self.is_init
            && matches!(self.tracker, Tracker::Scalar)
            && matches!(self.allocated.shape().def, Def::Option(_))
        {
            // SAFETY: Option<T> always implements Default (as None)
            if unsafe { self.allocated.shape().call_default_in_place(self.data) }.is_some() {
                self.is_init = true;
                return Ok(());
            }
        }

        match &mut self.tracker {
            Tracker::Struct { iset, .. } => {
                if let Type::User(UserType::Struct(struct_type)) = self.allocated.shape().ty {
                    // Fast path: if ALL fields are set, nothing to do
                    if iset.all_set(struct_type.fields.len()) {
                        return Ok(());
                    }

                    // Check if NO fields have been set and the container has a default
                    let no_fields_set = (0..struct_type.fields.len()).all(|i| !iset.get(i));
                    if no_fields_set {
                        // SAFETY: We're about to initialize the entire struct with its default value
                        if unsafe { self.allocated.shape().call_default_in_place(self.data) }
                            .is_some()
                        {
                            self.tracker = Tracker::Scalar;
                            self.is_init = true;
                            return Ok(());
                        }
                    }

                    // Check if the container has #[facet(default)] attribute
                    let container_has_default = self.allocated.shape().has_default_attr();

                    // Fill defaults for individual fields
                    for (idx, field) in struct_type.fields.iter().enumerate() {
                        // Skip already-initialized fields
                        if iset.get(idx) {
                            continue;
                        }

                        // Calculate field pointer
                        let field_ptr = unsafe { self.data.field_uninit(field.offset) };

                        // Try to initialize with default
                        if unsafe {
                            Self::try_init_field_default(field, field_ptr, container_has_default)
                        } {
                            // Mark field as initialized
                            iset.set(idx);
                        } else if field.has_default() {
                            // Field has #[facet(default)] but we couldn't find a default function.
                            // This happens with opaque types that don't have default_in_place.
                            return Err(ReflectErrorKind::DefaultAttrButNoDefaultImpl {
                                shape: field.shape(),
                            });
                        }
                    }
                }
            }
            Tracker::Enum { variant, data, .. } => {
                // Fast path: if ALL fields are set, nothing to do
                let num_fields = variant.data.fields.len();
                if num_fields == 0 || data.all_set(num_fields) {
                    return Ok(());
                }

                // Check if the container has #[facet(default)] attribute
                let container_has_default = self.allocated.shape().has_default_attr();

                // Handle enum variant fields
                for (idx, field) in variant.data.fields.iter().enumerate() {
                    // Skip already-initialized fields
                    if data.get(idx) {
                        continue;
                    }

                    // Calculate field pointer within the variant data
                    let field_ptr = unsafe { self.data.field_uninit(field.offset) };

                    // Try to initialize with default
                    if unsafe {
                        Self::try_init_field_default(field, field_ptr, container_has_default)
                    } {
                        // Mark field as initialized
                        data.set(idx);
                    } else if field.has_default() {
                        // Field has #[facet(default)] but we couldn't find a default function.
                        return Err(ReflectErrorKind::DefaultAttrButNoDefaultImpl {
                            shape: field.shape(),
                        });
                    }
                }
            }
            // Other tracker types don't have fields with defaults
            _ => {}
        }
        Ok(())
    }

    /// Initialize a field with its default value if one is available.
    ///
    /// Priority:
    /// 1. Explicit field-level default_fn (from `#[facet(default = ...)]`)
    /// 2. Type-level default_in_place (from Default impl, including `Option<T>`)
    ///    but only if the field has the DEFAULT flag
    /// 3. Container-level default: if the container has `#[facet(default)]` and
    ///    the field's type implements Default, use that
    /// 4. Special cases: `Option<T>` (defaults to None), () (unit type)
    ///
    /// Returns true if a default was applied, false otherwise.
    ///
    /// # Safety
    ///
    /// `field_ptr` must point to uninitialized memory of the appropriate type.
    unsafe fn try_init_field_default(
        field: &Field,
        field_ptr: PtrUninit,
        container_has_default: bool,
    ) -> bool {
        use facet_core::DefaultSource;

        // First check for explicit field-level default
        if let Some(default_source) = field.default {
            match default_source {
                DefaultSource::Custom(default_fn) => {
                    // Custom default function - it expects PtrUninit
                    unsafe { default_fn(field_ptr) };
                    return true;
                }
                DefaultSource::FromTrait => {
                    // Use the type's Default trait
                    if unsafe { field.shape().call_default_in_place(field_ptr) }.is_some() {
                        return true;
                    }
                }
            }
        }

        // If container has #[facet(default)] and the field's type implements Default,
        // use the type's Default impl. This allows `#[facet(default)]` on a struct to
        // mean "use Default for any missing fields whose types implement Default".
        if container_has_default
            && unsafe { field.shape().call_default_in_place(field_ptr) }.is_some()
        {
            return true;
        }

        // Special case: Option<T> always defaults to None, even without explicit #[facet(default)]
        // This is because Option is fundamentally "optional" - if not set, it should be None
        if matches!(field.shape().def, Def::Option(_))
            && unsafe { field.shape().call_default_in_place(field_ptr) }.is_some()
        {
            return true;
        }

        // Special case: () unit type always defaults to ()
        if field.shape().is_type::<()>()
            && unsafe { field.shape().call_default_in_place(field_ptr) }.is_some()
        {
            return true;
        }

        // Special case: Collection types (Vec, HashMap, HashSet, etc.) default to empty
        // These types have obvious "zero values" and it's almost always what you want
        // when deserializing data where the collection is simply absent.
        if matches!(field.shape().def, Def::List(_) | Def::Map(_) | Def::Set(_))
            && unsafe { field.shape().call_default_in_place(field_ptr) }.is_some()
        {
            return true;
        }

        false
    }

    /// Drain all initialized elements from the rope into the Vec.
    ///
    /// This is called when finalizing a list that used rope storage. Elements were
    /// built in stable rope chunks to allow deferred processing; now we move them
    /// into the actual Vec.
    ///
    /// # Safety
    ///
    /// The rope must contain only initialized elements (via `mark_last_initialized`).
    /// The list_data must point to an initialized Vec with capacity for the elements.
    fn drain_rope_into_vec(
        mut rope: ListRope,
        list_def: &facet_core::ListDef,
        list_data: PtrUninit,
    ) -> Result<(), ReflectErrorKind> {
        let count = rope.initialized_count();
        if count == 0 {
            return Ok(());
        }

        let push_fn = list_def
            .push()
            .ok_or_else(|| ReflectErrorKind::OperationFailed {
                shape: list_def.t(),
                operation: "List missing push function for rope drain",
            })?;

        // SAFETY: list_data points to initialized Vec (is_init was true)
        let list_ptr = unsafe { list_data.assume_init() };

        // Reserve space if available (optimization, not required)
        if let Some(reserve_fn) = list_def.reserve() {
            unsafe {
                reserve_fn(list_ptr, count);
            }
        }

        // Move each element from rope to Vec
        // SAFETY: rope contains `count` initialized elements
        unsafe {
            rope.drain_into(|element_ptr| {
                push_fn(
                    facet_core::PtrMut::new(list_ptr.as_mut_byte_ptr()),
                    facet_core::PtrMut::new(element_ptr.as_ptr()),
                );
            });
        }

        Ok(())
    }

    /// Insert all pending key-value entries into the map.
    ///
    /// This is called when finalizing a map that used delayed insertion. Entries were
    /// kept in pending_entries to allow deferred processing; now we insert them into
    /// the actual map and deallocate the temporary buffers.
    fn drain_pending_into_map(
        pending_entries: &mut Vec<(PtrUninit, PtrUninit)>,
        map_def: &facet_core::MapDef,
        map_data: PtrUninit,
    ) -> Result<(), ReflectErrorKind> {
        let insert_fn = map_def.vtable.insert;

        // SAFETY: map_data points to initialized map (is_init was true)
        let map_ptr = unsafe { map_data.assume_init() };

        for (key_ptr, value_ptr) in pending_entries.drain(..) {
            // Insert the key-value pair
            unsafe {
                insert_fn(
                    facet_core::PtrMut::new(map_ptr.as_mut_byte_ptr()),
                    facet_core::PtrMut::new(key_ptr.as_mut_byte_ptr()),
                    facet_core::PtrMut::new(value_ptr.as_mut_byte_ptr()),
                );
            }

            // Deallocate the temporary buffers (insert moved the data)
            if let Ok(key_layout) = map_def.k().layout.sized_layout()
                && key_layout.size() > 0
            {
                unsafe { alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_layout) };
            }
            if let Ok(value_layout) = map_def.v().layout.sized_layout()
                && value_layout.size() > 0
            {
                unsafe { alloc::alloc::dealloc(value_ptr.as_mut_byte_ptr(), value_layout) };
            }
        }

        Ok(())
    }

    /// Complete an Option by moving the pending inner value into it.
    ///
    /// This is called when finalizing an Option that used deferred init_some.
    /// The inner value was kept in stable memory for deferred processing;
    /// now we move it into the Option and deallocate the temporary buffer.
    fn complete_pending_option(
        option_def: facet_core::OptionDef,
        option_data: PtrUninit,
        inner_ptr: PtrUninit,
    ) -> Result<(), ReflectErrorKind> {
        let init_some_fn = option_def.vtable.init_some;
        let inner_shape = option_def.t;

        // The inner_ptr contains the initialized inner value
        let inner_value_ptr = unsafe { inner_ptr.assume_init() };

        // Initialize the Option as Some(inner_value)
        unsafe {
            init_some_fn(option_data, inner_value_ptr);
        }

        // Deallocate the inner value's memory since init_some_fn moved it
        if let Ok(layout) = inner_shape.layout.sized_layout()
            && layout.size() > 0
        {
            unsafe { alloc::alloc::dealloc(inner_ptr.as_mut_byte_ptr(), layout) };
        }

        Ok(())
    }

    fn complete_pending_smart_pointer(
        smart_ptr_shape: &'static Shape,
        smart_ptr_def: facet_core::PointerDef,
        smart_ptr_data: PtrUninit,
        inner_ptr: PtrUninit,
    ) -> Result<(), ReflectErrorKind> {
        // Check for sized pointee case first (uses new_into_fn)
        if let Some(new_into_fn) = smart_ptr_def.vtable.new_into_fn {
            let Some(inner_shape) = smart_ptr_def.pointee else {
                return Err(ReflectErrorKind::OperationFailed {
                    shape: smart_ptr_shape,
                    operation: "SmartPointer missing pointee shape",
                });
            };

            // The inner_ptr contains the initialized inner value
            let _ = unsafe { inner_ptr.assume_init() };

            // Initialize the SmartPointer with the inner value
            unsafe {
                new_into_fn(smart_ptr_data, PtrMut::new(inner_ptr.as_mut_byte_ptr()));
            }

            // Deallocate the inner value's memory since new_into_fn moved it
            if let Ok(layout) = inner_shape.layout.sized_layout()
                && layout.size() > 0
            {
                unsafe { alloc::alloc::dealloc(inner_ptr.as_mut_byte_ptr(), layout) };
            }

            return Ok(());
        }

        // Check for unsized pointee case: String -> Arc<str>/Box<str>/Rc<str>
        if let Some(pointee) = smart_ptr_def.pointee()
            && pointee.is_shape(str::SHAPE)
        {
            use alloc::{rc::Rc, string::String, sync::Arc};
            use facet_core::KnownPointer;

            let Some(known) = smart_ptr_def.known else {
                return Err(ReflectErrorKind::OperationFailed {
                    shape: smart_ptr_shape,
                    operation: "SmartPointer<str> missing known pointer type",
                });
            };

            // Read the String value from inner_ptr
            let string_ptr = inner_ptr.as_mut_byte_ptr() as *mut String;
            let string_value = unsafe { core::ptr::read(string_ptr) };

            // Convert to the appropriate smart pointer type
            match known {
                KnownPointer::Box => {
                    let boxed: alloc::boxed::Box<str> = string_value.into_boxed_str();
                    unsafe {
                        core::ptr::write(
                            smart_ptr_data.as_mut_byte_ptr() as *mut alloc::boxed::Box<str>,
                            boxed,
                        );
                    }
                }
                KnownPointer::Arc => {
                    let arc: Arc<str> = Arc::from(string_value.into_boxed_str());
                    unsafe {
                        core::ptr::write(smart_ptr_data.as_mut_byte_ptr() as *mut Arc<str>, arc);
                    }
                }
                KnownPointer::Rc => {
                    let rc: Rc<str> = Rc::from(string_value.into_boxed_str());
                    unsafe {
                        core::ptr::write(smart_ptr_data.as_mut_byte_ptr() as *mut Rc<str>, rc);
                    }
                }
                _ => {
                    return Err(ReflectErrorKind::OperationFailed {
                        shape: smart_ptr_shape,
                        operation: "Unsupported SmartPointer<str> type",
                    });
                }
            }

            // Deallocate the String's memory (we moved the data out via ptr::read)
            let string_layout = alloc::string::String::SHAPE.layout.sized_layout().unwrap();
            if string_layout.size() > 0 {
                unsafe { alloc::alloc::dealloc(inner_ptr.as_mut_byte_ptr(), string_layout) };
            }

            return Ok(());
        }

        Err(ReflectErrorKind::OperationFailed {
            shape: smart_ptr_shape,
            operation: "SmartPointer missing new_into_fn and not a supported unsized type",
        })
    }

    /// Returns an error if the value is not fully initialized.
    /// For lists with rope storage, drains the rope into the Vec.
    /// For maps with pending entries, drains the entries into the map.
    /// For options with pending inner values, calls init_some.
    fn require_full_initialization(&mut self) -> Result<(), ReflectErrorKind> {
        match &mut self.tracker {
            Tracker::Scalar => {
                if self.is_init {
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::Array { iset, .. } => {
                match self.allocated.shape().ty {
                    Type::Sequence(facet_core::SequenceType::Array(array_def)) => {
                        // Check if all array elements are initialized
                        if (0..array_def.n).all(|idx| iset.get(idx)) {
                            Ok(())
                        } else {
                            Err(ReflectErrorKind::UninitializedValue {
                                shape: self.allocated.shape(),
                            })
                        }
                    }
                    _ => Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    }),
                }
            }
            Tracker::Struct { iset, .. } => {
                match self.allocated.shape().ty {
                    Type::User(UserType::Struct(struct_type)) => {
                        if iset.all_set(struct_type.fields.len()) {
                            Ok(())
                        } else {
                            // Find index of the first bit not set
                            let first_missing_idx =
                                (0..struct_type.fields.len()).find(|&idx| !iset.get(idx));
                            if let Some(missing_idx) = first_missing_idx {
                                let field_name = struct_type.fields[missing_idx].name;
                                Err(ReflectErrorKind::UninitializedField {
                                    shape: self.allocated.shape(),
                                    field_name,
                                })
                            } else {
                                // fallback, something went wrong
                                Err(ReflectErrorKind::UninitializedValue {
                                    shape: self.allocated.shape(),
                                })
                            }
                        }
                    }
                    _ => Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    }),
                }
            }
            Tracker::Enum { variant, data, .. } => {
                // Check if all fields of the variant are initialized
                let num_fields = variant.data.fields.len();
                if num_fields == 0 {
                    // Unit variant, always initialized
                    Ok(())
                } else if (0..num_fields).all(|idx| data.get(idx)) {
                    Ok(())
                } else {
                    // Find the first uninitialized field
                    let first_missing_idx = (0..num_fields).find(|&idx| !data.get(idx));
                    if let Some(missing_idx) = first_missing_idx {
                        let field_name = variant.data.fields[missing_idx].name;
                        Err(ReflectErrorKind::UninitializedField {
                            shape: self.allocated.shape(),
                            field_name,
                        })
                    } else {
                        Err(ReflectErrorKind::UninitializedValue {
                            shape: self.allocated.shape(),
                        })
                    }
                }
            }
            Tracker::SmartPointer {
                building_inner,
                pending_inner,
            } => {
                if *building_inner {
                    // Inner value is still being built
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else if let Some(inner_ptr) = pending_inner.take() {
                    // Finalize the pending inner value
                    let smart_ptr_shape = self.allocated.shape();
                    if let Def::Pointer(smart_ptr_def) = smart_ptr_shape.def {
                        Self::complete_pending_smart_pointer(
                            smart_ptr_shape,
                            smart_ptr_def,
                            self.data,
                            inner_ptr,
                        )?;
                        self.is_init = true;
                        Ok(())
                    } else {
                        Err(ReflectErrorKind::OperationFailed {
                            shape: smart_ptr_shape,
                            operation: "SmartPointer frame without SmartPointer definition",
                        })
                    }
                } else if self.is_init {
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::SmartPointerSlice { building_item, .. } => {
                if *building_item {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else {
                    Ok(())
                }
            }
            Tracker::List {
                current_child,
                rope,
            } => {
                if self.is_init && current_child.is_none() {
                    // Drain rope into Vec if we have elements stored there
                    if let Some(rope) = rope.take()
                        && let Def::List(list_def) = self.allocated.shape().def
                    {
                        Self::drain_rope_into_vec(rope, &list_def, self.data)?;
                    }
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::Map {
                insert_state,
                pending_entries,
                ..
            } => {
                if self.is_init && matches!(insert_state, MapInsertState::Idle) {
                    // Insert all pending entries into the map
                    if !pending_entries.is_empty()
                        && let Def::Map(map_def) = self.allocated.shape().def
                    {
                        Self::drain_pending_into_map(pending_entries, &map_def, self.data)?;
                    }
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::Set { current_child } => {
                if self.is_init && !*current_child {
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::Option {
                building_inner,
                pending_inner,
            } => {
                if *building_inner {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else {
                    // Finalize pending init_some if we have a pending inner value
                    if let Some(inner_ptr) = pending_inner.take()
                        && let Def::Option(option_def) = self.allocated.shape().def
                    {
                        Self::complete_pending_option(option_def, self.data, inner_ptr)?;
                    }
                    Ok(())
                }
            }
            Tracker::Result { building_inner, .. } => {
                if *building_inner {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else {
                    Ok(())
                }
            }
            Tracker::Inner { building_inner } => {
                if *building_inner {
                    // Inner value is still being built
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else if self.is_init {
                    Ok(())
                } else {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                }
            }
            Tracker::DynamicValue { state } => {
                if matches!(state, DynamicValueState::Uninit) {
                    Err(ReflectErrorKind::UninitializedValue {
                        shape: self.allocated.shape(),
                    })
                } else {
                    // Insert pending entries for Object state
                    if let DynamicValueState::Object {
                        pending_entries,
                        insert_state,
                    } = state
                    {
                        if !matches!(insert_state, DynamicObjectInsertState::Idle) {
                            return Err(ReflectErrorKind::UninitializedValue {
                                shape: self.allocated.shape(),
                            });
                        }

                        if !pending_entries.is_empty()
                            && let Def::DynamicValue(dyn_def) = self.allocated.shape().def
                        {
                            let object_ptr = unsafe { self.data.assume_init() };
                            let value_shape = self.allocated.shape();

                            for (key, value_ptr) in pending_entries.drain(..) {
                                // Insert the entry
                                unsafe {
                                    (dyn_def.vtable.insert_object_entry)(
                                        object_ptr,
                                        &key,
                                        value_ptr.assume_init(),
                                    );
                                }
                                // Deallocate the value buffer (insert_object_entry moved the value)
                                if let Ok(layout) = value_shape.layout.sized_layout()
                                    && layout.size() > 0
                                {
                                    unsafe {
                                        alloc::alloc::dealloc(value_ptr.as_mut_byte_ptr(), layout);
                                    }
                                }
                            }
                        }
                    }

                    // Insert pending elements for Array state
                    if let DynamicValueState::Array {
                        pending_elements,
                        building_element,
                    } = state
                    {
                        if *building_element {
                            return Err(ReflectErrorKind::UninitializedValue {
                                shape: self.allocated.shape(),
                            });
                        }

                        if !pending_elements.is_empty()
                            && let Def::DynamicValue(dyn_def) = self.allocated.shape().def
                        {
                            let array_ptr = unsafe { self.data.assume_init() };
                            let element_shape = self.allocated.shape();

                            for element_ptr in pending_elements.drain(..) {
                                // Push the element into the array
                                unsafe {
                                    (dyn_def.vtable.push_array_element)(
                                        array_ptr,
                                        element_ptr.assume_init(),
                                    );
                                }
                                // Deallocate the element buffer (push_array_element moved the value)
                                if let Ok(layout) = element_shape.layout.sized_layout()
                                    && layout.size() > 0
                                {
                                    unsafe {
                                        alloc::alloc::dealloc(
                                            element_ptr.as_mut_byte_ptr(),
                                            layout,
                                        );
                                    }
                                }
                            }
                        }
                    }

                    Ok(())
                }
            }
        }
    }

    /// Fill defaults and check required fields in a single pass using precomputed plans.
    ///
    /// This replaces the separate `fill_defaults` + `require_full_initialization` calls
    /// with a single iteration over the precomputed `FieldInitPlan` list.
    ///
    /// # Arguments
    /// * `plans` - Precomputed field initialization plans from TypePlan
    /// * `num_fields` - Total number of fields (from StructPlan/VariantPlanMeta)
    /// * `type_plan_core` - Reference to the TypePlanCore for resolving validators
    ///
    /// # Returns
    /// `Ok(())` if all required fields are set (or filled with defaults), or an error
    /// describing the first missing required field.
    #[allow(unsafe_code)]
    fn fill_and_require_fields(
        &mut self,
        plans: &[FieldInitPlan],
        num_fields: usize,
        type_plan_core: &TypePlanCore,
    ) -> Result<(), ReflectErrorKind> {
        // With lazy tracker initialization, structs start with Tracker::Scalar.
        // If is_init is true with Scalar, the struct was set wholesale - nothing to do.
        // If is_init is false, we need to upgrade to Tracker::Struct to track fields.
        if !self.is_init
            && matches!(self.tracker, Tracker::Scalar)
            && matches!(self.allocated.shape().ty, Type::User(UserType::Struct(_)))
        {
            // Try container-level default first
            if unsafe { self.allocated.shape().call_default_in_place(self.data) }.is_some() {
                self.is_init = true;
                return Ok(());
            }
            // Upgrade to Tracker::Struct for field-by-field tracking
            self.tracker = Tracker::Struct {
                iset: ISet::new(num_fields),
                current_child: None,
            };
        }

        // Get the iset based on tracker type
        let iset = match &mut self.tracker {
            Tracker::Struct { iset, .. } => iset,
            Tracker::Enum { data, .. } => data,
            // Scalar with is_init=true means struct was set wholesale - all fields initialized
            Tracker::Scalar if self.is_init => return Ok(()),
            // Other tracker types don't use field_init_plans
            _ => return Ok(()),
        };

        // Fast path: if all fields are already set, no defaults needed.
        // But validators still need to run.
        let all_fields_set = iset.all_set(num_fields);

        for plan in plans {
            if !all_fields_set && !iset.get(plan.index) {
                // Field not set - handle according to fill rule
                match &plan.fill_rule {
                    FillRule::Defaultable(default) => {
                        // Calculate field pointer
                        let field_ptr = unsafe { self.data.field_uninit(plan.offset) };

                        // Call the appropriate default function
                        let success = match default {
                            FieldDefault::Custom(default_fn) => {
                                // SAFETY: default_fn writes to uninitialized memory
                                unsafe { default_fn(field_ptr) };
                                true
                            }
                            FieldDefault::FromTrait(shape) => {
                                // SAFETY: call_default_in_place writes to uninitialized memory
                                unsafe { shape.call_default_in_place(field_ptr) }.is_some()
                            }
                        };

                        if success {
                            iset.set(plan.index);
                        } else {
                            return Err(ReflectErrorKind::UninitializedField {
                                shape: self.allocated.shape(),
                                field_name: plan.name,
                            });
                        }
                    }
                    FillRule::Required => {
                        return Err(ReflectErrorKind::UninitializedField {
                            shape: self.allocated.shape(),
                            field_name: plan.name,
                        });
                    }
                }
            }

            // Run validators on the (now initialized) field
            if !plan.validators.is_empty() {
                let field_ptr = unsafe { self.data.field_init(plan.offset) };
                for validator in type_plan_core.validators(plan.validators) {
                    validator.run(field_ptr.into(), plan.name, self.allocated.shape())?;
                }
            }
        }

        Ok(())
    }

    /// Get the [EnumType] of the frame's shape, if it is an enum type
    pub(crate) const fn get_enum_type(&self) -> Result<EnumType, ReflectErrorKind> {
        match self.allocated.shape().ty {
            Type::User(UserType::Enum(e)) => Ok(e),
            _ => Err(ReflectErrorKind::WasNotA {
                expected: "enum",
                actual: self.allocated.shape(),
            }),
        }
    }

    pub(crate) fn get_field(&self) -> Option<&Field> {
        match self.allocated.shape().ty {
            Type::User(user_type) => match user_type {
                UserType::Struct(struct_type) => {
                    // Try to get currently active field index
                    if let Tracker::Struct {
                        current_child: Some(idx),
                        ..
                    } = &self.tracker
                    {
                        struct_type.fields.get(*idx)
                    } else {
                        None
                    }
                }
                UserType::Enum(_enum_type) => {
                    if let Tracker::Enum {
                        variant,
                        current_child: Some(idx),
                        ..
                    } = &self.tracker
                    {
                        variant.data.fields.get(*idx)
                    } else {
                        None
                    }
                }
                _ => None,
            },
            _ => None,
        }
    }
}

// Convenience methods on Partial for accessing FrameMode internals.
// These help minimize changes to the rest of the codebase during the refactor.
impl<'facet, const BORROW: bool> Partial<'facet, BORROW> {
    /// Get a reference to the frame stack.
    #[inline]
    pub(crate) const fn frames(&self) -> &Vec<Frame> {
        self.mode.stack()
    }

    /// Get a mutable reference to the frame stack.
    #[inline]
    pub(crate) fn frames_mut(&mut self) -> &mut Vec<Frame> {
        self.mode.stack_mut()
    }

    /// Check if we're in deferred mode.
    #[inline]
    pub const fn is_deferred(&self) -> bool {
        self.mode.is_deferred()
    }

    /// Get the start depth if in deferred mode.
    #[inline]
    pub(crate) const fn start_depth(&self) -> Option<usize> {
        self.mode.start_depth()
    }

    /// Derive the path from the current frame stack.
    ///
    /// Compute the navigation path for deferred mode storage and lookup.
    /// The returned `Path` is anchored to the root shape for proper type context.
    ///
    /// This extracts Field steps from struct/enum frames and Index steps from
    /// array/list frames. Option wrappers, smart pointers (Box, Rc, etc.), and
    /// other transparent types don't add path steps.
    ///
    /// This MUST match the storage path computation in end() for consistency.
    pub(crate) fn derive_path(&self) -> Path {
        // Get the root shape from the first frame
        let root_shape = self
            .frames()
            .first()
            .map(|f| f.allocated.shape())
            .unwrap_or_else(|| {
                // Fallback to unit type shape if no frames (shouldn't happen in practice)
                <() as facet_core::Facet>::SHAPE
            });

        let mut path = Path::new(root_shape);

        // Walk ALL frames, extracting navigation steps
        // This matches the storage path computation in end()
        let frames = self.frames();
        for (frame_idx, frame) in frames.iter().enumerate() {
            match &frame.tracker {
                Tracker::Struct {
                    current_child: Some(idx),
                    ..
                } => {
                    path.push(PathStep::Field(*idx as u32));
                }
                Tracker::Enum {
                    current_child: Some(idx),
                    ..
                } => {
                    path.push(PathStep::Field(*idx as u32));
                }
                Tracker::List {
                    current_child: Some(idx),
                    ..
                } => {
                    path.push(PathStep::Index(*idx as u32));
                }
                Tracker::Array {
                    current_child: Some(idx),
                    ..
                } => {
                    path.push(PathStep::Index(*idx as u32));
                }
                Tracker::Option {
                    building_inner: true,
                    ..
                } => {
                    // Option with building_inner contributes OptionSome to path
                    path.push(PathStep::OptionSome);
                }
                Tracker::SmartPointer {
                    building_inner: true,
                    ..
                } => {
                    // SmartPointer with building_inner contributes Deref to path
                    path.push(PathStep::Deref);
                }
                Tracker::SmartPointerSlice {
                    current_child: Some(idx),
                    ..
                } => {
                    // SmartPointerSlice with current_child contributes Index to path
                    path.push(PathStep::Index(*idx as u32));
                }
                Tracker::Inner {
                    building_inner: true,
                } => {
                    // Inner with building_inner contributes Inner to path
                    path.push(PathStep::Inner);
                }
                Tracker::Map {
                    current_entry_index: Some(idx),
                    building_key,
                    ..
                } => {
                    // Map with active entry contributes MapKey or MapValue with entry index
                    if *building_key {
                        path.push(PathStep::MapKey(*idx as u32));
                    } else {
                        path.push(PathStep::MapValue(*idx as u32));
                    }
                }
                // Other tracker types (Set, Result, etc.)
                // don't contribute to the storage path - they're transparent wrappers
                _ => {}
            }

            // If the next frame is a proxy frame, add a Proxy step (matches end())
            if frame_idx + 1 < frames.len() && frames[frame_idx + 1].using_custom_deserialization {
                path.push(PathStep::Proxy);
            }
        }

        path
    }
}

impl<'facet, const BORROW: bool> Drop for Partial<'facet, BORROW> {
    fn drop(&mut self) {
        trace!("🧹 Partial is being dropped");

        // With the ownership transfer model:
        // - When we enter a field, parent's iset[idx] is cleared
        // - Parent won't try to drop fields with iset[idx] = false
        // - No double-free possible by construction

        // 1. Clean up stored frames from deferred state
        if let FrameMode::Deferred {
            stored_frames,
            stack,
            ..
        } = &mut self.mode
        {
            // Stored frames have ownership of their data (parent's iset was cleared).
            // IMPORTANT: Process in deepest-first order so children are dropped before parents.
            // Child frames have data pointers into parent memory, so parents must stay valid
            // until all their children are cleaned up.
            //
            // CRITICAL: Before dropping a child frame, we must mark the parent's field as
            // uninitialized. Otherwise, when we later drop the parent, it will try to drop
            // that field again, causing a double-free.
            let mut stored_frames = core::mem::take(stored_frames);
            let mut paths: Vec<_> = stored_frames.keys().cloned().collect();
            // Sort by path depth (number of steps), deepest first
            paths.sort_by_key(|p| core::cmp::Reverse(p.steps.len()));
            for path in paths {
                if let Some(mut frame) = stored_frames.remove(&path) {
                    // Before dropping this frame, update the parent to prevent double-free.
                    // The parent path is everything except the last step.
                    let parent_path = Path {
                        shape: path.shape,
                        steps: path.steps[..path.steps.len().saturating_sub(1)].to_vec(),
                    };

                    // Helper to find parent frame in stored_frames or stack
                    let find_parent_frame =
                        |stored: &mut alloc::collections::BTreeMap<Path, Frame>,
                         stk: &mut [Frame],
                         pp: &Path|
                         -> Option<*mut Frame> {
                            if let Some(pf) = stored.get_mut(pp) {
                                Some(pf as *mut Frame)
                            } else {
                                let idx = pp.steps.len();
                                stk.get_mut(idx).map(|f| f as *mut Frame)
                            }
                        };

                    match path.steps.last() {
                        Some(PathStep::Field(field_idx)) => {
                            let field_idx = *field_idx as usize;
                            if let Some(parent_ptr) =
                                find_parent_frame(&mut stored_frames, stack, &parent_path)
                            {
                                // SAFETY: parent_ptr is valid for the duration of this block
                                let parent_frame = unsafe { &mut *parent_ptr };
                                match &mut parent_frame.tracker {
                                    Tracker::Struct { iset, .. } => {
                                        iset.unset(field_idx);
                                    }
                                    Tracker::Enum { data, .. } => {
                                        data.unset(field_idx);
                                    }
                                    _ => {}
                                }
                            }
                        }
                        Some(PathStep::MapKey(entry_idx)) => {
                            // Map key frame - clear from parent's insert_state to prevent
                            // double-free. The key will be dropped by this frame's deinit.
                            let entry_idx = *entry_idx as usize;
                            if let Some(parent_ptr) =
                                find_parent_frame(&mut stored_frames, stack, &parent_path)
                            {
                                let parent_frame = unsafe { &mut *parent_ptr };
                                if let Tracker::Map {
                                    insert_state,
                                    pending_entries,
                                    ..
                                } = &mut parent_frame.tracker
                                {
                                    // If key is in insert_state, clear it
                                    if let MapInsertState::PushingKey {
                                        key_frame_on_stack, ..
                                    } = insert_state
                                    {
                                        *key_frame_on_stack = false;
                                    }
                                    // Also check if there's a pending entry with this key
                                    // that needs to have the key nullified
                                    if entry_idx < pending_entries.len() {
                                        // Remove this entry since we're handling cleanup here
                                        // The key will be dropped by this frame's deinit
                                        // The value frame will be handled separately
                                        // Mark the key as already-handled by setting to dangling
                                        // Actually, we'll clear the entire entry - the value
                                        // frame will be processed separately anyway
                                    }
                                }
                            }
                        }
                        Some(PathStep::MapValue(entry_idx)) => {
                            // Map value frame - remove the entry from pending_entries.
                            // The value is dropped by this frame's deinit.
                            // The key is dropped by the MapKey frame's deinit (processed separately).
                            let entry_idx = *entry_idx as usize;
                            if let Some(parent_ptr) =
                                find_parent_frame(&mut stored_frames, stack, &parent_path)
                            {
                                let parent_frame = unsafe { &mut *parent_ptr };
                                if let Tracker::Map {
                                    pending_entries, ..
                                } = &mut parent_frame.tracker
                                {
                                    // Remove the entry at this index if it exists.
                                    // Don't drop key/value here - they're handled by their
                                    // respective stored frames (MapKey and MapValue).
                                    if entry_idx < pending_entries.len() {
                                        pending_entries.remove(entry_idx);
                                    }
                                }
                            }
                        }
                        Some(PathStep::Index(_)) => {
                            // List element frames with RopeSlot ownership are handled by
                            // the deinit check for RopeSlot - they skip dropping since the
                            // rope owns the data. No parent update needed.
                        }
                        _ => {}
                    }
                    frame.deinit();
                    frame.dealloc();
                }
            }
        }

        // 2. Pop and deinit stack frames
        // CRITICAL: Before deiniting a child frame, we must mark the parent's field as
        // uninitialized. Otherwise, the parent will try to drop the field again.
        loop {
            let stack = self.mode.stack_mut();
            if stack.is_empty() {
                break;
            }

            let mut frame = stack.pop().unwrap();

            // If this frame has Field ownership, mark the parent's bit as unset
            // so the parent won't try to drop it again.
            if let FrameOwnership::Field { field_idx } = frame.ownership
                && let Some(parent_frame) = stack.last_mut()
            {
                match &mut parent_frame.tracker {
                    Tracker::Struct { iset, .. } => {
                        iset.unset(field_idx);
                    }
                    Tracker::Enum { data, .. } => {
                        data.unset(field_idx);
                    }
                    Tracker::Array { iset, .. } => {
                        iset.unset(field_idx);
                    }
                    _ => {}
                }
            }

            frame.deinit();
            frame.dealloc();
        }
    }
}

#[cfg(test)]
mod size_tests {
    use super::*;
    use core::mem::size_of;

    #[test]
    fn print_type_sizes() {
        eprintln!("\n=== Type Sizes ===");
        eprintln!("Frame: {} bytes", size_of::<Frame>());
        eprintln!("Tracker: {} bytes", size_of::<Tracker>());
        eprintln!("ISet: {} bytes", size_of::<ISet>());
        eprintln!("AllocatedShape: {} bytes", size_of::<AllocatedShape>());
        eprintln!("FrameOwnership: {} bytes", size_of::<FrameOwnership>());
        eprintln!("PtrUninit: {} bytes", size_of::<facet_core::PtrUninit>());
        eprintln!("Option<usize>: {} bytes", size_of::<Option<usize>>());
        eprintln!(
            "Option<&'static facet_core::ProxyDef>: {} bytes",
            size_of::<Option<&'static facet_core::ProxyDef>>()
        );
        eprintln!(
            "TypePlanNode: {} bytes",
            size_of::<typeplan::TypePlanNode>()
        );
        eprintln!("Vec<Frame>: {} bytes", size_of::<Vec<Frame>>());
        eprintln!("MapInsertState: {} bytes", size_of::<MapInsertState>());
        eprintln!(
            "DynamicValueState: {} bytes",
            size_of::<DynamicValueState>()
        );
        eprintln!("===================\n");
    }
}