shape-vm 0.3.2

Stack-based bytecode virtual machine for the Shape programming language
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
//! Type Tracking for Bytecode Compiler
//!
//! This module tracks known type information during compilation to enable
//! type-specialized code generation. When a variable's type is known at
//! compile time, the compiler can emit optimized opcodes for field access.
//!
//! # How Types Become Known
//!
//! Types are known in these situations:
//! - Explicit type annotation: `let x: Candle = ...`
//! - Constructor call: `let x = Candle { ... }`
//! - Object literal: `let x = { a: 1, b: 2 }` (inline struct type)
//! - Function with declared return type: `let x = get_candle()`
//!
//! # Usage
//!
//! The compiler uses this to emit typed field opcodes for dot access:
//! - `GetFieldTyped` (specialized): Direct slot access by precomputed offset
//! - `SetFieldTyped` (specialized): Direct slot update by precomputed offset
//! Generic `GetProp`/`SetProp` are reserved for non-dot operations (index/slice).
//!
//! # Storage Type Hints
//!
//! For JIT optimization, we track storage types:
//! - `StorageHint::NullableFloat64`: Option<f64> uses NaN sentinel
//! - `StorageHint::Float64`: Plain f64, no nullability
//!
//! # Strict-typing contract: `prove_native_kind` and `ProofGap`
//!
//! Every typed-opcode emission site must call [`prove_native_kind`] and
//! handle the [`ProofGap`] error. `ProofGap`'s constructor is private to
//! this module: emit code cannot fabricate "I proved it". The Rust type
//! system enforces the discipline.
//!
//! In Phases 2-4, the predicate panics in debug + test, returns a
//! compile error in release. There is no fallback path.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use shape_ast::ast::TypeAnnotation;
use shape_runtime::type_schema::{FieldType, SchemaId, TypeSchema, TypeSchemaRegistry};
use shape_runtime::type_system::{BuiltinTypes, StorageType};
use shape_value::v2::struct_layout::{FieldKind, StructLayout};

/// Numeric type known at compile time for typed opcode emission.
///
/// When the compiler can determine the numeric subtype of an expression,
/// it emits typed opcodes (e.g., `MulInt` instead of `Mul`) that skip
/// runtime type dispatch entirely.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericType {
    /// Integer (i64) — the default integer type
    Int,
    /// Width-specific integer (i8, u8, i16, u16, i32, u32, u64)
    IntWidth(shape_ast::IntWidth),
    /// Floating point (f64)
    Number,
    /// Exact decimal (rust_decimal::Decimal)
    Decimal,
}


// `NativeKind` (formerly `SlotKind`) is the single discriminator used at
// every typed-ABI boundary. Moved to `shape-value::native_kind` so that
// shape-runtime's marshal layer and shape-vm's compile-time proof share one
// type. See `docs/defections.md` 2026-05-06 (Phase 2b unified marshal).
pub use shape_value::NativeKind;

/// Backwards-compatible alias. Prefer `NativeKind` in new code.
pub type StorageHint = NativeKind;

/// Convert a runtime `StorageType` to its marshal-layer `NativeKind`.
///
/// Free function because `StorageType` lives in shape-runtime and
/// `NativeKind` lives in shape-value — Rust's orphan rule forbids an
/// inherent `impl NativeKind { fn from_storage_type … }` here, and the
/// previous `From<StorageType> for NativeKind` impl violated E0117
/// (neither type is local to shape-vm). Callers explicitly invoke this
/// fallible function and pattern-match `None` to surface "complex
/// storage — kind not proven here" per CLAUDE.md type-system rules.
///
/// Returns `None` for complex `StorageType` variants
/// (Array/Table/Object/Result/TaggedUnion/Function/Struct/Dynamic):
/// the bulldozer deleted the `Unknown` sink, so callers must commit
/// to a concrete kind. A `None` return is a "you must prove a typed
/// kind here" signal — compiler-tier intermediate state per ADR-006
/// §2.7.5.1.
pub fn native_kind_from_storage_type(st: &StorageType) -> Option<NativeKind> {
    match st {
        StorageType::Float64 => Some(NativeKind::Float64),
        StorageType::Int64 => Some(NativeKind::Int64),
        StorageType::Bool => Some(NativeKind::Bool),
        StorageType::String => Some(NativeKind::String),

        StorageType::NullableFloat64 => Some(NativeKind::NullableFloat64),
        StorageType::NullableInt64 => Some(NativeKind::NullableInt64),
        StorageType::NullableBool => Some(NativeKind::Bool), // 3-state in Boxed

        StorageType::Array(_)
        | StorageType::Table { .. }
        | StorageType::Object
        | StorageType::Result { .. }
        | StorageType::TaggedUnion { .. }
        | StorageType::Function
        | StorageType::Struct(_)
        | StorageType::Dynamic => None,
    }
}

/// Typed frame layout metadata.
///
/// A `FrameDescriptor` describes the storage layout for every local slot
/// (parameters + locals) in a single function or top-level frame.  The JIT
/// and VM use this to allocate registers / stack space with correct widths
/// and to skip NaN-boxing for slots whose type is statically known.
///
/// This is the canonical replacement for the loose `Vec<StorageHint>` arrays
/// that were previously threaded through `BytecodeProgram` and `Function`.
///
/// # Wire-format binding (ADR-006 §2.7.5.1)
///
/// `FrameDescriptor` is `#[derive(Serialize, Deserialize)]` and lives
/// inside `FunctionBlob`, the content-hash unit for distributed
/// bytecode. Per §2.7.5.1, `slots: Vec<NativeKind>` is post-proof — no
/// `Vec<Option<NativeKind>>` wrap, no `NativeKind::Unknown` placeholder
/// (both deleted by the bulldozer). By the time a `FrameDescriptor`
/// reaches `FunctionBlob` construction, every slot's `NativeKind` is
/// proven; an unproven slot is a compile error per CLAUDE.md type-system
/// rules.
///
/// `return_kind: Option<NativeKind>` is the single-slot field carrying
/// the function's return-value kind, or `None` for "no return value /
/// kind not yet stamped". The single-slot `Option<NativeKind>` shape is
/// the §2.7.8 / Q10 cell-storage pattern (single-slot fields take
/// `Option<NativeKind>`); §2.7.5.1's "no `Option<NativeKind>` wrapping"
/// rule targets the bulk `slots` Vec, not single-slot fields where
/// `None` distinguishes "no return value" from "return value of kind X".
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrameDescriptor {
    /// One entry per local slot (index 0 = first param or local).
    /// Every slot's kind is proven at `FunctionBlob` construction time
    /// per ADR-006 §2.7.5.1 — `NativeKind::Unknown` was deleted from the
    /// enum and is never re-introduced under any name.
    pub slots: Vec<NativeKind>,

    /// Return type kind for the function, or `None` for "no return
    /// value / kind not stamped". `Some(kind)` means the JIT boundary
    /// ABI uses `kind` to unmarshal the return value from JIT-compiled
    /// code; `None` means the host boundary has no return-kind to
    /// unmarshal (e.g. top-level program with no terminal expression).
    #[serde(default)]
    pub return_kind: Option<NativeKind>,
}

impl FrameDescriptor {
    /// Create an empty descriptor with no slots and an unset return
    /// kind. Callers stamp `return_kind` to `Some(kind)` once the
    /// function's return type is proven.
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            return_kind: None,
        }
    }

    /// Build a descriptor from an existing `Vec<NativeKind>` of proven
    /// slot kinds. `return_kind` is left `None` for the caller to stamp.
    pub fn from_slots(slots: Vec<NativeKind>) -> Self {
        Self {
            slots,
            return_kind: None,
        }
    }

    /// Number of slots described.
    #[inline]
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    /// Whether the descriptor is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.slots.is_empty()
    }

    /// Get the kind of a specific slot, or `None` for out-of-range
    /// indices. Note: a present slot always has a proven `NativeKind`
    /// (no `Unknown` sentinel post-bulldozer).
    #[inline]
    pub fn slot(&self, index: usize) -> Option<NativeKind> {
        self.slots.get(index).copied()
    }
}

impl Default for FrameDescriptor {
    fn default() -> Self {
        Self::new()
    }
}

/// The kind of variable: regular value, typed table, row view, or column.
///
/// Replaces the old `is_datatable` / `is_row_view` / `is_column` boolean flags,
/// which were mutually exclusive but had no compiler enforcement.
#[derive(Debug, Clone, PartialEq)]
pub enum VariableKind {
    /// Regular value (struct, primitive, object, etc.)
    Value,
    /// A DataTable with known row schema — Table<T>.
    /// Closure methods (filter/map/etc.) propagate schema to row params.
    Table { element_type: String },
    /// A typed row from an Arrow DataTable — Row<T>.
    /// Field access emits LoadColF64/I64/Bool/Str instead of GetProp.
    RowView { element_type: String },
    /// A typed column from an Arrow DataTable — Column<T>.
    Column {
        element_type: String,
        column_type: String,
    },
    /// An indexed table — Indexed<T> with a designated index column.
    /// Only Indexed tables can use resample/between operations.
    Indexed {
        element_type: String,
        index_column: String,
    },
}

/// Source-level ownership class for a binding slot.
///
/// This tracks how the binding was declared, independent of the value's type.
/// Later storage planning uses this to decide whether a slot can stay direct,
/// must allow aliasing, or should preserve reference representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BindingOwnershipClass {
    /// `let` — immutable owned binding.
    OwnedImmutable,
    /// `let mut` — mutable owned binding.
    OwnedMutable,
    /// `var` — flexible/aliasable binding whose storage is chosen later.
    Flexible,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Aliasability {
    /// Single owner, no aliasing possible.
    Unique,
    /// Shared via immutable references only.
    SharedImmutable,
    /// Shared with potential mutation (var semantics).
    SharedMutable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MutationCapability {
    /// Cannot be mutated (`let`).
    Immutable,
    /// Mutable by single owner (`let mut`).
    LocalMutable,
    /// Mutable with shared access (`var` captured/aliased).
    SharedMutable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EscapeStatus {
    /// Stays within declaring scope.
    Local,
    /// Captured by a closure.
    Captured,
    /// Escapes declaring function (returned, stored in module state).
    Escaped,
}

/// Planned runtime storage strategy for a binding slot.
///
/// `Deferred` is the initial state for ordinary bindings until a later planner
/// decides whether the slot can stay direct or must be upgraded.
///
/// `LocalMutablePtr` (Closure Spec Phase D) marks a slot that lives on the
/// stack AND has had a typed `*mut T` handed to a non-escaping closure env.
/// The borrow checker has verified that no outer code races the closure over
/// that slot's lifetime (the `ClosureCapture` was lowered as an exclusive
/// borrow with `LoanSinkKind::ClosureEnvMut`). The binding is still direct in
/// the sense that the slot stays on the caller stack — no `Arc<RwLock<>>`,
/// no boxing. This is orthogonal to `Direct`/`UniqueHeap`: `Direct` means
/// "no indirection and no closure-env sharing", `LocalMutablePtr` means "no
/// indirection but a closure env holds a typed pointer into this slot".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BindingStorageClass {
    Deferred,
    Direct,
    UniqueHeap,
    SharedCow,
    Reference,
    /// Phase D: stack-resident slot with a typed `*mut T` capture handed to a
    /// non-escaping closure. See the doc comment on `BindingStorageClass`.
    LocalMutablePtr,
}

/// Ownership/storage metadata for a binding slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BindingSemantics {
    pub ownership_class: BindingOwnershipClass,
    pub storage_class: BindingStorageClass,
    pub aliasability: Aliasability,
    pub mutation_capability: MutationCapability,
    pub escape_status: EscapeStatus,
    /// Phase 5.B: If this binding was initialized from a call to a function
    /// with a known return-ownership mode, record that mode here. Phase 5.C
    /// consumes the hint to skip the Arc→Box `PromoteToOwned` at the callsite
    /// when the callee has already returned a uniquely-owned value.
    pub return_ownership_hint: Option<crate::mir::ReturnOwnershipMode>,
}

impl BindingSemantics {
    pub const fn deferred(ownership_class: BindingOwnershipClass) -> Self {
        Self {
            ownership_class,
            storage_class: BindingStorageClass::Deferred,
            aliasability: Aliasability::Unique,
            mutation_capability: match ownership_class {
                BindingOwnershipClass::OwnedImmutable => MutationCapability::Immutable,
                BindingOwnershipClass::OwnedMutable => MutationCapability::LocalMutable,
                BindingOwnershipClass::Flexible => MutationCapability::SharedMutable,
            },
            escape_status: EscapeStatus::Local,
            return_ownership_hint: None,
        }
    }
}

/// Type information for a variable
#[derive(Debug, Clone)]
pub struct VariableTypeInfo {
    /// Schema ID if type is known and registered
    pub schema_id: Option<SchemaId>,
    /// Type name (e.g., "Candle", "Point")
    pub type_name: Option<String>,
    /// Whether the type is definitely known (vs inferred/uncertain)
    pub is_definite: bool,
    /// Storage hint for JIT optimization, or `None` when the kind is
    /// not yet proven during compile-time inference.
    ///
    /// Per ADR-006 §2.7.5.1, this is compiler-tier intermediate state —
    /// `VariableTypeInfo` is NOT serialized into `FunctionBlob`, so the
    /// `Option<NativeKind>` wrap stays local to the analysis pass and
    /// does not reach the wire format. By the time a `FrameDescriptor`
    /// is constructed for `FunctionBlob`, the kind is proven and stored
    /// flat in `FrameDescriptor.slots: Vec<NativeKind>` (no Option).
    pub storage_hint: Option<StorageHint>,
    /// Preserved concrete numeric runtime type (e.g. "i16", "u8", "f32", "i64")
    /// derived from source annotations.
    pub concrete_numeric_type: Option<String>,
    /// What kind of variable this is (value, table, row view, column)
    pub kind: VariableKind,
    /// v2: For typed arrays, the element's FieldKind (enables typed array codegen)
    pub v2_array_element_kind: Option<FieldKind>,
    /// v2: For typed structs, the SchemaId referencing a StructLayout in TypeTracker
    pub v2_struct_layout: Option<SchemaId>,
}

impl VariableTypeInfo {
    /// Create type info for a known type
    pub fn known(schema_id: SchemaId, type_name: String) -> Self {
        let concrete_numeric_type = Self::infer_numeric_runtime_name(&type_name);
        Self {
            schema_id: Some(schema_id),
            type_name: Some(type_name),
            is_definite: true,
            storage_hint: None,
            concrete_numeric_type,
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for an unknown/dynamic type
    pub fn unknown() -> Self {
        Self {
            schema_id: None,
            type_name: None,
            is_definite: false,
            storage_hint: None,
            concrete_numeric_type: None,
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for a type name that may or may not be registered
    pub fn named(type_name: String) -> Self {
        // Infer storage hint from common type names
        let storage_hint = Self::infer_storage_hint(&type_name);
        let concrete_numeric_type = Self::infer_numeric_runtime_name(&type_name);
        Self {
            schema_id: None,
            type_name: Some(type_name),
            is_definite: false,
            storage_hint,
            concrete_numeric_type,
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info with explicit storage hint
    pub fn with_storage(type_name: String, storage_hint: StorageHint) -> Self {
        let concrete_numeric_type = Self::infer_numeric_runtime_name(&type_name);
        Self {
            schema_id: None,
            type_name: Some(type_name),
            is_definite: true,
            storage_hint: Some(storage_hint),
            concrete_numeric_type,
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for Option<f64> (NaN sentinel optimization)
    pub fn nullable_number() -> Self {
        Self {
            schema_id: None,
            type_name: Some("Option<Number>".to_string()),
            is_definite: true,
            storage_hint: Some(StorageHint::NullableFloat64),
            concrete_numeric_type: Some("f64".to_string()),
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for plain f64
    pub fn number() -> Self {
        Self {
            schema_id: None,
            type_name: Some("Number".to_string()),
            is_definite: true,
            storage_hint: Some(StorageHint::Float64),
            concrete_numeric_type: Some("f64".to_string()),
            kind: VariableKind::Value,
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for a RowView variable (typed row from Arrow DataTable).
    pub fn row_view(schema_id: SchemaId, type_name: String) -> Self {
        Self {
            schema_id: Some(schema_id),
            type_name: Some(type_name.clone()),
            is_definite: true,
            storage_hint: None,
            concrete_numeric_type: None,
            kind: VariableKind::RowView {
                element_type: type_name,
            },
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for a DataTable variable with known schema (Table<T>).
    pub fn datatable(schema_id: SchemaId, type_name: String) -> Self {
        Self {
            schema_id: Some(schema_id),
            type_name: Some(type_name.clone()),
            is_definite: true,
            storage_hint: None,
            concrete_numeric_type: None,
            kind: VariableKind::Table {
                element_type: type_name,
            },
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for a Column<T> variable (ColumnRef from Arrow DataTable).
    pub fn column(schema_id: SchemaId, type_name: String, element_type: String) -> Self {
        Self {
            schema_id: Some(schema_id),
            type_name: Some(type_name.clone()),
            is_definite: true,
            storage_hint: None,
            concrete_numeric_type: None,
            kind: VariableKind::Column {
                element_type,
                column_type: type_name,
            },
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Create type info for an Indexed table variable — Indexed<T> with known index column.
    pub fn indexed(schema_id: SchemaId, type_name: String, index_column: String) -> Self {
        Self {
            schema_id: Some(schema_id),
            type_name: Some(type_name.clone()),
            is_definite: true,
            storage_hint: None,
            concrete_numeric_type: None,
            kind: VariableKind::Indexed {
                element_type: type_name,
                index_column,
            },
            v2_array_element_kind: None,
            v2_struct_layout: None,
        }
    }

    /// Check if this type is known (has schema ID)
    pub fn is_known(&self) -> bool {
        self.schema_id.is_some()
    }

    /// Check if this type uses NaN sentinel for nullability
    pub fn uses_nan_sentinel(&self) -> bool {
        self.storage_hint == Some(StorageHint::NullableFloat64)
    }

    /// Check if this variable is a DataTable (Table<T>)
    pub fn is_datatable(&self) -> bool {
        matches!(self.kind, VariableKind::Table { .. })
    }

    /// Check if this variable is a RowView (Row<T>)
    pub fn is_row_view(&self) -> bool {
        matches!(self.kind, VariableKind::RowView { .. })
    }

    /// Check if this variable is a Column (Column<T>)
    pub fn is_column(&self) -> bool {
        matches!(self.kind, VariableKind::Column { .. })
    }

    /// Check if this variable is an Indexed table (Indexed<T>)
    pub fn is_indexed(&self) -> bool {
        matches!(self.kind, VariableKind::Indexed { .. })
    }

    /// Infer storage hint from type name. Returns `None` when the
    /// type name cannot be mapped to a concrete `NativeKind` —
    /// per ADR-006 §2.7.5.1 / CLAUDE.md, this is the analysis-tier
    /// "kind not yet proven" intermediate state, never an `Unknown`
    /// sentinel.
    fn infer_storage_hint(type_name: &str) -> Option<StorageHint> {
        let trimmed = type_name.trim();

        if let Some(inner) = Self::option_inner_type(trimmed) {
            let inner = inner.trim();
            if let Some(runtime) = BuiltinTypes::canonical_numeric_runtime_name(inner)
                && let Some(hint) = Self::storage_hint_for_runtime_numeric(runtime, true)
            {
                return Some(hint);
            }
            if BuiltinTypes::is_bool_type_name(inner) {
                return Some(StorageHint::Bool);
            }
            if BuiltinTypes::is_string_type_name(inner) {
                return Some(StorageHint::String);
            }
            return None;
        }

        if let Some(runtime) = BuiltinTypes::canonical_numeric_runtime_name(trimmed)
            && let Some(hint) = Self::storage_hint_for_runtime_numeric(runtime, false)
        {
            return Some(hint);
        }
        if BuiltinTypes::is_bool_type_name(trimmed) {
            return Some(StorageHint::Bool);
        }
        if BuiltinTypes::is_string_type_name(trimmed) {
            return Some(StorageHint::String);
        }
        None
    }

    fn option_inner_type(type_name: &str) -> Option<&str> {
        type_name
            .strip_prefix("Option<")
            .and_then(|inner| inner.strip_suffix('>'))
    }

    fn storage_hint_for_runtime_numeric(runtime_name: &str, nullable: bool) -> Option<StorageHint> {
        let base = match runtime_name {
            "f32" | "f64" => StorageHint::Float64,
            "i8" => StorageHint::Int8,
            "u8" => StorageHint::UInt8,
            "i16" => StorageHint::Int16,
            "u16" => StorageHint::UInt16,
            "i32" => StorageHint::Int32,
            "u32" => StorageHint::UInt32,
            "i64" => StorageHint::Int64,
            "u64" => StorageHint::UInt64,
            "isize" => StorageHint::IntSize,
            "usize" => StorageHint::UIntSize,
            _ => return None,
        };
        Some(base.with_nullability(nullable))
    }

    fn infer_numeric_runtime_name(type_name: &str) -> Option<String> {
        let inner = if type_name.starts_with("Option<") && type_name.ends_with('>') {
            &type_name["Option<".len()..type_name.len() - 1]
        } else {
            type_name
        };
        BuiltinTypes::canonical_numeric_runtime_name(inner).map(ToString::to_string)
    }
}

/// Sweep phase 3c.1: snapshot of the type-tracker's local-types state
/// captured before a nested function compilation that clears them.
/// Wraps both the flat `local_types` map and the per-scope
/// `local_type_scopes` stack so `pop_scope` semantics survive the
/// round-trip.
#[derive(Debug, Clone)]
pub struct LocalTypesSnapshot {
    pub local_types: HashMap<u16, VariableTypeInfo>,
    pub local_type_scopes: Vec<HashMap<u16, VariableTypeInfo>>,
}

impl LocalTypesSnapshot {
    pub fn len(&self) -> usize {
        self.local_types.len()
    }

    pub fn is_empty(&self) -> bool {
        self.local_types.is_empty()
    }
}

/// Tracks type information for variables during compilation
#[derive(Debug)]
pub struct TypeTracker {
    /// Type schema registry for looking up type definitions
    schema_registry: TypeSchemaRegistry,

    /// Type info for local variables (by slot index)
    local_types: HashMap<u16, VariableTypeInfo>,

    /// Type info for module_binding variables (by slot index)
    binding_types: HashMap<u16, VariableTypeInfo>,

    /// Binding ownership/storage metadata for locals.
    local_binding_semantics: HashMap<u16, BindingSemantics>,

    /// Binding ownership/storage metadata for module bindings.
    binding_semantics: HashMap<u16, BindingSemantics>,

    /// Scoped local type mappings (for scope push/pop)
    local_type_scopes: Vec<HashMap<u16, VariableTypeInfo>>,

    /// Scoped local binding metadata mappings (for scope push/pop).
    local_binding_semantic_scopes: Vec<HashMap<u16, BindingSemantics>>,

    /// Function return types (function name -> type name)
    function_return_types: HashMap<String, String>,
    /// Compile-time object schema contracts: schema id -> field type annotation.
    ///
    /// Used for callable typed-object fields where runtime schema stores only slot layout.
    object_field_contracts: HashMap<SchemaId, HashMap<String, TypeAnnotation>>,

    /// v2: Computed C-compatible struct layouts indexed by SchemaId.
    /// Enables the compiler to look up field offsets at compile time for typed codegen.
    pub v2_layouts: HashMap<SchemaId, StructLayout>,

    /// Per-compiler counter for generating unique names for inline object
    /// schemas (`__inline_obj_{N}`). Moved off the process-global
    /// `INLINE_OBJECT_COUNTER` static in B1.8; scoping it to a single
    /// compile makes the generated names deterministic per compile.
    inline_object_counter: u64,
}

impl TypeTracker {
    /// Create a new type tracker with the given schema registry
    pub fn new(schema_registry: TypeSchemaRegistry) -> Self {
        Self {
            schema_registry,
            local_types: HashMap::new(),
            binding_types: HashMap::new(),
            local_binding_semantics: HashMap::new(),
            binding_semantics: HashMap::new(),
            local_type_scopes: vec![HashMap::new()],
            local_binding_semantic_scopes: vec![HashMap::new()],
            function_return_types: HashMap::new(),
            object_field_contracts: HashMap::new(),
            v2_layouts: HashMap::new(),
            inline_object_counter: 0,
        }
    }

    /// Create a new type tracker with an empty registry
    pub fn empty() -> Self {
        Self::new(TypeSchemaRegistry::new())
    }

    /// Create a new type tracker with stdlib types pre-registered
    pub fn with_stdlib() -> Self {
        Self::new(TypeSchemaRegistry::with_stdlib_types())
    }

    /// Get the schema registry
    pub fn schema_registry(&self) -> &TypeSchemaRegistry {
        &self.schema_registry
    }

    /// Get mutable schema registry
    pub fn schema_registry_mut(&mut self) -> &mut TypeSchemaRegistry {
        &mut self.schema_registry
    }

    /// Push a new scope for local types
    pub fn push_scope(&mut self) {
        self.local_type_scopes.push(HashMap::new());
        self.local_binding_semantic_scopes.push(HashMap::new());
    }

    /// Pop a scope, removing local type info for that scope
    pub fn pop_scope(&mut self) {
        if let Some(scope) = self.local_type_scopes.pop() {
            // Remove type info for variables in this scope
            for slot in scope.keys() {
                self.local_types.remove(slot);
            }
        }
        if let Some(scope) = self.local_binding_semantic_scopes.pop() {
            for slot in scope.keys() {
                self.local_binding_semantics.remove(slot);
            }
        }
    }

    /// Set type info for a local variable
    pub fn set_local_type(&mut self, slot: u16, type_info: VariableTypeInfo) {
        // Try to resolve schema ID if we have a type name but no schema ID
        let resolved_info = if type_info.type_name.is_some() && type_info.schema_id.is_none() {
            self.resolve_type_info(type_info)
        } else {
            type_info
        };

        // Track in current scope
        if let Some(scope) = self.local_type_scopes.last_mut() {
            scope.insert(slot, resolved_info.clone());
        }
        self.local_types.insert(slot, resolved_info);
    }

    /// Set type info for a module_binding variable
    pub fn set_binding_type(&mut self, slot: u16, type_info: VariableTypeInfo) {
        let resolved_info = if type_info.type_name.is_some() && type_info.schema_id.is_none() {
            self.resolve_type_info(type_info)
        } else {
            type_info
        };
        self.binding_types.insert(slot, resolved_info);
    }

    /// Set ownership/storage metadata for a local binding.
    pub fn set_local_binding_semantics(&mut self, slot: u16, semantics: BindingSemantics) {
        if let Some(scope) = self.local_binding_semantic_scopes.last_mut() {
            scope.insert(slot, semantics);
        }
        self.local_binding_semantics.insert(slot, semantics);
    }

    /// Set ownership/storage metadata for a module binding.
    pub fn set_binding_semantics(&mut self, slot: u16, semantics: BindingSemantics) {
        self.binding_semantics.insert(slot, semantics);
    }

    /// Update only the storage strategy for a local binding.
    pub fn set_local_binding_storage_class(
        &mut self,
        slot: u16,
        storage_class: BindingStorageClass,
    ) {
        if let Some(existing) = self.local_binding_semantics.get_mut(&slot) {
            existing.storage_class = storage_class;
        }
        for scope in self.local_binding_semantic_scopes.iter_mut().rev() {
            if let Some(existing) = scope.get_mut(&slot) {
                existing.storage_class = storage_class;
                break;
            }
        }
    }

    /// Update only the storage strategy for a module binding.
    pub fn set_binding_storage_class(&mut self, slot: u16, storage_class: BindingStorageClass) {
        if let Some(existing) = self.binding_semantics.get_mut(&slot) {
            existing.storage_class = storage_class;
        }
    }

    /// Get type info for a local variable
    pub fn get_local_type(&self, slot: u16) -> Option<&VariableTypeInfo> {
        self.local_types.get(&slot)
    }

    /// Get type info for a module_binding variable
    pub fn get_binding_type(&self, slot: u16) -> Option<&VariableTypeInfo> {
        self.binding_types.get(&slot)
    }

    /// Get ownership/storage metadata for a local binding.
    pub fn get_local_binding_semantics(&self, slot: u16) -> Option<&BindingSemantics> {
        self.local_binding_semantics.get(&slot)
    }

    /// Get ownership/storage metadata for a module binding.
    pub fn get_binding_semantics(&self, slot: u16) -> Option<&BindingSemantics> {
        self.binding_semantics.get(&slot)
    }

    /// Register a function's return type
    pub fn register_function_return_type(&mut self, func_name: &str, return_type: &str) {
        self.function_return_types
            .insert(func_name.to_string(), return_type.to_string());
    }

    /// Get a function's return type
    pub fn get_function_return_type(&self, func_name: &str) -> Option<&String> {
        self.function_return_types.get(func_name)
    }

    /// Register compile-time field type contracts for an object schema id.
    pub fn register_object_field_contracts(
        &mut self,
        schema_id: SchemaId,
        fields: HashMap<String, TypeAnnotation>,
    ) {
        self.object_field_contracts.insert(schema_id, fields);
    }

    /// Lookup a compile-time field type contract for a schema field.
    pub fn get_object_field_contract(
        &self,
        schema_id: SchemaId,
        field_name: &str,
    ) -> Option<&TypeAnnotation> {
        self.object_field_contracts
            .get(&schema_id)
            .and_then(|fields| fields.get(field_name))
    }

    /// Resolve type name to schema ID
    fn resolve_type_info(&self, mut type_info: VariableTypeInfo) -> VariableTypeInfo {
        if let Some(ref type_name) = type_info.type_name {
            if let Some(schema) = self.schema_registry.get(type_name) {
                type_info.schema_id = Some(schema.id);
                type_info.is_definite = true;
            }
        }
        type_info
    }

    /// Get field offset for typed field access
    ///
    /// Returns (schema_id, field_offset, field_index) if type and field are known
    pub fn get_typed_field_info(
        &self,
        type_name: &str,
        field_name: &str,
    ) -> Option<(SchemaId, usize, u16)> {
        let schema = self.schema_registry.get(type_name)?;
        let field = schema.get_field(field_name)?;
        Some((schema.id, field.offset, field.index))
    }

    /// Get column index for a RowView field access.
    ///
    /// Returns the field index (used as col_id for ColumnAccess operand)
    /// if the variable is a RowView and the field exists in its schema.
    pub fn get_row_view_column_id(
        &self,
        slot: u16,
        is_local: bool,
        field_name: &str,
    ) -> Option<u32> {
        let type_info = if is_local {
            self.get_local_type(slot)?
        } else {
            self.get_binding_type(slot)?
        };
        if !type_info.is_row_view() {
            return None;
        }
        let type_name = type_info.type_name.as_ref()?;
        let schema = self.schema_registry.get(type_name)?;
        let field = schema.get_field(field_name)?;
        Some(field.index as u32)
    }

    /// Check if we can use typed field access for a variable and field
    pub fn can_use_typed_access(&self, slot: u16, is_local: bool, field_name: &str) -> bool {
        let type_info = if is_local {
            self.get_local_type(slot)
        } else {
            self.get_binding_type(slot)
        };

        if let Some(info) = type_info {
            if let Some(ref type_name) = info.type_name {
                return self
                    .schema_registry
                    .field_offset(type_name, field_name)
                    .is_some();
            }
        }
        false
    }

    /// Get storage hint for a local variable. Returns `None` for
    /// unknown slots or when the slot's kind has not yet been proven —
    /// per ADR-006 §2.7.5.1, callers handle the "not proven" arm
    /// explicitly rather than dispatching on a placeholder sentinel.
    pub fn get_local_storage_hint(&self, slot: u16) -> Option<StorageHint> {
        self.get_local_type(slot).and_then(|info| info.storage_hint)
    }

    /// Get storage hint for a module_binding variable. Returns `None`
    /// for unknown slots or unproven kinds — see
    /// [`get_local_storage_hint`].
    pub fn get_module_binding_storage_hint(&self, slot: u16) -> Option<StorageHint> {
        self.get_binding_type(slot)
            .and_then(|info| info.storage_hint)
    }

    /// Check if a local variable uses NaN sentinel for nullability
    pub fn local_uses_nan_sentinel(&self, slot: u16) -> bool {
        self.get_local_storage_hint(slot) == Some(StorageHint::NullableFloat64)
    }

    /// Check if a module_binding variable uses NaN sentinel for nullability
    pub fn module_binding_uses_nan_sentinel(&self, slot: u16) -> bool {
        self.get_module_binding_storage_hint(slot) == Some(StorageHint::NullableFloat64)
    }

    /// Clear all local type info (for function entry)
    pub fn clear_locals(&mut self) {
        self.local_types.clear();
        self.local_binding_semantics.clear();
        self.local_type_scopes.clear();
        self.local_type_scopes.push(HashMap::new());
        self.local_binding_semantic_scopes.clear();
        self.local_binding_semantic_scopes.push(HashMap::new());
    }

    /// Track A.1C.2: snapshot the outer function's local binding
    /// semantics before entering a nested function compilation. Pairs
    /// with [`restore_local_binding_semantics`] to preserve ownership
    /// / storage classification across `compile_function`'s
    /// `clear_locals` call so subsequent closures in the outer scope
    /// still observe the binding's classification (e.g. `var` →
    /// `Flexible`, `let mut` → `OwnedMutable`).
    pub fn snapshot_local_binding_semantics(&self) -> HashMap<u16, BindingSemantics> {
        self.local_binding_semantics.clone()
    }

    /// Track A.1C.2: restore a previously-snapshotted local binding
    /// semantics map. Used by `compile_function` after a nested closure
    /// body compilation wipes the outer function's semantics.
    pub fn restore_local_binding_semantics(&mut self, snapshot: HashMap<u16, BindingSemantics>) {
        self.local_binding_semantics = snapshot;
    }

    /// Sweep phase 3c.1: snapshot the outer function's local type
    /// information before entering a nested function compilation.
    /// Pairs with [`restore_local_types`] to preserve typed-tracker
    /// state (e.g. `let base = 100` → `int`) across
    /// `compile_function`'s `clear_locals` call so post-closure
    /// strict-typing-sweep code paths can still resolve outer-scope
    /// identifier types — e.g. inferring `f`'s return type for
    /// `let f = |x: int| x + base`.
    ///
    /// The snapshot covers both the flattened `local_types` map AND
    /// the per-scope `local_type_scopes` stack — `pop_scope` (called
    /// during closure compile teardown) reads from the scope stack to
    /// know which `local_types` entries to evict, so a restore that
    /// only re-installs `local_types` would have its outer-scope
    /// entries silently re-evicted by the next `pop_scope` whose
    /// scope stack still contains the inner-closure slot indices.
    pub fn snapshot_local_types(&self) -> LocalTypesSnapshot {
        LocalTypesSnapshot {
            local_types: self.local_types.clone(),
            local_type_scopes: self.local_type_scopes.clone(),
        }
    }

    /// Sweep phase 3c.1: restore a previously-snapshotted local types
    /// map and scope stack. Used by `compile_function` after a nested
    /// closure body compilation wipes the outer function's type
    /// information.
    pub fn restore_local_types(&mut self, snapshot: LocalTypesSnapshot) {
        self.local_types = snapshot.local_types;
        self.local_type_scopes = snapshot.local_type_scopes;
    }

    /// Register an inline object schema from field names.
    ///
    /// Creates a TypeSchema for an object literal with the given fields.
    /// All fields are typed `FieldType::Any` at the schema layer since
    /// the caller does not provide per-field type info — the
    /// post_inference_verify pass at
    /// `crates/shape-vm/src/compiler/post_inference_verify.rs` absorbs
    /// the resulting `__inline_obj_N` schemas via the W17.2-C narrowed
    /// transitional whitelist row pre-W17.3 (per audit §4.D.5 + §9.B.3
    /// supervisor ratify 2026-05-19).
    ///
    /// **Deprecation (W17.2-C):** prefer
    /// [`Self::register_inline_object_schema_typed`] when per-field
    /// types are known at the call site. The untyped variant routes
    /// internally through `register_inline_object_schema_typed` with
    /// each field stamped `FieldType::Any` — same `__inline_obj_N` name
    /// format + same verification-pass absorber. Per audit §4.D.5
    /// PROPAGATE disposition: callers SHOULD migrate to the typed
    /// variant; the verification-pass safety net catches any residual
    /// Any leakage at user-facing schemas. ADR-006 §2.7.5 producer-side
    /// stamp.
    ///
    /// Returns the SchemaId for use with NewTypedObject opcode.
    ///
    /// # Example
    /// ```ignore
    /// // For: let x = { a: 1, b: "hello" }
    /// let schema_id = tracker.register_inline_object_schema(&["a", "b"]);
    /// // Now emit NewTypedObject with schema_id
    /// ```
    #[deprecated(
        since = "0.3.0",
        note = "Prefer `register_inline_object_schema_typed` per audit \
                §4.D.5 W17.2-C (PROPAGATE per-field types at call site). \
                The untyped variant routes through the typed variant \
                with FieldType::Any per field; the post_inference_verify \
                pass absorbs via the __inline_obj_* transitional row."
    )]
    pub fn register_inline_object_schema(&mut self, field_names: &[&str]) -> SchemaId {
        // Route through the typed variant with FieldType::Any per field
        // — keeps schema-name format (`__inline_obj_N`) + deduplication
        // identical, while the deprecation nudges callers toward the
        // typed variant. Per audit §4.D.5 W17.2-C PROPAGATE.
        let typed_fields: Vec<(&str, FieldType)> = field_names
            .iter()
            .map(|name| (*name, FieldType::Any))
            .collect();
        self.register_inline_object_schema_typed(&typed_fields)
    }

    /// Register an inline object schema with typed fields
    ///
    /// Like `register_inline_object_schema` but allows specifying field types
    /// for better JIT optimization. Deduplicates by matching both field names
    /// and types.
    pub fn register_inline_object_schema_typed(
        &mut self,
        fields: &[(&str, FieldType)],
    ) -> SchemaId {
        if let Some(existing) = self.schema_registry.type_names().find_map(|name| {
            self.schema_registry.get(name).and_then(|schema| {
                if schema.fields.len() != fields.len() {
                    return None;
                }
                let same = schema
                    .fields
                    .iter()
                    .zip(fields.iter())
                    .all(|(f, (n, t))| f.name == *n && f.field_type == *t);
                if same { Some(schema.id) } else { None }
            })
        }) {
            return existing;
        }

        let id = self.inline_object_counter;
        self.inline_object_counter += 1;
        let type_name = format!("__inline_obj_{}", id);
        let field_defs: Vec<(String, FieldType)> = fields
            .iter()
            .map(|(name, ft)| (name.to_string(), ft.clone()))
            .collect();
        let schema = TypeSchema::new(&type_name, field_defs);
        let schema_id = schema.id;
        self.schema_registry.register(schema);
        schema_id
    }

    /// Register a named struct schema (e.g. `Point { x, y }`)
    ///
    /// Unlike `register_inline_object_schema` which auto-generates names,
    /// this uses the actual struct type name so `.type()` can resolve it.
    pub fn register_named_object_schema(
        &mut self,
        type_name: &str,
        fields: &[(&str, FieldType)],
    ) -> SchemaId {
        let field_defs: Vec<(String, FieldType)> = fields
            .iter()
            .map(|(name, ft)| (name.to_string(), ft.clone()))
            .collect();

        let schema = TypeSchema::new(type_name, field_defs);
        let schema_id = schema.id;
        self.schema_registry.register(schema);

        schema_id
    }

    /// Register an inline object schema with typed fields
    ///
    /// Like `register_inline_object_schema` but allows specifying field types
    /// for better JIT optimization.
    pub fn register_typed_object_schema(
        &mut self,
        field_defs: Vec<(String, FieldType)>,
    ) -> SchemaId {
        let id = self.inline_object_counter;
        self.inline_object_counter += 1;
        let type_name = format!("__inline_obj_{}", id);

        let schema = TypeSchema::new(&type_name, field_defs);
        let schema_id = schema.id;
        self.schema_registry.register(schema);

        schema_id
    }

    // --- v2 helpers ---

    /// Register a v2 StructLayout for the given schema ID.
    pub fn register_v2_layout(&mut self, schema_id: SchemaId, layout: StructLayout) {
        self.v2_layouts.insert(schema_id, layout);
    }

    /// Look up a v2 StructLayout by schema ID.
    pub fn get_v2_layout(&self, schema_id: SchemaId) -> Option<&StructLayout> {
        self.v2_layouts.get(&schema_id)
    }

    /// Check if a local slot is a typed array and return its element kind.
    pub fn is_typed_array(&self, slot: u16) -> Option<FieldKind> {
        self.local_types.get(&slot)?.v2_array_element_kind
    }

    /// Check if a local slot has a v2 struct layout and return its schema ID.
    pub fn is_typed_struct(&self, slot: u16) -> Option<SchemaId> {
        self.local_types.get(&slot)?.v2_struct_layout
    }
}

impl Default for TypeTracker {
    fn default() -> Self {
        Self::empty()
    }
}

// ─────────────────────────────────────────────────────────────────────
// Strict-typing predicate: `prove_native_kind` and `ProofGap`
//
// Every site emitting a typed opcode (AddI64, MulF64, ReturnValueBool,
// LoadLocalI64, etc.) must call `prove_native_kind` and propagate any
// `ProofGap` it returns. `ProofGap` has no public constructor — only
// this module can produce one — so emit code cannot fabricate a
// successful proof. The Rust type system enforces the discipline.
//
// Phase 2 wires call sites to use this predicate. Phase 3 makes the
// predicate panic in debug + test on missing proof. Phase 5 makes it a
// hard compile error E_TYPED_OPCODE_WITHOUT_PROOF in release.
// ─────────────────────────────────────────────────────────────────────

/// A type-system proof gap — the compiler tried to emit a typed opcode
/// but could not prove the operand kind. Surfaces as
/// `E_TYPED_OPCODE_WITHOUT_PROOF` in release; panics in debug + test.
///
/// Constructor is private. Only [`prove_native_kind`] can produce one.
#[derive(Debug)]
pub struct ProofGap {
    site: &'static str,
    detail: String,
    _seal: ProofGapSeal,
}

/// Module-private seal token. External code cannot construct a
/// `ProofGap` because they cannot construct a `ProofGapSeal`.
#[derive(Debug)]
struct ProofGapSeal(());

impl ProofGap {
    /// Site identifier (e.g. "emit_typed_arithmetic", "emit_return_value").
    pub fn site(&self) -> &'static str {
        self.site
    }

    /// Human-readable explanation of what couldn't be proved.
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl std::fmt::Display for ProofGap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "E_TYPED_OPCODE_WITHOUT_PROOF at {}: {}",
            self.site, self.detail
        )
    }
}

impl std::error::Error for ProofGap {}

/// Prove that the given slot's content is a specific [`NativeKind`] at
/// emission time, or surface a [`ProofGap`].
///
/// # Phase 2 contract (current)
///
/// Phase 2 wires call sites to call this predicate. Until Phase 3, the
/// predicate is a no-op that returns the supplied `claimed_kind` —
/// callers can run end-to-end. Phase 3 hardens to debug-panic; Phase 5
/// hardens to release compile-error.
///
/// # Future strict mode (Phases 3-5)
///
/// The body will inspect the compiler's slot-kind tracker for the
/// declared kind at the source location and compare against
/// `claimed_kind`. Mismatch or unknown → `ProofGap`.
#[inline]
pub fn prove_native_kind(
    site: &'static str,
    claimed_kind: NativeKind,
) -> Result<NativeKind, ProofGap> {
    // Phase 2 stub: pass-through. Phase 3+ replaces with real proof check.
    Ok(claimed_kind)
}

/// Construct a `ProofGap` from inside this module only. Used by the
/// predicate (Phase 3+) when proof fails.
#[allow(dead_code)]
fn proof_gap(site: &'static str, detail: impl Into<String>) -> ProofGap {
    ProofGap {
        site,
        detail: detail.into(),
        _seal: ProofGapSeal(()),
    }
}

/// Surface a [`ProofGap`] for an operand whose compile-time type could not be
/// resolved to a concrete kind.
///
/// This is the emit-side soundness floor (ε-1 PART 1): a typed opcode requires
/// the compiler to *prove* the operand's `NativeKind`. When the type-inference
/// engine leaves a value as an unresolved `Type::Variable` (or a still-bounded
/// `Type::Constrained` variable), the emitter has nothing to prove against —
/// it must NOT fall back to a default kind (the historical `Float64` default
/// is exactly the silent-wrong path this guards). The caller turns the
/// returned `ProofGap` into a clean compile error per CLAUDE.md §Type System
/// Rules ("if the type can't be proven, it is a compile error").
pub fn proof_gap_unresolved_operand(site: &'static str, detail: impl Into<String>) -> ProofGap {
    proof_gap(site, detail)
}

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

    #[test]
    fn test_basic_type_tracking() {
        let mut registry = TypeSchemaRegistry::new();

        TypeSchemaBuilder::new("Point")
            .f64_field("x")
            .f64_field("y")
            .register(&mut registry);

        let mut tracker = TypeTracker::new(registry);

        // Set type for local slot 0
        tracker.set_local_type(0, VariableTypeInfo::named("Point".to_string()));

        // Check that we can use typed access
        assert!(tracker.can_use_typed_access(0, true, "x"));
        assert!(tracker.can_use_typed_access(0, true, "y"));
        assert!(!tracker.can_use_typed_access(0, true, "z")); // Unknown field
    }

    #[test]
    fn test_scope_tracking() {
        let mut tracker = TypeTracker::empty();

        // Declare in outer scope
        tracker.set_local_type(0, VariableTypeInfo::named("Outer".to_string()));

        // Push inner scope
        tracker.push_scope();
        tracker.set_local_type(1, VariableTypeInfo::named("Inner".to_string()));

        assert!(tracker.get_local_type(0).is_some());
        assert!(tracker.get_local_type(1).is_some());

        // Pop inner scope
        tracker.pop_scope();

        // Outer still exists, inner removed
        assert!(tracker.get_local_type(0).is_some());
        assert!(tracker.get_local_type(1).is_none());
    }

    #[test]
    fn test_binding_semantics_scope_tracking() {
        let mut tracker = TypeTracker::empty();

        tracker.set_local_binding_semantics(
            0,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedImmutable),
        );
        tracker.set_binding_semantics(
            5,
            BindingSemantics::deferred(BindingOwnershipClass::Flexible),
        );

        tracker.push_scope();
        tracker.set_local_binding_semantics(
            1,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedMutable),
        );

        assert_eq!(
            tracker
                .get_local_binding_semantics(0)
                .map(|s| s.ownership_class),
            Some(BindingOwnershipClass::OwnedImmutable)
        );
        assert_eq!(
            tracker
                .get_local_binding_semantics(1)
                .map(|s| s.ownership_class),
            Some(BindingOwnershipClass::OwnedMutable)
        );
        assert_eq!(
            tracker.get_binding_semantics(5).map(|s| s.ownership_class),
            Some(BindingOwnershipClass::Flexible)
        );

        tracker.pop_scope();

        assert!(tracker.get_local_binding_semantics(1).is_none());
        assert!(tracker.get_local_binding_semantics(0).is_some());
        assert!(tracker.get_binding_semantics(5).is_some());
    }

    #[test]
    fn test_binding_storage_class_updates() {
        let mut tracker = TypeTracker::empty();
        tracker.set_local_binding_semantics(
            0,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedMutable),
        );
        tracker.set_binding_semantics(
            4,
            BindingSemantics::deferred(BindingOwnershipClass::Flexible),
        );

        tracker.set_local_binding_storage_class(0, BindingStorageClass::Reference);
        tracker.set_binding_storage_class(4, BindingStorageClass::SharedCow);

        assert_eq!(
            tracker
                .get_local_binding_semantics(0)
                .map(|s| s.storage_class),
            Some(BindingStorageClass::Reference)
        );
        assert_eq!(
            tracker.get_binding_semantics(4).map(|s| s.storage_class),
            Some(BindingStorageClass::SharedCow)
        );

        tracker.clear_locals();
        assert!(tracker.get_local_binding_semantics(0).is_none());
        assert!(tracker.get_binding_semantics(4).is_some());
    }

    #[test]
    fn test_function_return_types() {
        let mut tracker = TypeTracker::empty();

        tracker.register_function_return_type("get_point", "Point");

        assert_eq!(
            tracker.get_function_return_type("get_point"),
            Some(&"Point".to_string())
        );
        assert!(tracker.get_function_return_type("unknown").is_none());
    }

    #[test]
    fn test_typed_field_info() {
        let mut registry = TypeSchemaRegistry::new();

        TypeSchemaBuilder::new("Vector3")
            .f64_field("x")
            .f64_field("y")
            .f64_field("z")
            .register(&mut registry);

        let tracker = TypeTracker::new(registry);

        let info = tracker.get_typed_field_info("Vector3", "y");
        assert!(info.is_some());
        let (schema_id, offset, index) = info.unwrap();
        assert!(schema_id > 0);
        assert_eq!(offset, 8); // Second field, 8 bytes offset
        assert_eq!(index, 1);
    }

    #[test]
    fn test_unknown_type() {
        let tracker = TypeTracker::empty();

        // Unknown type should not allow typed access
        assert!(!tracker.can_use_typed_access(0, true, "field"));
    }

    #[test]
    fn test_binding_type_tracking() {
        let mut registry = TypeSchemaRegistry::new();

        TypeSchemaBuilder::new("Config")
            .f64_field("threshold")
            .string_field("name")
            .register(&mut registry);

        let mut tracker = TypeTracker::new(registry);

        // Set type for module_binding slot 5
        tracker.set_binding_type(5, VariableTypeInfo::named("Config".to_string()));

        assert!(tracker.can_use_typed_access(5, false, "threshold"));
        assert!(tracker.can_use_typed_access(5, false, "name"));
        assert!(!tracker.can_use_typed_access(5, false, "unknown"));
    }

    #[test]
    fn test_storage_hint_inference() {
        // Primitive types
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Number"),
            Some(StorageHint::Float64)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Integer"),
            Some(StorageHint::Int64)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Bool"),
            Some(StorageHint::Bool)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("String"),
            Some(StorageHint::String)
        );

        // Nullable types
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Option<Number>"),
            Some(StorageHint::NullableFloat64)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Option<Integer>"),
            Some(StorageHint::NullableInt64)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Option<byte>"),
            Some(StorageHint::NullableUInt8)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Option<char>"),
            Some(StorageHint::NullableInt8)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("Option<u32>"),
            Some(StorageHint::NullableUInt32)
        );

        // Unknown types — analysis-tier "not yet proven" is `None`
        // per ADR-006 §2.7.5.1 (no `NativeKind::Unknown` sentinel).
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("SomeCustomType"),
            None
        );
    }

    #[test]
    fn test_width_integer_storage_hint_inference() {
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("i8"),
            Some(StorageHint::Int8)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("byte"),
            Some(StorageHint::UInt8)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("char"),
            Some(StorageHint::Int8)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("u16"),
            Some(StorageHint::UInt16)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("i32"),
            Some(StorageHint::Int32)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("u64"),
            Some(StorageHint::UInt64)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("isize"),
            Some(StorageHint::IntSize)
        );
        assert_eq!(
            VariableTypeInfo::infer_storage_hint("usize"),
            Some(StorageHint::UIntSize)
        );
    }

    #[test]
    fn test_concrete_numeric_type_inference() {
        assert_eq!(
            VariableTypeInfo::infer_numeric_runtime_name("int"),
            Some("i64".to_string())
        );
        assert_eq!(
            VariableTypeInfo::infer_numeric_runtime_name("i16"),
            Some("i16".to_string())
        );
        assert_eq!(
            VariableTypeInfo::infer_numeric_runtime_name("byte"),
            Some("u8".to_string())
        );
        assert_eq!(
            VariableTypeInfo::infer_numeric_runtime_name("Option<f32>"),
            Some("f32".to_string())
        );
        assert_eq!(
            VariableTypeInfo::infer_numeric_runtime_name("SomeCustomType"),
            None
        );
    }

    #[test]
    fn test_native_kind_from_storage_type() {
        assert_eq!(
            native_kind_from_storage_type(&StorageType::Float64),
            Some(NativeKind::Float64)
        );
        assert_eq!(
            native_kind_from_storage_type(&StorageType::NullableFloat64),
            Some(NativeKind::NullableFloat64)
        );
        // Bulldozer deleted the Unknown sink — complex types now return None.
        assert_eq!(
            native_kind_from_storage_type(&StorageType::Dynamic),
            None
        );
    }

    #[test]
    fn test_nullable_number_type() {
        let info = VariableTypeInfo::nullable_number();
        assert!(info.uses_nan_sentinel());
        assert_eq!(info.storage_hint, Some(StorageHint::NullableFloat64));
    }

    #[test]
    fn test_row_view_column_id_resolution() {
        let mut registry = TypeSchemaRegistry::new();

        TypeSchemaBuilder::new("Candle")
            .f64_field("open")
            .f64_field("high")
            .f64_field("low")
            .f64_field("close")
            .i64_field("volume")
            .register(&mut registry);

        let mut tracker = TypeTracker::new(registry);

        // Get schema ID for Candle
        let schema = tracker.schema_registry().get("Candle").unwrap();
        let schema_id = schema.id;

        // Set local slot 0 as a RowView<Candle>
        tracker.set_local_type(
            0,
            VariableTypeInfo::row_view(schema_id, "Candle".to_string()),
        );

        // Should resolve known fields
        assert_eq!(tracker.get_row_view_column_id(0, true, "open"), Some(0));
        assert_eq!(tracker.get_row_view_column_id(0, true, "high"), Some(1));
        assert_eq!(tracker.get_row_view_column_id(0, true, "close"), Some(3));
        assert_eq!(tracker.get_row_view_column_id(0, true, "volume"), Some(4));

        // Should return None for unknown fields
        assert_eq!(tracker.get_row_view_column_id(0, true, "nonexistent"), None);

        // Non-row-view variable should return None
        tracker.set_local_type(1, VariableTypeInfo::named("Candle".to_string()));
        assert_eq!(tracker.get_row_view_column_id(1, true, "open"), None);
    }

    #[test]
    fn test_tracker_storage_hints() {
        let mut tracker = TypeTracker::empty();

        // Set local with nullable type
        tracker.set_local_type(0, VariableTypeInfo::nullable_number());
        assert!(tracker.local_uses_nan_sentinel(0));

        // Set local with regular number
        tracker.set_local_type(1, VariableTypeInfo::number());
        assert!(!tracker.local_uses_nan_sentinel(1));

        // Unknown slot
        assert!(!tracker.local_uses_nan_sentinel(99));
    }

    #[test]
    fn test_datatable_type_info() {
        let mut registry = TypeSchemaRegistry::new();

        TypeSchemaBuilder::new("Trade")
            .f64_field("price")
            .i64_field("volume")
            .string_field("symbol")
            .register(&mut registry);

        let mut tracker = TypeTracker::new(registry);

        let schema = tracker.schema_registry().get("Trade").unwrap();
        let schema_id = schema.id;

        // Create a datatable type info
        tracker.set_local_type(
            0,
            VariableTypeInfo::datatable(schema_id, "Trade".to_string()),
        );

        let info = tracker.get_local_type(0).unwrap();
        assert!(info.is_datatable());
        assert!(!info.is_row_view());
        assert_eq!(info.schema_id, Some(schema_id));
        assert_eq!(info.type_name.as_deref(), Some("Trade"));

        // RowView should not be a datatable
        tracker.set_local_type(
            1,
            VariableTypeInfo::row_view(schema_id, "Trade".to_string()),
        );
        let info = tracker.get_local_type(1).unwrap();
        assert!(!info.is_datatable());
        assert!(info.is_row_view());
    }

    #[test]
    fn test_v2_struct_layout_registration() {
        use shape_value::v2::struct_layout::{FieldKind, StructLayout};

        let mut tracker = TypeTracker::empty();

        let layout = StructLayout::new(&[("x", FieldKind::F64), ("y", FieldKind::F64)]);
        assert_eq!(layout.total_size(), 24);

        // Use a fake schema ID
        let schema_id: SchemaId = 42;
        tracker.register_v2_layout(schema_id, layout);

        let retrieved = tracker.get_v2_layout(schema_id);
        assert!(retrieved.is_some());
        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved.field_count(), 2);
        assert_eq!(retrieved.field_offset(0), 8);
        assert_eq!(retrieved.field_offset(1), 16);
        assert_eq!(retrieved.total_size(), 24);

        // Non-existent schema ID returns None
        assert!(tracker.get_v2_layout(999).is_none());
    }

    #[test]
    fn test_v2_typed_array_element_kind() {
        use shape_value::v2::struct_layout::FieldKind;

        let mut tracker = TypeTracker::empty();

        // Set up a local as a typed array of F64
        let mut info = VariableTypeInfo::named("Array<number>".to_string());
        info.v2_array_element_kind = Some(FieldKind::F64);
        tracker.set_local_type(0, info);

        assert_eq!(tracker.is_typed_array(0), Some(FieldKind::F64));
        assert_eq!(tracker.is_typed_array(1), None); // unset slot

        // Set up a local as a typed array of I32
        let mut info2 = VariableTypeInfo::named("Array<i32>".to_string());
        info2.v2_array_element_kind = Some(FieldKind::I32);
        tracker.set_local_type(1, info2);

        assert_eq!(tracker.is_typed_array(1), Some(FieldKind::I32));
    }

    #[test]
    fn test_v2_typed_struct_on_variable() {
        use shape_value::v2::struct_layout::{FieldKind, StructLayout};

        let mut tracker = TypeTracker::empty();

        let layout = StructLayout::new(&[
            ("name", FieldKind::Ptr),
            ("age", FieldKind::I32),
            ("score", FieldKind::F64),
        ]);
        let schema_id: SchemaId = 100;
        tracker.register_v2_layout(schema_id, layout);

        // Set up a local with v2_struct_layout
        let mut info = VariableTypeInfo::named("Person".to_string());
        info.v2_struct_layout = Some(schema_id);
        tracker.set_local_type(0, info);

        // Verify is_typed_struct returns the schema ID
        assert_eq!(tracker.is_typed_struct(0), Some(schema_id));
        assert_eq!(tracker.is_typed_struct(1), None);

        // Verify we can look up the layout from the schema ID
        let layout = tracker.get_v2_layout(schema_id).unwrap();
        assert_eq!(layout.field_count(), 3);
        assert_eq!(layout.field_kind(0), FieldKind::Ptr);
        assert_eq!(layout.field_kind(1), FieldKind::I32);
        assert_eq!(layout.field_kind(2), FieldKind::F64);
        assert_eq!(layout.heap_field_mask, 0b001); // only field 0 is Ptr
    }

    #[test]
    fn test_v2_fields_default_none() {
        // All constructors should default v2 fields to None
        let info = VariableTypeInfo::unknown();
        assert!(info.v2_array_element_kind.is_none());
        assert!(info.v2_struct_layout.is_none());

        let info = VariableTypeInfo::number();
        assert!(info.v2_array_element_kind.is_none());
        assert!(info.v2_struct_layout.is_none());

        let info = VariableTypeInfo::named("Foo".to_string());
        assert!(info.v2_array_element_kind.is_none());
        assert!(info.v2_struct_layout.is_none());

        let info = VariableTypeInfo::known(1, "Bar".to_string());
        assert!(info.v2_array_element_kind.is_none());
        assert!(info.v2_struct_layout.is_none());
    }

    /// ε-1 PART 1: the emit-side soundness guard surfaces a `ProofGap`,
    /// labelled `E_TYPED_OPCODE_WITHOUT_PROOF`, carrying the emission site and
    /// the human-readable reason. This is the clean diagnostic the binary-op
    /// emitter raises instead of stamping a default `NativeKind` on an operand
    /// whose type the inference engine could not resolve.
    #[test]
    fn test_proof_gap_unresolved_operand_surfaces_cleanly() {
        let gap = proof_gap_unresolved_operand(
            "emit_typed_arithmetic",
            "operand `x` of `Mul` has an unresolved type",
        );
        assert_eq!(gap.site(), "emit_typed_arithmetic");
        assert!(gap.detail().contains("unresolved type"));
        let rendered = gap.to_string();
        assert!(
            rendered.starts_with("E_TYPED_OPCODE_WITHOUT_PROOF at emit_typed_arithmetic:"),
            "diagnostic must be the labelled proof-gap form, got: {rendered}"
        );
        assert!(rendered.contains("operand `x` of `Mul`"));
    }
}