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
//! Closure (function expression) compilation

use crate::bytecode::{Function, Instruction, OpCode, Operand};
use crate::compiler::monomorphization::type_resolution::concrete_type_for_expr;
use crate::type_tracking::{BindingOwnershipClass, BindingStorageClass};
use shape_ast::ast::type_path::TypePath;
use shape_ast::ast::{Expr, FunctionDef, Span, TypeAnnotation};
use shape_ast::error::{Result, ShapeError};
use shape_runtime::closure::EnvironmentAnalyzer;
use shape_value::v2::concrete_type::{ClosureTypeId, ConcreteType};
use std::collections::BTreeSet;

use super::super::BytecodeCompiler;

/// Strict-typing-sweep (Cluster 2): scan a closure body for binary ops
/// of the form `<param_name> <op> <literal>` (or the symmetric form), and
/// derive a `TypeAnnotation` for `param_name` from the literal's type when
/// the literal has one. This handles the canonical
/// `|x| x + 1` / `|y| y + N` patterns that previously rode on the
/// (now-deleted) Dynamic-emission shim.
///
/// Conservative: returns `None` if the param appears only in untyped
/// contexts, or if the binary op pairs the param with another unknown
/// (e.g. `|x, y| x + y`). The closure body still compiles in those cases
/// — strict-typing simply errors at the offending binary op as before.
pub(crate) fn infer_param_type_from_body(
    param_name: &str,
    body: &[shape_ast::ast::Statement],
) -> Option<TypeAnnotation> {
    use shape_ast::ast::{Literal, Statement};
    fn literal_to_type_ann(lit: &Literal) -> Option<TypeAnnotation> {
        Some(match lit {
            Literal::Int(_) => TypeAnnotation::Basic("int".to_string()),
            Literal::Number(_) => TypeAnnotation::Basic("number".to_string()),
            Literal::Bool(_) => TypeAnnotation::Basic("bool".to_string()),
            Literal::String(_) => TypeAnnotation::Basic("string".to_string()),
            _ => return None,
        })
    }
    fn scan_expr(name: &str, expr: &Expr) -> Option<TypeAnnotation> {
        match expr {
            Expr::BinaryOp { left, right, .. } => {
                if let (Expr::Identifier(n, _), Expr::Literal(lit, _)) =
                    (left.as_ref(), right.as_ref())
                {
                    if n == name {
                        if let Some(t) = literal_to_type_ann(lit) {
                            return Some(t);
                        }
                    }
                }
                if let (Expr::Literal(lit, _), Expr::Identifier(n, _)) =
                    (left.as_ref(), right.as_ref())
                {
                    if n == name {
                        if let Some(t) = literal_to_type_ann(lit) {
                            return Some(t);
                        }
                    }
                }
                scan_expr(name, left).or_else(|| scan_expr(name, right))
            }
            Expr::UnaryOp { operand, .. } => scan_expr(name, operand),
            Expr::FunctionCall { args, .. } => {
                args.iter().find_map(|a| scan_expr(name, a))
            }
            Expr::MethodCall { receiver, args, .. } => {
                scan_expr(name, receiver).or_else(|| args.iter().find_map(|a| scan_expr(name, a)))
            }
            Expr::Array(elements, _) => elements.iter().find_map(|e| scan_expr(name, e)),
            Expr::Return(Some(e), _) => scan_expr(name, e),
            // Match: when the scrutinee is the bare `name`, look at any
            // arm-pattern binding of an identifier and propagate its
            // body/guard usage back to `name`'s type. Conservatively
            // handles the common idiom `match v { x where x > 0 => x }`
            // where `v` and `x` are aliased through pattern binding.
            Expr::Match(match_expr, _) => {
                if let Expr::Identifier(scrutinee_name, _) = match_expr.scrutinee.as_ref() {
                    if scrutinee_name == name {
                        // Look at each arm; if its pattern is a single
                        // identifier `x`, scan the guard + body for
                        // `<x> op <literal>` pairings.
                        for arm in &match_expr.arms {
                            if let shape_ast::ast::Pattern::Identifier(bound_name) =
                                &arm.pattern
                            {
                                if let Some(guard) = arm.guard.as_ref() {
                                    if let Some(t) = scan_expr(bound_name, guard) {
                                        return Some(t);
                                    }
                                }
                                if let Some(t) = scan_expr(bound_name, &arm.body) {
                                    return Some(t);
                                }
                            }
                        }
                    }
                }
                // Otherwise just recurse into scrutinee + arms looking
                // for the original name.
                scan_expr(name, &match_expr.scrutinee)
                    .or_else(|| {
                        match_expr.arms.iter().find_map(|arm| {
                            arm.guard
                                .as_ref()
                                .and_then(|g| scan_expr(name, g))
                                .or_else(|| scan_expr(name, &arm.body))
                        })
                    })
            }
            _ => None,
        }
    }
    fn scan_stmt(name: &str, stmt: &Statement) -> Option<TypeAnnotation> {
        match stmt {
            Statement::Expression(expr, _) => scan_expr(name, expr),
            Statement::Return(Some(e), _) => scan_expr(name, e),
            Statement::VariableDecl(decl, _) => {
                decl.value.as_ref().and_then(|e| scan_expr(name, e))
            }
            Statement::Assignment(asgn, _) => scan_expr(name, &asgn.value),
            _ => None,
        }
    }
    body.iter().find_map(|s| scan_stmt(param_name, s))
}

/// Sweep phase 3c.x: scan a closure body for `param_name op outer_ident`
/// where `outer_ident` has a known type in `known_outer_types`, and
/// propagate that type back to `param_name`. Returns the propagated type
/// name as a `String` (e.g. "int") or `None` if no such pairing is found.
fn infer_param_type_from_outer_pairing(
    param_name: &str,
    body: &[shape_ast::ast::Statement],
    known_outer_types: &std::collections::HashMap<String, String>,
) -> Option<String> {
    use shape_ast::ast::Statement;
    fn scan(name: &str, expr: &Expr, known: &std::collections::HashMap<String, String>) -> Option<String> {
        match expr {
            Expr::BinaryOp { left, right, .. } => {
                if let (Expr::Identifier(ln, _), Expr::Identifier(rn, _)) =
                    (left.as_ref(), right.as_ref())
                {
                    if ln == name {
                        if let Some(t) = known.get(rn) {
                            return Some(t.clone());
                        }
                    }
                    if rn == name {
                        if let Some(t) = known.get(ln) {
                            return Some(t.clone());
                        }
                    }
                }
                scan(name, left, known).or_else(|| scan(name, right, known))
            }
            Expr::UnaryOp { operand, .. } => scan(name, operand, known),
            Expr::Return(Some(e), _) => scan(name, e, known),
            Expr::FunctionCall { args, .. } => {
                args.iter().find_map(|a| scan(name, a, known))
            }
            Expr::MethodCall { receiver, args, .. } => {
                scan(name, receiver, known)
                    .or_else(|| args.iter().find_map(|a| scan(name, a, known)))
            }
            _ => None,
        }
    }
    fn scan_stmt(
        name: &str,
        stmt: &Statement,
        known: &std::collections::HashMap<String, String>,
    ) -> Option<String> {
        match stmt {
            Statement::Expression(e, _) => scan(name, e, known),
            Statement::Return(Some(e), _) => scan(name, e, known),
            _ => None,
        }
    }
    body.iter().find_map(|s| scan_stmt(param_name, s, known_outer_types))
}

/// Strict-typing-sweep (Cluster 1): convert a `ConcreteType` (the v2 typed
/// value-representation type) back into an AST `TypeAnnotation` so it can be
/// attached to a synthetic capture parameter. Returning `None` falls back to
/// the no-annotation path (which is fine for opaque types — those captures
/// never participate in typed binary-ops anyway).
///
/// We map the type-name primitives that `tracked_type_name_from_annotation`
/// recognizes plus `Vec<T>` for arrays. Composite/opaque types
/// (Struct/Enum/Closure/Function/Pointer/HashMap with non-trivial inner)
/// return `None` — they don't need typed-op support inside the closure body.
pub(crate) fn concrete_type_to_type_annotation(ct: &ConcreteType) -> Option<TypeAnnotation> {
    match ct {
        ConcreteType::F64 => Some(TypeAnnotation::Basic("number".to_string())),
        ConcreteType::I64 => Some(TypeAnnotation::Basic("int".to_string())),
        ConcreteType::I32 => Some(TypeAnnotation::Basic("i32".to_string())),
        ConcreteType::I16 => Some(TypeAnnotation::Basic("i16".to_string())),
        ConcreteType::I8 => Some(TypeAnnotation::Basic("i8".to_string())),
        ConcreteType::U64 => Some(TypeAnnotation::Basic("u64".to_string())),
        ConcreteType::U32 => Some(TypeAnnotation::Basic("u32".to_string())),
        ConcreteType::U16 => Some(TypeAnnotation::Basic("u16".to_string())),
        ConcreteType::U8 => Some(TypeAnnotation::Basic("u8".to_string())),
        ConcreteType::Bool => Some(TypeAnnotation::Basic("bool".to_string())),
        ConcreteType::String => Some(TypeAnnotation::Basic("string".to_string())),
        ConcreteType::Decimal => Some(TypeAnnotation::Basic("decimal".to_string())),
        ConcreteType::BigInt => Some(TypeAnnotation::Basic("bigint".to_string())),
        ConcreteType::DateTime => Some(TypeAnnotation::Basic("DateTime".to_string())),
        ConcreteType::Array(inner) => {
            // Render as Vec<T> via the Generic form so
            // `tracked_type_name_from_annotation` produces "Vec<int>" /
            // "Vec<number>" — the names the type-tracker keys typed array
            // ops on.
            concrete_type_to_type_annotation(inner).map(|inner_ann| TypeAnnotation::Generic {
                name: TypePath::simple("Vec"),
                args: vec![inner_ann],
            })
        }
        // Nullable: drop the wrapper — the captured variable is the inner
        // value at the binary-op site if the closure narrows it. No-annotation
        // is safer than a wrong annotation.
        ConcreteType::Option(_) => None,
        // Other composite / opaque types: no useful annotation for the
        // type-tracker. The capture lives as a Pointer-typed slot via the
        // closure layout and does not participate in typed binops.
        _ => None,
    }
}

/// Sweep phase 3c.1: extract a primitive scalar type-name from a
/// runtime `Type`. Mirrors the subset of `numeric_ops::type_display_name`
/// the closure return-type inference cares about.
pub(crate) fn type_display_name_for_closure_inference(
    ty: &shape_runtime::type_system::Type,
) -> String {
    use shape_runtime::type_system::Type;
    match ty {
        Type::Concrete(TypeAnnotation::Basic(name)) => name.clone(),
        Type::Concrete(TypeAnnotation::Reference(name)) => name.to_string(),
        _ => String::new(),
    }
}

/// Sweep phase 3c.1: infer a return-type name for a closure expression
/// based on its body, params, and the outer scope (via `compiler`).
///
/// Conservative; returns `None` when any operand or sub-expression cannot
/// be statically resolved. Used by `update_callable_binding_from_expr` to
/// populate `local_callable_return_types` so a `FunctionCall` against a
/// `let f = |…|` binding can recover `f`'s return type for strict-typing
/// binop dispatch (`f(5) + f(7)` etc.).
///
/// The helper:
/// 1. Honours an explicit `-> T` return annotation when present.
/// 2. Otherwise builds a `HashMap<String, String>` of param-name → tracked
///    type-name from the closure's params (using their annotations or the
///    body-level literal-pairing heuristic the closure compiler itself
///    relies on).
/// 3. Walks the body's terminal expression and resolves identifiers via
///    that map first, then falls back to outer-scope resolution via
///    `concrete_type_for_expr` (which recognises `let base = 100` as I64).
/// 4. Recurses into binary ops, requiring both operand types to agree
///    (and to be one of the primitive scalar names) for the result to be
///    inferred.
pub(crate) fn infer_closure_body_return_type_name(
    compiler: &mut BytecodeCompiler,
    params: &[shape_ast::ast::FunctionParameter],
    body: &[shape_ast::ast::Statement],
    explicit_return: Option<&TypeAnnotation>,
) -> Option<String> {
    infer_closure_body_return_type_name_with_outer(compiler, params, body, explicit_return, &[])
}

/// Sweep phase 3c.x: variant that also accepts a list of enclosing-scope
/// parameters whose names should resolve to their declared types when
/// scanning the closure body. Used by `update_callable_binding_from_expr`
/// for the `let f = make(...)` → `f(arg) + f(arg)` pattern, where `make`'s
/// returned closure captures `make`'s parameters by name and we want to
/// recover their declared types without actually compiling `make`'s body.
pub(crate) fn infer_closure_body_return_type_name_with_outer(
    compiler: &mut BytecodeCompiler,
    params: &[shape_ast::ast::FunctionParameter],
    body: &[shape_ast::ast::Statement],
    explicit_return: Option<&TypeAnnotation>,
    enclosing_params: &[shape_ast::ast::FunctionParameter],
) -> Option<String> {
    infer_closure_body_return_type_name_with_caller_context(
        compiler,
        params,
        body,
        explicit_return,
        enclosing_params,
        &[],
    )
}

/// cluster-2-cw-IB-class-b (2026-05-16, supervisor R3 binding-ratified):
/// caller-context-aware variant of the closure-body return-type inference.
///
/// `caller_arg_type_names[i]` is the type name (e.g. `"Vec<int>"`,
/// `"int"`, `"string"`) of the i-th argument the closure is being called
/// with at the call site. This seeds `param_types[params[i].name]` when
/// the closure param has no explicit annotation AND no body-literal
/// pairing — i.e. the case where the closure's param is inferred-typed
/// at the call site rather than declared.
///
/// Class B fixture (inventory §B.2):
///   `let xs: Array<int> = [1,2,3,4,5]`
///   `let f = |inner| inner.sum()`
///   `print(f(xs))`
///
/// At `f(xs)`, `caller_arg_type_names[0] = Some("Vec<int>")` (derived
/// from `concrete_type_for_expr(xs)` → `Array(I64)` →
/// `concrete_type_to_type_annotation` → `Generic("Vec", [int])` →
/// `tracked_type_name_from_annotation` → `"Vec<int>"`). The body's
/// terminal expression `inner.sum()` then resolves via the extended
/// `expr_type` MethodCall arm: receiver `inner` has type
/// `"Vec<int>"`; method `sum` on `Vec<scalar>` returns the element
/// scalar `"int"`.
///
/// ADR-006 §2.7.5 stamp-at-compile-time: the caller-supplied arg type
/// IS the proof of the closure param's type at the call site — no
/// runtime probe, no fabricated Bool-default. The inference returns
/// `None` when the body's terminal expression cannot be resolved
/// against the seeded param_types.
pub(crate) fn infer_closure_body_return_type_name_with_caller_context(
    compiler: &mut BytecodeCompiler,
    params: &[shape_ast::ast::FunctionParameter],
    body: &[shape_ast::ast::Statement],
    explicit_return: Option<&TypeAnnotation>,
    enclosing_params: &[shape_ast::ast::FunctionParameter],
    caller_arg_type_names: &[Option<String>],
) -> Option<String> {
    use shape_ast::ast::{BinaryOp as Op, Literal, Statement};
    use std::collections::HashMap;

    if let Some(ann) = explicit_return {
        if let Some(name) = BytecodeCompiler::tracked_type_name_from_annotation(ann) {
            return Some(name);
        }
    }

    // Build param-type map. Start with the enclosing-scope params (e.g.
    // the captured `n: int` from `fn make(n: int) -> any { return |x| x + n }`)
    // so the closure body can resolve free identifiers that came from the
    // outer function. Closure-local params override on name collision.
    let mut param_types: HashMap<String, String> = HashMap::new();
    for p in enclosing_params {
        let Some(ident) = p.pattern.as_identifier() else {
            continue;
        };
        if let Some(ann) = &p.type_annotation {
            if let Some(tn) = BytecodeCompiler::tracked_type_name_from_annotation(ann) {
                param_types.insert(ident.to_string(), tn);
            }
        }
    }
    for (param_idx, p) in params.iter().enumerate() {
        let Some(ident) = p.pattern.as_identifier() else {
            continue;
        };
        if let Some(ann) = &p.type_annotation {
            if let Some(tn) = BytecodeCompiler::tracked_type_name_from_annotation(ann) {
                param_types.insert(ident.to_string(), tn);
                continue;
            }
        }
        // Fallback: same body-literal-pairing heuristic the closure
        // compiler uses for unannotated params (`|x| x + 1`).
        if let Some(ann) = infer_param_type_from_body(ident, body) {
            if let Some(tn) = BytecodeCompiler::tracked_type_name_from_annotation(&ann) {
                param_types.insert(ident.to_string(), tn);
            }
        }
        // Sweep phase 3c.x: when the param has no annotation and no
        // body-literal pairing, but the body uses it in a binary op
        // against an enclosing-param that IS typed, infer the closure
        // param's type from the enclosing param's type. Covers
        // `|x| x + n` over `fn make(n: int) ...`.
        if !param_types.contains_key(ident) {
            if let Some(tn) = infer_param_type_from_outer_pairing(ident, body, &param_types) {
                param_types.insert(ident.to_string(), tn);
            }
        }
        // cluster-2-cw-IB-class-b: when no inferred type from local
        // sources, fall through to the caller-context-supplied arg
        // type. The arg's type at the call site IS the proof of the
        // param's type when the closure is invoked there. ADR-006
        // §2.7.5 stamp-at-compile-time — call-site arg type comes
        // from `concrete_type_for_expr(arg)` at bytecode-emission, not
        // from a runtime probe.
        if !param_types.contains_key(ident) {
            if let Some(Some(caller_tn)) = caller_arg_type_names.get(param_idx) {
                param_types.insert(ident.to_string(), caller_tn.clone());
            }
        }
    }

    fn lit_type(lit: &Literal) -> Option<String> {
        Some(
            match lit {
                Literal::Int(_) => "int",
                Literal::Number(_) => "number",
                Literal::Bool(_) => "bool",
                Literal::String(_) | Literal::FormattedString { .. } => "string",
                Literal::Decimal(_) => "decimal",
                _ => return None,
            }
            .to_string(),
        )
    }

    fn expr_type(
        compiler: &mut BytecodeCompiler,
        param_types: &HashMap<String, String>,
        expr: &Expr,
    ) -> Option<String> {
        match expr {
            Expr::Literal(lit, _) => lit_type(lit),
            Expr::Identifier(name, _) => {
                if let Some(tn) = param_types.get(name) {
                    return Some(tn.clone());
                }
                // Outer-scope resolution: try `concrete_type_for_expr`
                // first (covers tracker-recorded primitives + array
                // element types), then fall back to the compiler's
                // `infer_expr_type` (which consults the type-inference
                // engine that ran on the program AST and can see
                // `let base = 100` even when the type tracker has no
                // entry for `base`).
                let ident_expr = Expr::Identifier(name.clone(), Span::DUMMY);
                if let Some(ct) = concrete_type_for_expr(compiler, &ident_expr) {
                    if let Some(tn) = concrete_type_to_type_annotation(&ct)
                        .and_then(|ann| BytecodeCompiler::tracked_type_name_from_annotation(&ann))
                    {
                        return Some(tn);
                    }
                }
                if let Ok(ty) = compiler.infer_expr_type(&ident_expr) {
                    let display = type_display_name_for_closure_inference(&ty);
                    if BytecodeCompiler::tracker_type_name_is_primitive(&display) {
                        return Some(display);
                    }
                }
                None
            }
            Expr::BinaryOp { left, right, op, .. } => {
                let lt = expr_type(compiler, param_types, left)?;
                let rt = expr_type(compiler, param_types, right)?;
                match op {
                    // Arithmetic on matching primitive scalar types
                    // preserves the type. Comparison/logical ops yield
                    // bool.
                    Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Mod => {
                        if lt == rt && BytecodeCompiler::tracker_type_name_is_primitive(&lt) {
                            Some(lt)
                        } else {
                            None
                        }
                    }
                    Op::Equal
                    | Op::NotEqual
                    | Op::Less
                    | Op::LessEq
                    | Op::Greater
                    | Op::GreaterEq
                    | Op::And
                    | Op::Or => Some("bool".to_string()),
                    _ => None,
                }
            }
            Expr::UnaryOp { operand, .. } => expr_type(compiler, param_types, operand),
            Expr::Return(Some(inner), _) => expr_type(compiler, param_types, inner),
            Expr::Block(block, _) => {
                let last = block.items.last()?;
                match last {
                    shape_ast::ast::BlockItem::Expression(e) => {
                        expr_type(compiler, param_types, e)
                    }
                    shape_ast::ast::BlockItem::Statement(s) => {
                        stmt_type(compiler, param_types, s)
                    }
                    _ => None,
                }
            }
            // cluster-2-cw-IB-class-b (2026-05-16, supervisor R3 binding-
            // ratified): MethodCall arm. Mirrors the JIT-side
            // `well_known_method_return_kind` +
            // `parametric_method_return_kind_from_receiver` classifier shape
            // (`crates/shape-jit/src/mir_compiler/types.rs:818-1019`) — the
            // single source of truth for kind-classification across both
            // bytecode-emission and JIT-MIR layers.
            //
            // Class B fixture (inventory §B.2): `let f = |inner| inner.sum()`
            // with `inner` resolved (via caller-context arg type) to
            // `"Vec<int>"`. `inner.sum()` matches the parametric
            // `("sum"|..., Array(elem))` arm and returns the element
            // scalar `"int"`. The downstream conduit value-call
            // destination-stamping pass then stamps the Call-terminator's
            // destination slot with `ConcreteType::I64`, and the JIT-MIR
            // `slot_kinds` projection picks up `NativeKind::Int64`, closing
            // the `print(f(xs))` chain.
            //
            // Invariant-return methods (size/len/length/count → int,
            // isEmpty/contains/has → bool) are receiver-shape-agnostic
            // and matched first. Parametric methods consult the
            // receiver's resolved type name — supports `Vec<scalar>`
            // shape recognition (i.e. element-typed accessors on typed
            // arrays).
            //
            // No tag-bit decode, no Bool-default fallback, no fabricated
            // default — when the receiver type isn't recognised or the
            // method name isn't in either classifier, returns `None` so
            // the outer caller's value-call stamping stays Void per
            // §2.7.5.1 / §2.7.7 #9.
            Expr::MethodCall { receiver, method, args, .. } => {
                // Invariant-across-receiver methods: classify from name
                // alone without needing the receiver's type.
                let invariant_kind: Option<&'static str> = match method.as_str() {
                    "size" | "len" | "length" | "count" => Some("int"),
                    "isEmpty" | "is_empty" | "has" | "contains" => Some("bool"),
                    _ => None,
                };
                if let Some(kind) = invariant_kind {
                    return Some(kind.to_string());
                }

                // Parametric methods: receiver's resolved type name
                // determines the return type. Resolve the receiver via
                // the same expr_type walker (so `inner` resolves to its
                // seeded param_types entry like "Vec<int>").
                let recv_ty = expr_type(compiler, param_types, receiver)?;

                // `Vec<T>` element-typed accessors. The element name
                // strips the `Vec<...>` wrapper. Matches the JIT-side
                // `("sum" | "mean" | "min" | "max", ConcreteType::Array
                // (elem))` arm at `types.rs:976-981`.
                if let Some(elem) = recv_ty
                    .strip_prefix("Vec<")
                    .and_then(|s| s.strip_suffix('>'))
                {
                    match method.as_str() {
                        "sum" | "mean" | "min" | "max" | "get" => {
                            // .get(i) returns element T directly per the
                            // JIT-side classifier; .sum/.mean/.min/.max
                            // also return element T (the typed-array
                            // method registry returns
                            // `KindedSlot::from_<elem>` per receiver-
                            // element kind).
                            if BytecodeCompiler::tracker_type_name_is_primitive(elem) {
                                return Some(elem.to_string());
                            }
                        }
                        _ => {}
                    }
                }

                // Receiver-type-specific arms for built-in scalar types
                // can be added here as needed; bounded to the same set
                // the JIT-side classifier supports to avoid drift.
                let _ = args;
                None
            }
            _ => None,
        }
    }

    fn stmt_type(
        compiler: &mut BytecodeCompiler,
        param_types: &HashMap<String, String>,
        stmt: &Statement,
    ) -> Option<String> {
        match stmt {
            Statement::Expression(e, _) => expr_type(compiler, param_types, e),
            Statement::Return(Some(e), _) => expr_type(compiler, param_types, e),
            _ => None,
        }
    }

    // Find body's terminal expression: prefer last statement; if it's a
    // `Return(e)` use e, else if it's an expression statement use it.
    let last = body.last()?;
    stmt_type(compiler, &param_types, last)
}

impl BytecodeCompiler {
    /// Compile a function expression (closure)
    ///
    /// `closure_span` is the span of the `||`/`|args|` expression itself
    /// — used by Session 1's Rust-move move-after-capture diagnostic to
    /// point at the capturing closure that consumed a `let mut` binding.
    pub(super) fn compile_expr_closure(
        &mut self,
        params: &[shape_ast::ast::FunctionParameter],
        body: &[shape_ast::ast::Statement],
        closure_span: Span,
    ) -> Result<()> {
        let closure_name = format!("__closure_{}", self.closure_counter);
        self.closure_counter += 1;

        let proto_def = FunctionDef {
            name: closure_name.clone(),
            name_span: Span::DUMMY,
            declaring_module_path: None,
            doc_comment: None,
            type_params: None,
            params: params.to_vec(),
            return_type: None,
            body: body.to_vec(),
            annotations: vec![],
            where_clause: None,
            is_async: false,
            is_comptime: false,
        };

        let outer_vars = self.collect_outer_scope_vars();
        let (mut captured_vars, mutated_captures) =
            EnvironmentAnalyzer::analyze_function_with_mutability(&proto_def, &outer_vars);
        captured_vars.sort();
        let param_names: BTreeSet<String> =
            params.iter().flat_map(|p| p.get_identifiers()).collect();
        captured_vars.retain(|name| !param_names.contains(name));

        // Inside function bodies the MIR solver detects reference-capture errors
        // via `closure_capture_loans` facts, producing `ReferenceEscapeIntoClosure`.
        // For top-level code (no MIR), we still reject at the front-end.
        // Exception: inferred-ref locals (params passed by reference for performance)
        // are owned values and CAN be captured — the value is dereferenced at capture time.
        if self.current_function.is_none() {
            for captured in &captured_vars {
                if let Some(local_idx) = self.resolve_local(captured) {
                    let escapes_direct_borrow = self.ref_locals.contains(&local_idx)
                        && !self.inferred_ref_locals.contains(&local_idx);
                    let escapes_reference_value = self.reference_value_locals.contains(&local_idx);
                    if escapes_direct_borrow || escapes_reference_value {
                        return Err(ShapeError::SemanticError {
                            message: format!(
                                "[B0003] reference '{}' cannot escape into a closure; capture a value instead",
                                captured
                            ),
                            location: None,
                        });
                    }
                }

                if let Some(scoped_name) = self.resolve_scoped_module_binding_name(captured)
                    && let Some(&binding_idx) = self.module_bindings.get(&scoped_name)
                    && self.reference_value_module_bindings.contains(&binding_idx)
                {
                    return Err(ShapeError::SemanticError {
                        message: format!(
                            "[B0003] reference '{}' cannot escape into a closure; capture a value instead",
                            captured
                        ),
                        location: None,
                    });
                }
            }
        }

        // BUG1 — reject assignment to an immutable (`let`) outer binding
        // from inside the closure body. The environment analyzer marks
        // the binding in `mutated_captures` when the closure writes to
        // it; if the outer binding's ownership class is `OwnedImmutable`
        // (the `let` form), the write violates Shape's immutability
        // rules. Without this check the compiler still lowers a
        // `MakeClosure` whose capture layout mismatches the legacy
        // SharedCell path, producing the runtime-only crash
        // `MakeClosure for function N has no registered ClosureLayout`.
        // The diagnostic uses code `B0005` — the same code used for other
        // immutability/move violations across closure boundaries — and
        // suggests both `let mut` (local mutation) and `var` (shareable
        // mutation through closure captures) to match CLAUDE.md guidance.
        for captured in &captured_vars {
            if !mutated_captures.contains(captured) {
                continue;
            }
            let ownership = self
                .binding_semantics_for_name(captured)
                .map(|(_, _, sem)| sem.ownership_class);
            if !matches!(ownership, Some(BindingOwnershipClass::OwnedImmutable)) {
                continue;
            }
            let is_local_slot = self.resolve_local(captured).is_some();
            let is_module_binding_slot = !is_local_slot
                && (self.resolve_scoped_module_binding_name(captured).is_some()
                    || self.module_bindings.contains_key(captured));
            if !is_local_slot && !is_module_binding_slot {
                continue;
            }
            return Err(ShapeError::SemanticError {
                message: format!(
                    "[B0005] cannot assign to immutable binding '{captured}' captured by \
                     closure; use `let mut {captured}` for local mutation or `var {captured}` \
                     to allow shared mutation through closures"
                ),
                location: Some(self.span_to_source_location(closure_span)),
            });
        }

        // Build per-capture mutability flags (aligned with captured_vars order).
        // A capture is mutable if the closure itself mutates it OR if a previous
        // closure in the same scope already boxed it into a SharedCell.
        let mutable_flags: Vec<bool> = captured_vars
            .iter()
            .map(|name| mutated_captures.contains(name) || self.boxed_locals.contains(name))
            .collect();

        // Build closure parameters: only immutable captures become leading params.
        // Mutable captures are accessed via LoadClosure/StoreClosure opcodes.
        //
        // Strict-typing-sweep (Cluster 1): synthesize a `type_annotation` for each
        // capture from its resolved upstream `ConcreteType`. Without this the
        // capture-param falls into the "no annotation" branch in
        // `compile_function_body` (line ~1182) and ends up in `param_locals` with
        // no type info — which then makes binary-ops on the capture inside the
        // closure body fail with "Cannot infer types for binary operation".
        let mut closure_params = Vec::with_capacity(captured_vars.len() + params.len());
        for name in &captured_vars {
            let ident_expr = Expr::Identifier(name.clone(), Span::DUMMY);
            let capture_ct = concrete_type_for_expr(self, &ident_expr);
            let type_annotation = capture_ct
                .as_ref()
                .and_then(concrete_type_to_type_annotation);
            closure_params.push(shape_ast::ast::FunctionParameter {
                pattern: shape_ast::ast::DestructurePattern::Identifier(name.clone(), Span::DUMMY),
                is_const: false,
                is_reference: false,
                is_mut_reference: false,
                is_out: false,
                type_annotation,
                default_value: None,
            });
        }

        // Strict-typing-sweep (Cluster 3): consume bidirectional inference
        // hints for the user-portion params. The outer HOF dispatch site
        // populates `pending_closure_param_types` with one Option<TypeAnnotation>
        // per user param when the receiver type implies an arg type
        // (`arr.map(|x| …)` with `arr: Array<int>` → `x: int`). User params
        // with their own explicit annotation always win.
        let user_param_hints = self.pending_closure_param_types.take();

        // Strict-typing-sweep (Cluster 2): closure-body param inference.
        // For closures bound to a `let` and called via the local (or
        // synthesized inside a generic body where const-args have been
        // substituted to literals), we don't have an HOF-style call-site
        // hint. Infer each unannotated user param's type by scanning the
        // body for binary ops `<param> op <literal>` and pulling the
        // literal's type. This is the same conservative heuristic that
        // closure compilation has always relied on for `|x| x + 1`-shaped
        // bodies, just made first-class instead of riding on the deleted
        // *Dynamic-emission shim.
        for (idx, user_param) in params.iter().enumerate() {
            let mut p = user_param.clone();
            if p.type_annotation.is_none() {
                // 1. HOF call-site hint wins first.
                if let Some(hints) = user_param_hints.as_ref() {
                    if let Some(Some(ann)) = hints.get(idx) {
                        p.type_annotation = Some(ann.clone());
                    }
                }
                // 2. Body-level literal-pairing heuristic. Pulls type
                //    info from any binary op pairing the param with a
                //    typed literal OR with a captured/outer-scope
                //    identifier whose type is known.
                if p.type_annotation.is_none() {
                    if let Some(name) = p.pattern.as_identifier() {
                        if let Some(ann) = infer_param_type_from_body(name, body) {
                            p.type_annotation = Some(ann);
                        } else if let Some(ann) =
                            self.infer_param_type_from_body_with_outer_idents(name, body)
                        {
                            p.type_annotation = Some(ann);
                        }
                    }
                }
            }
            closure_params.push(p);
        }

        let closure_def = FunctionDef {
            name: closure_name.clone(),
            name_span: Span::DUMMY,
            declaring_module_path: None,
            doc_comment: None,
            type_params: None,
            params: closure_params,
            return_type: None,
            body: body.to_vec(),
            annotations: vec![],
            where_clause: None,
            is_async: false,
            is_comptime: false,
        };

        let user_pass_modes = self.effective_function_like_pass_modes(None, params, Some(body));
        let mut closure_pass_modes =
            vec![crate::compiler::ParamPassMode::ByValue; captured_vars.len()];
        closure_pass_modes.extend(user_pass_modes);
        let ref_params: Vec<_> = closure_pass_modes
            .iter()
            .map(|mode| mode.is_reference())
            .collect();
        let ref_mutates: Vec<_> = closure_pass_modes
            .iter()
            .map(|mode| mode.is_exclusive())
            .collect();
        self.inferred_param_pass_modes
            .insert(closure_name.clone(), closure_pass_modes);

        // Phase A: mint a ClosureTypeId keyed on the capture signature.
        //
        // Resolves each captured name to a `ConcreteType` via the monomorphizer
        // helpers; unresolved captures fall back to `Pointer(Void)` (opaque
        // 8-byte slot, conservatively treated as a heap-refcounted pointer by
        // the layout's `heap_capture_mask`). This records layout metadata in
        // `closure_registry` that Phase C consumes to extend the monomorphization
        // cache key. Emission is unchanged.
        let closure_type_id = self.mint_closure_type_id(&captured_vars);

        // Phase F: mint a FunctionTypeId for the callable signature. This is
        // the `Function<A, R>` identity — the signature omits captures and
        // covers only the parameters the caller supplies plus the return.
        //
        // Phase F keeps signature resolution conservative: param / return
        // types that lack compile-time resolution fall back to `Void`. The
        // ID is still globally unique per structural signature (driven by
        // the registry's intern), so `CallFunctionIndirect` can pick a
        // Cranelift call signature once signature inference lands. Two
        // closures with structurally identical callable shapes share a
        // `FunctionTypeId` even when their capture layouts (and hence
        // `ClosureTypeId`s) differ — this is exactly what `Array<Function<
        // (int) -> int>>` relies on for polymorphic dispatch.
        let function_type_id = self.mint_function_type_id_for_params(params);

        let func_idx = self.program.functions.len();
        self.program.functions.push(Function {
            name: closure_name.clone(),
            arity: closure_def.params.len() as u16,
            param_names: closure_def
                .params
                .iter()
                .flat_map(|p| p.get_identifiers())
                .collect(),
            locals_count: 0,
            entry_point: 0,
            body_length: 0,
            is_closure: true,
            captures_count: captured_vars.len() as u16,
            is_async: false,
            ref_params,
            ref_mutates,
            mutable_captures: mutable_flags.clone(),
            frame_descriptor: None,
            osr_entry_points: Vec::new(),
            mir_data: None,
        });

        // Record closure function_id for MIR back-patching (ClosurePlaceholder → Function)
        self.closure_function_ids
            .push((closure_name.clone(), func_idx as u16));
        // Phase A: record the closure's ClosureTypeId against its function index.
        self.closure_type_ids
            .push((func_idx as u16, closure_type_id));
        // Phase F: record the closure's FunctionTypeId alongside the capture
        // layout id. One entry per closure literal, same ordering as
        // `closure_type_ids`.
        self.function_type_ids
            .push((func_idx as u16, function_type_id));

        // Track A.1C — derive the `CaptureKind` for each capture based on
        // the source binding's declared form AND whether the closure body
        // actually mutates the capture.
        //
        // Binding form (when mutated inside the closure) → CaptureKind:
        //   `let mut x = ...`   (OwnedMutable source)   → CaptureKind::OwnedMutable
        //   `var x = ...`       (Flexible source)       → CaptureKind::Shared
        //
        // Everything else (including read-only captures of `let mut` /
        // `var` bindings, and all captures of `let` / function parameters)
        // → `CaptureKind::Immutable`. A read-only capture is semantically
        // a by-value snapshot and does not require cell indirection.
        //
        // Note (A.1C partial): this metadata rides on the layout's
        // `capture_kinds` field only. The mutable-mask bits on the layout
        // remain zero in this commit — see the design note on
        // `build_closure_function_layouts`. The interpreter's
        // `op_make_closure` still routes mutable-capture closures through
        // the legacy `HeapValue::Closure` + SharedCell path because the
        // compiler has not yet been rewired to emit the A.1B
        // `Load/StoreOwnedMutableCapture` / `Load/StoreSharedCapture`
        // opcodes in closure bodies, and outer-scope reads of promoted
        // `let mut` / `var` bindings still flow through `LoadClosure` +
        // `HeapValue::SharedCell` auto-deref. Full routing is the A.1C
        // residual.
        use shape_value::v2::closure_layout::CaptureKind;
        let capture_kinds: Vec<CaptureKind> = captured_vars
            .iter()
            .enumerate()
            .map(|(i, name)| {
                // Only mutated captures need cell indirection. Read-only
                // captures are snapshot-by-value and stay Immutable
                // regardless of the source binding's ownership class —
                // this keeps function-parameter captures (default
                // `OwnedMutable` per `binding_semantics_for_param`) on
                // the Immutable path when the closure doesn't write
                // through them.
                if !mutable_flags.get(i).copied().unwrap_or(false) {
                    return CaptureKind::Immutable;
                }
                // Track A.1C.2 (locals) + A.1C.3 (module bindings): any
                // mutable `var` capture routes through
                // `CaptureKind::Shared`, whether the outer slot is a
                // local or a module binding. Both paths allocate an
                // `Arc<parking_lot::Mutex<u64>>` and install its
                // `Arc::into_raw` pointer into the closure's Ptr slot;
                // `op_make_closure` bumps the strong count. The compiler
                // emits different *outer-scope* opcodes for local vs
                // module-binding promotion (`AllocSharedLocal` vs
                // `AllocSharedModuleBinding`), but the closure-side
                // machinery is the same.
                let is_local_slot = self.resolve_local(name).is_some();
                let is_module_binding_slot = !is_local_slot
                    && (self.resolve_scoped_module_binding_name(name).is_some()
                        || self.module_bindings.contains_key(name));
                let ownership = self
                    .binding_semantics_for_name(name)
                    .map(|(_, _, sem)| sem.ownership_class);
                match ownership {
                    // Track A.1C.2b: `let mut` captures whose outer slot
                    // is a local flow through the A.1B OwnedMutable
                    // Raw path. For module-binding `let mut` (top-level
                    // `let mut sum = 0` in REPL-style eval compiles to
                    // a module binding), there is no move-into-closure
                    // semantics — the binding is program-lifetime. Fall
                    // through to the Shared pipeline so mutations from
                    // the closure propagate to the outer slot, matching
                    // the pre-A.1C.3 legacy SharedCell semantics.
                    Some(BindingOwnershipClass::OwnedMutable) if is_local_slot => {
                        CaptureKind::OwnedMutable
                    }
                    Some(BindingOwnershipClass::OwnedMutable) if is_module_binding_slot => {
                        CaptureKind::Shared
                    }
                    Some(BindingOwnershipClass::OwnedMutable) => CaptureKind::Immutable,
                    Some(BindingOwnershipClass::Flexible)
                        if is_local_slot || is_module_binding_slot =>
                    {
                        CaptureKind::Shared
                    }
                    Some(BindingOwnershipClass::Flexible) => CaptureKind::Immutable,
                    // Track A.1C.2 / A.1C.3: semantics lookup can return
                    // `None` when a prior closure's `compile_function`
                    // wiped the outer function's type-tracker local
                    // semantics. Fall back to persistent witnesses
                    // populated by the previous classification pass:
                    //   - `shared_locals` / `shared_module_bindings`
                    //     for `var` captures.
                    //   - `owned_mutable_locals` for `let mut` local
                    //     captures (A.1C.3: without this witness, a
                    //     second closure capturing a different local
                    //     would reclassify to `Immutable`, nulling the
                    //     layout's OwnedMutable mask and tripping the
                    //     `op_make_closure` layout-mismatch guard).
                    _ if is_local_slot && self.shared_locals.contains(name) => CaptureKind::Shared,
                    _ if is_local_slot && self.owned_mutable_locals.contains(name) => {
                        CaptureKind::OwnedMutable
                    }
                    _ if is_module_binding_slot
                        && self.shared_module_binding_contains(name) =>
                    {
                        CaptureKind::Shared
                    }
                    // A.1C.3: module-binding captures with no resolved
                    // ownership semantics (e.g. imported functions used
                    // as callable values, top-level `let` without `mut`
                    // — unreachable here since `mutable_flags[i]` is
                    // true) also go through Shared when the closure
                    // mutates them. `mutable_flags[i]` is already known
                    // true at this point (early return above).
                    _ if is_module_binding_slot => CaptureKind::Shared,
                    _ => CaptureKind::Immutable,
                }
            })
            .collect();
        // Track A.1C.3: record persistent witnesses for each classified
        // capture so sibling closures (after the type-tracker has been
        // wiped by `compile_function`) reclassify the same way rather
        // than falling back to `Immutable`.
        for (i, name) in captured_vars.iter().enumerate() {
            match capture_kinds[i] {
                CaptureKind::OwnedMutable if self.resolve_local(name).is_some() => {
                    self.owned_mutable_locals.insert(name.clone());
                }
                _ => {}
            }
        }
        self.closure_capture_kinds
            .push((func_idx as u16, capture_kinds.clone()));

        // Track A.1C.2: if any capture is non-Immutable, re-intern the
        // closure_type_id under the kinds-aware registry key so two
        // closures with identical types but different kinds get distinct
        // `ClosureTypeId`s. When all captures are Immutable, the original
        // types-only intern already returned the canonical id — skip.
        if capture_kinds
            .iter()
            .any(|k| !matches!(k, CaptureKind::Immutable))
        {
            use shape_value::v2::concrete_type::ConcreteType;
            let capture_types: Vec<ConcreteType> = captured_vars
                .iter()
                .map(|name| {
                    let ident = Expr::Identifier(name.clone(), Span::DUMMY);
                    concrete_type_for_expr(self, &ident)
                        .unwrap_or_else(|| ConcreteType::Pointer(Box::new(ConcreteType::Void)))
                })
                .collect();
            let kinds_id = self
                .closure_registry
                .intern_with_kinds(capture_types, capture_kinds.clone());
            // Overwrite the last-pushed `closure_type_ids` entry for this
            // function with the kinds-aware id. The Immutable entry
            // produced by `mint_closure_type_id` (which ignores kinds)
            // remains in the registry for all-immutable closures.
            if let Some(last) = self.closure_type_ids.last_mut() {
                debug_assert_eq!(last.0, func_idx as u16);
                last.1 = kinds_id;
            }
            let _ = closure_type_id; // the kinds-aware id supersedes it.
        }

        // Track A.1C.2b — enforce `let mut` escape rejection (§4.3).
        //
        // `let mut` bindings captured by an escaping closure are a
        // compile error: `let mut` is a unique-owner form, and moving
        // it into a heap closure that outlives the surrounding frame
        // would leak the owner out of its original scope. The compiler
        // rejects this with B0003 and asks the user to promote the
        // source to `var` (shared) or restructure. Non-escaping
        // closures (the common case) are fine — the `let mut` binding
        // is moved by value into a single closure at make-closure time
        // and accessed inside the body via `LoadOwnedMutableCapture` /
        // `StoreOwnedMutableCapture` (A.1B).
        //
        // The heap-promotion signal is `emit_make_closure_heap_next`.
        let closure_is_escaping = self.emit_make_closure_heap_next;
        for (i, name) in captured_vars.iter().enumerate() {
            if !mutable_flags.get(i).copied().unwrap_or(false) {
                continue;
            }
            let local_idx = self.resolve_local(name);
            let plan_class = local_idx.and_then(|idx| self.mir_storage_class_for_slot(idx));
            let ownership = self
                .binding_semantics_for_name(name)
                .map(|(_, _, sem)| sem.ownership_class);

            if matches!(ownership, Some(BindingOwnershipClass::OwnedMutable))
                && !matches!(
                    plan_class,
                    Some(BindingStorageClass::LocalMutablePtr)
                        | Some(BindingStorageClass::Reference)
                        | Some(BindingStorageClass::Direct)
                        | Some(BindingStorageClass::Deferred)
                        | None,
                )
            {
                return Err(ShapeError::SemanticError {
                    message: format!(
                        "[B0003] mutable binding '{}' cannot be captured by an escaping closure; \
                         promote the source to `var` or restructure to keep the closure local",
                        name
                    ),
                    location: None,
                });
            }
        }

        // Set up the per-kind closure-body emission maps. During body
        // compilation:
        //   * `mutable_closure_captures` → legacy `LoadClosure` /
        //     `StoreClosure` (module-binding `var` captures and any
        //     residual capture whose outer slot could not be migrated
        //     to A.1B's Raw path).
        //   * `owned_mutable_closure_captures` → A.1B's
        //     `LoadOwnedMutableCapture` / `StoreOwnedMutableCapture`
        //     for `let mut` captures (outer slot is moved by value into
        //     the closure at make-closure time; closure owns the
        //     `Box::into_raw(Box::new(initial))` pointer).
        //   * `shared_closure_captures` → A.1B's `LoadSharedCapture` /
        //     `StoreSharedCapture` for `var` (local-slot) captures
        //     previously promoted via `AllocSharedLocal`.
        let saved_mutable_captures = std::mem::take(&mut self.mutable_closure_captures);
        let saved_shared_captures = std::mem::take(&mut self.shared_closure_captures);
        let saved_owned_mutable_captures =
            std::mem::take(&mut self.owned_mutable_closure_captures);
        let saved_owned_mutable_capture_inner_kinds =
            std::mem::take(&mut self.owned_mutable_capture_inner_kinds);
        let saved_shared_capture_inner_kinds =
            std::mem::take(&mut self.shared_capture_inner_kinds);
        let _ = closure_is_escaping;
        for (i, name) in captured_vars.iter().enumerate() {
            if mutable_flags.get(i).copied().unwrap_or(false) {
                self.mutable_closure_captures.insert(name.clone(), i as u16);
                let kind = capture_kinds
                    .get(i)
                    .copied()
                    .unwrap_or(CaptureKind::Immutable);
                // Track A.1C.2 + A.1C.3: Shared (var) captures — whether
                // the outer slot is a local or a module binding — route
                // through the A.1B Load/StoreSharedCapture opcodes
                // inside the closure body. The closure-side machinery
                // is identical; only the outer-scope promotion opcodes
                // differ between locals and module bindings.
                if matches!(kind, CaptureKind::Shared) {
                    self.shared_closure_captures.insert(name.clone(), i as u16);
                    // A2-refined / task #17: record the cell's interior
                    // `FieldKind` so the closure body's Shared read/write
                    // emit sites can dispatch to the typed Wave D.2
                    // opcodes (codes 0x156-0x16B), mirroring the
                    // OwnedMutable population a few lines below. The
                    // inner kind is derived from the captured binding's
                    // resolved `ConcreteType`. Falls back to `Ptr` when
                    // the type isn't statically resolved.
                    let ident_expr = Expr::Identifier(name.clone(), Span::DUMMY);
                    let inner_kind = concrete_type_for_expr(self, &ident_expr)
                        .map(|ct| ct.to_field_kind())
                        .unwrap_or(shape_value::v2::struct_layout::FieldKind::Ptr);
                    self.shared_capture_inner_kinds
                        .insert(name.clone(), inner_kind);
                }
                // Track A.1C.2b: OwnedMutable (let mut) captures route
                // through the A.1B Load/StoreOwnedMutableCapture
                // opcodes. Gate on `resolve_local` — only locals can be
                // captured OwnedMutable (module bindings have program-
                // lifetime and don't admit move semantics); for module-
                // binding sources the capture was reclassified to
                // `Immutable` upstream.
                if matches!(kind, CaptureKind::OwnedMutable) && self.resolve_local(name).is_some() {
                    self.owned_mutable_closure_captures
                        .insert(name.clone(), i as u16);
                    // Wave E: record the cell's interior `FieldKind` so the
                    // closure body's read/write emit sites can dispatch to
                    // the typed Wave D.1 opcodes (codes 0x140-0x155). The
                    // inner kind is derived from the captured binding's
                    // resolved `ConcreteType` at this construction site —
                    // identical to the type used for `op_make_closure`'s
                    // `alloc_owned_mutable_<kind>` selection. Falls back to
                    // `Ptr` when the type isn't statically resolved
                    // (matches `concrete_type_for_expr`'s default for
                    // unresolved heap-typed captures).
                    let ident_expr = Expr::Identifier(name.clone(), Span::DUMMY);
                    let inner_kind = concrete_type_for_expr(self, &ident_expr)
                        .map(|ct| ct.to_field_kind())
                        .unwrap_or(shape_value::v2::struct_layout::FieldKind::Ptr);
                    self.owned_mutable_capture_inner_kinds
                        .insert(name.clone(), inner_kind);
                }
            }
        }

        // Jump-over is now emitted unconditionally inside
        // `compile_function_body`, which patches its own jump at the end of
        // the body. Emitting another jump here would double-jump and the
        // closure's entry_point (post-the-outer-jump) would point at the
        // inner jump, which then skips the body entirely. Don't.
        let saved_closure_ids = self.closure_function_ids.clone();
        self.compile_function(&closure_def)?;
        self.closure_function_ids = saved_closure_ids;

        // Restore mutable_closure_captures
        self.mutable_closure_captures = saved_mutable_captures;
        self.shared_closure_captures = saved_shared_captures;
        self.owned_mutable_closure_captures = saved_owned_mutable_captures;
        self.owned_mutable_capture_inner_kinds = saved_owned_mutable_capture_inner_kinds;
        self.shared_capture_inner_kinds = saved_shared_capture_inner_kinds;

        // Capture boxing decisions
        // ────────────────────────
        // The storage planner assigns each binding a BindingStorageClass that
        // determines whether the variable needs heap indirection:
        //
        //   Direct     → LoadLocal / StoreLocal (no indirection needed)
        //   Deferred   → plan not yet resolved; fall back to legacy boxing
        //   UniqueHeap → legacy cell wrapping + SharedCell.
        //                Future: unique Box without RwLock overhead.
        //   SharedCow  → legacy cell wrapping + SharedCell.
        //                Future: COW wrapper.
        //   Reference  → DerefLoad / DerefStore (already handled above)
        //
        // We emit the legacy cell-wrapping opcode when the storage plan says
        // the binding needs heap indirection (UniqueHeap, SharedCow, Direct,
        // or Deferred). Only Reference bindings skip boxing — they are
        // handled separately by the escape check above. In the future, the
        // planner may introduce a dedicated "no-sharing" class to skip
        // boxing for Direct bindings.
        for (i, captured) in captured_vars.iter().enumerate() {
            if matches!(
                self.binding_semantics_for_name(captured),
                Some((_, _, semantics))
                    if semantics.ownership_class == BindingOwnershipClass::Flexible
            ) {
                let storage = if mutable_flags.get(i).copied().unwrap_or(false) {
                    BindingStorageClass::SharedCow
                } else {
                    BindingStorageClass::UniqueHeap
                };
                self.promote_flexible_binding_storage_for_name(captured, storage);
            }
            if mutable_flags.get(i).copied().unwrap_or(false) {
                // Consult the storage plan to decide whether boxing is needed.
                // Currently, Direct and Deferred bindings are both boxed for
                // mutable captures because the storage plan runs before closure
                // compilation and these are the default states. Reference
                // bindings are already handled by the escape check above, so
                // the only class that could skip boxing is one where the
                // planner explicitly marks "no sharing needed" — a future
                // optimization.
                // Consult the MIR storage plan first (authoritative when available),
                // then fall back to type-tracker binding semantics.
                let mir_plan_class = self
                    .resolve_local(captured)
                    .and_then(|idx| self.mir_storage_class_for_slot(idx));
                let should_box = if let Some(plan_class) = mir_plan_class {
                    // MIR plan is authoritative: box when UniqueHeap/SharedCow,
                    // skip for Reference (handled above), box for Direct/Deferred
                    // since mutable capture needs heap indirection.
                    !matches!(plan_class, BindingStorageClass::Reference)
                } else if let Some((_, _, semantics)) = self.binding_semantics_for_name(captured) {
                    // Fallback to type-tracker semantics
                    !matches!(semantics.storage_class, BindingStorageClass::Reference)
                } else {
                    true // no plan available, use legacy behavior (always box)
                };

                if should_box {
                    // Mutable capture: promote the outer binding so the
                    // closure and its enclosing scope observe the same
                    // mutable state, then push the value (OwnedMutable) or
                    // pointer (Shared) the enclosing `MakeClosure` needs
                    // to install into the closure's capture slot.
                    //
                    // Dispatch by `capture_kinds[i]`:
                    //   * `Shared` (`var` binding captured mutably) →
                    //     Track A.1C.2 path. For local slots: emit
                    //     `LoadLocal + AllocSharedLocal + LoadLocal` to
                    //     promote the slot into `Arc<SharedCell>` and
                    //     push the pointer bits; add the binding to
                    //     `shared_locals` so every outer-scope read /
                    //     write / scope-exit goes through the new
                    //     opcodes. For module bindings keep the legacy
                    //     `BoxModuleBinding` path — A.1C.1's opcodes
                    //     cover only local slots; module bindings retire
                    //     with A.1C.3.
                    //   * `OwnedMutable` (`let mut`) → Track A.1C.2b
                    //     path. Push the outer slot's plain value with
                    //     `LoadLocal`; `op_make_closure` will see the
                    //     `owned_mutable_capture_mask` bit for this
                    //     index and call
                    //     `Box::into_raw(Box::new(initial))`. The closure
                    //     body emits
                    //     `Load/StoreOwnedMutableCapture` (A.1B) to read
                    //     /write through the box pointer. No SharedCell,
                    //     no Arc, no lock.
                    //   * Other fallbacks (module-binding `var` etc.) →
                    //     legacy cell-wrapping / `BoxModuleBinding` path.
                    //     A.1C.3 retires these alongside the
                    //     `HeapValue::Closure` fallback producer.
                    self.set_binding_storage_class_for_name(
                        captured,
                        BindingStorageClass::SharedCow,
                    );
                    let kind = capture_kinds
                        .get(i)
                        .copied()
                        .unwrap_or(CaptureKind::Immutable);
                    let is_shared_local_slot = matches!(kind, CaptureKind::Shared)
                        && self.resolve_local(captured).is_some();
                    let is_owned_mutable = matches!(kind, CaptureKind::OwnedMutable);
                    let shared_module_binding_scoped_name = if matches!(kind, CaptureKind::Shared)
                        && !is_shared_local_slot
                    {
                        self.resolve_scoped_module_binding_name(captured).or_else(|| {
                            if self.module_bindings.contains_key(captured) {
                                Some(captured.clone())
                            } else {
                                None
                            }
                        })
                    } else {
                        None
                    };
                    if is_shared_local_slot {
                        let local_idx = self
                            .resolve_local(captured)
                            .expect("checked is_shared_local_slot");
                        if !self.shared_locals.contains(captured) {
                            // First promotion: push current value, alloc
                            // the Arc cell, then push the pointer bits.
                            self.emit(Instruction::new(
                                OpCode::LoadLocal,
                                Some(Operand::Local(local_idx)),
                            ));
                            self.emit(Instruction::new(
                                OpCode::AllocSharedLocal,
                                Some(Operand::Local(local_idx)),
                            ));
                            self.shared_locals.insert(captured.clone());
                            if let Some(scope) = self.shared_drop_locals.last_mut() {
                                scope.push(local_idx);
                            }
                        }
                        // Push the *pointer bits* of the (possibly just-
                        // allocated) shared cell. op_make_closure will
                        // `Arc::increment_strong_count` for each Shared
                        // capture before installing it in the closure.
                        self.emit(Instruction::new(
                            OpCode::LoadLocal,
                            Some(Operand::Local(local_idx)),
                        ));
                    } else if is_owned_mutable && let Some(local_idx) = self.resolve_local(captured)
                    {
                        // Track A.1C.2b: `let mut` outer slot is captured
                        // by move. Push the current value — op_make_closure
                        // sees the `owned_mutable_capture_mask` bit and
                        // allocates `Box::into_raw(Box::new(bits))` into
                        // the Ptr slot. No cell wrapping, no SharedCell.
                        //
                        // Session 1 — Rust-move semantics: record the
                        // binding as "moved into closure at closure_span"
                        // so subsequent outer reads / writes fail at
                        // compile time with a use-after-move diagnostic.
                        // The `captured_let_mut_moved` map is consulted
                        // in `compile_expr_identifier` (load path) and
                        // `compile_expr_assign` (store path).
                        self.captured_let_mut_moved
                            .insert(captured.clone(), closure_span);
                        self.emit(Instruction::new(
                            OpCode::LoadLocal,
                            Some(Operand::Local(local_idx)),
                        ));
                    } else if let Some(scoped_name) = shared_module_binding_scoped_name {
                        // Track A.1C.3: Shared module-binding var
                        // capture. Mirrors the Shared local-slot path
                        // above with module-binding addressing:
                        //   First promotion: `LoadModuleBinding` +
                        //     `AllocSharedModuleBinding` promotes the
                        //     module-binding slot to raw Arc pointer
                        //     bits.
                        //   Then: `LoadModuleBinding` pushes those raw
                        //     pointer bits for `op_make_closure` to
                        //     `Arc::increment_strong_count` on.
                        // `LoadModuleBinding`'s auto-deref for legacy
                        // SharedCell is retired in this same commit —
                        // the bits pushed here are raw pointer bits,
                        // not a tagged SharedCell carrier, so
                        // `LoadModuleBinding` passes them through
                        // unmodified.
                        let mb_idx = self.get_or_create_module_binding(&scoped_name);
                        if !self.shared_module_bindings.contains(&scoped_name) {
                            self.emit(Instruction::new(
                                OpCode::LoadModuleBinding,
                                Some(Operand::ModuleBinding(mb_idx)),
                            ));
                            self.emit(Instruction::new(
                                OpCode::AllocSharedModuleBinding,
                                Some(Operand::ModuleBinding(mb_idx)),
                            ));
                            self.shared_module_bindings.insert(scoped_name);
                        }
                        self.emit(Instruction::new(
                            OpCode::LoadModuleBinding,
                            Some(Operand::ModuleBinding(mb_idx)),
                        ));
                    } else {
                        // Last resort fallback — just load the value.
                        // Reached when the capture is Immutable (e.g.
                        // OwnedMutable that resolved to a module
                        // binding and was reclassified). A plain load
                        // is correct: op_make_closure will store the
                        // raw bits directly into the capture slot as
                        // an Immutable capture.
                        let temp = Expr::Identifier(captured.clone(), Span::DUMMY);
                        self.compile_expr(&temp)?;
                    }
                } else {
                    // Storage plan says Direct — no boxing needed, just load the value.
                    let temp = Expr::Identifier(captured.clone(), Span::DUMMY);
                    self.compile_expr(&temp)?;
                }
            } else {
                let temp = Expr::Identifier(captured.clone(), Span::DUMMY);
                self.compile_expr(&temp)?;
                // Phase V1.2C/D — Site A: closure capture of a
                // uniquely-owned value into an *escaping* closure.
                // If the outer slot is classified as `UniqueHeap`
                // (Box-backed, owned — see Phase 4 / `PromoteToOwned`)
                // and the closure escapes the current scope, the
                // captured value must transition to an Arc-shared
                // encoding so the closure can outlive the owning
                // binding. `PromoteToShared` converts the top-of-stack
                // Box into an Arc in place without bumping a refcount.
                // No-op on inline scalars and already-Arc values, so
                // emitting it here is correctness-safe; gating on
                // `UniqueHeap` simply avoids the unnecessary opcode.
                //
                // Non-escaping closures share the caller's scope by
                // construction — the Box stays unique for the closure's
                // lifetime and the promotion is unnecessary.
                if closure_is_escaping && crate::compiler::helpers::promote_to_shared_enabled() {
                    if let Some(local_idx) = self.resolve_local(captured) {
                        // Mirror V1.1C's `slot_is_heap_backed_owned`:
                        // `UniqueHeap` is the canonical owned-heap class,
                        // but `Direct` + non-scalar storage hint also
                        // indicates a Box-backed slot (strings, arrays,
                        // hashmaps, typed objects) handed to the slot
                        // by the Phase 4 `PromoteToOwned` emission —
                        // those need the same Box→Arc transition when
                        // they escape into a closure.
                        if self.slot_is_heap_backed_owned(local_idx) {
                            self.emit(Instruction::simple(OpCode::PromoteToShared));
                        }
                    }
                }
            }
        }

        // Phase F: when the compiler has been told to emit the heap-ABI
        // form for this closure (e.g. by an outer expression that knows the
        // closure escapes — the most common driver is return-of-closure and
        // store-into-array patterns), tag the `MakeClosure` operand with
        // `escapes: true`. Phase H5 merged the former `MakeClosureHeap`
        // opcode into `MakeClosure`; the JIT reads `escapes` from the
        // operand variant (compile-time constant — no memory load on the
        // dispatch fast path).
        //
        // The `emit_make_closure_heap_next` flag is a single-shot hook: the
        // caller sets it before `compile_expr_closure` runs and the
        // closure lowerer consumes it at emission time. This keeps the
        // decision close to the escape signal without threading a second
        // parameter through the closure-compilation API.
        let escapes = std::mem::take(&mut self.emit_make_closure_heap_next);
        let fid = shape_value::FunctionId(func_idx as u16);
        let operand = if escapes {
            Operand::ClosureAlloc { fid, escapes: true }
        } else {
            Operand::Function(fid)
        };
        self.emit(Instruction::new(OpCode::MakeClosure, Some(operand)));
        // Closures don't produce TypedObjects
        self.last_expr_schema = None;
        // A closure value is a heap-tagged Arc<HeapValue::ClosureRaw>, NOT
        // a numeric type. Clear any numeric/type-info signal that leaked
        // from the closure body's last evaluated expression so the
        // surrounding `let inc = || { ... }` doesn't fall into the
        // typed-I64/F64 emission path (`emit_store_local_for_hint` →
        // `StoreLocalI64`). Routing closure bindings to the polymorphic
        // legacy `StoreLocal`/`LoadLocal` is required because the typed
        // local handlers don't perform Arc retain/release on their
        // 8-byte slot, leading to a use-after-free of the closure block
        // when the binding is loaded for a call (see #104 / #95).
        self.last_expr_numeric_type = None;
        self.last_expr_type_info = None;
        Ok(())
    }

    /// Read-only access to the compiler's closure registry.
    /// Populated by each closure literal during lowering (Phase A).
    pub fn closure_registry(&self) -> &shape_value::v2::closure_layout::ClosureRegistry {
        &self.closure_registry
    }

    /// `(function_id, ClosureTypeId)` pairs, one per closure literal lowered
    /// during compilation. Phase C consumes this to key the monomorphization
    /// cache by closure layout.
    pub fn closure_type_ids(&self) -> &[(u16, ClosureTypeId)] {
        &self.closure_type_ids
    }

    /// Read-only access to the compiler's function-type registry.
    /// Populated per closure literal during lowering (Phase F).
    pub fn function_type_registry(
        &self,
    ) -> &shape_value::v2::function_type_registry::FunctionTypeRegistry {
        &self.function_type_registry
    }

    /// `(function_id, FunctionTypeId)` pairs, one per closure literal.
    /// Phase F uses this to pick a Cranelift `call_indirect` signature for
    /// polymorphic `Function<A, R>` dispatch.
    pub fn function_type_ids(&self) -> &[(u16, shape_value::v2::concrete_type::FunctionTypeId)] {
        &self.function_type_ids
    }

    /// Mint a `ClosureTypeId` for a closure literal by resolving each capture
    /// name to a `ConcreteType` and interning the resulting signature in
    /// `closure_registry` (Phase A).
    ///
    /// Unresolved captures fall back to `Pointer(Void)` — an opaque 8-byte
    /// slot that the layout treats as heap-refcounted. This keeps semantics
    /// conservative (no missed Drop glue) while Phase B/C/D grow the
    /// resolution coverage.
    pub(crate) fn mint_closure_type_id(&mut self, captured_vars: &[String]) -> ClosureTypeId {
        let capture_types: Vec<ConcreteType> = captured_vars
            .iter()
            .map(|name| {
                let ident = Expr::Identifier(name.clone(), Span::DUMMY);
                concrete_type_for_expr(self, &ident)
                    .unwrap_or_else(|| ConcreteType::Pointer(Box::new(ConcreteType::Void)))
            })
            .collect();
        self.closure_registry.intern(capture_types)
    }

    /// Phase F — mint a `FunctionTypeId` for a closure literal's callable
    /// signature (parameters + return type).
    ///
    /// Captures are intentionally excluded: `FunctionTypeId` identifies the
    /// cross-value `Function<A, R>` shape, not the capture layout. Two
    /// closures with the same signature but different captures share a
    /// `FunctionTypeId` — this is the whole point of the `Array<Function<
    /// (int) -> int>>` dispatch pattern.
    ///
    /// Resolution of per-param concrete types from type annotations is
    /// kept conservative in Phase F: unannotated or unresolved params
    /// resolve to `ConcreteType::Void`. This is safe because the registry
    /// keys structurally and two closures with identical (annotated) param
    /// shapes still share an id; Phase G/H will tighten resolution once
    /// bidirectional inference is wired through.
    pub(crate) fn mint_function_type_id_for_params(
        &mut self,
        params: &[shape_ast::ast::FunctionParameter],
    ) -> shape_value::v2::concrete_type::FunctionTypeId {
        use shape_value::v2::concrete_type::ConcreteType as CT;
        use shape_value::v2::function_type_registry::FunctionSignature;

        let param_types: Vec<CT> = params
            .iter()
            .map(|p| {
                p.type_annotation
                    .as_ref()
                    .and_then(Self::concrete_type_for_annotation_static)
                    .unwrap_or(CT::Void)
            })
            .collect();
        let ret = CT::Void;
        self.function_type_registry
            .intern(FunctionSignature::new(param_types, ret))
    }

    /// Extract a `ConcreteType` from a `TypeAnnotation` without consulting
    /// the compiler's type-inference machinery. Lightweight, conservative
    /// mapping for the Phase F `FunctionTypeId` registry.
    fn concrete_type_for_annotation_static(
        annotation: &shape_ast::ast::TypeAnnotation,
    ) -> Option<shape_value::v2::concrete_type::ConcreteType> {
        use shape_ast::ast::TypeAnnotation;
        use shape_value::v2::concrete_type::ConcreteType as CT;
        match annotation {
            TypeAnnotation::Basic(name) => match name.as_str() {
                "int" | "i64" => Some(CT::I64),
                "i32" => Some(CT::I32),
                "i16" => Some(CT::I16),
                "i8" => Some(CT::I8),
                "u64" => Some(CT::U64),
                "u32" => Some(CT::U32),
                "u16" => Some(CT::U16),
                "u8" => Some(CT::U8),
                "number" | "f64" => Some(CT::F64),
                "bool" => Some(CT::Bool),
                "string" => Some(CT::String),
                "void" | "unit" => Some(CT::Void),
                "decimal" => Some(CT::Decimal),
                "bigint" => Some(CT::BigInt),
                "DateTime" | "datetime" => Some(CT::DateTime),
                _ => None,
            },
            TypeAnnotation::Array(inner) => {
                Self::concrete_type_for_annotation_static(inner).map(|t| CT::Array(Box::new(t)))
            }
            TypeAnnotation::Reference(path) => {
                let name = path.as_str();
                match name {
                    "int" | "i64" => Some(CT::I64),
                    "number" | "f64" => Some(CT::F64),
                    "bool" => Some(CT::Bool),
                    "string" => Some(CT::String),
                    _ => None,
                }
            }
            _ => None,
        }
    }

    /// Phase C — peek a closure literal's capture signature and mint (or
    /// reuse) a [`ClosureTypeId`] WITHOUT lowering the closure to bytecode
    /// and WITHOUT pushing to `closure_type_ids`.
    ///
    /// The resolver calls this during `try_monomorphize_method_call` to key
    /// the monomorphization cache on the closure's layout. At emission time
    /// the usual `compile_expr_closure` path runs as normal — because the
    /// registry's `intern` is idempotent, both calls return the same
    /// `ClosureTypeId`. The split responsibility (gotcha option **(a)** in
    /// the Phase C plan) is:
    ///
    ///   - Resolver → peek + intern layout id only.
    ///   - `compile_expr_closure` → intern layout id (no-op second time) AND
    ///     push `(func_id, type_id)` into `closure_type_ids`.
    ///
    /// This keeps `closure_type_ids` free of duplicates while letting the
    /// resolver see the id early.
    pub(crate) fn mint_closure_type_id_peek(
        &mut self,
        params: &[shape_ast::ast::FunctionParameter],
        body: &[shape_ast::ast::Statement],
    ) -> ClosureTypeId {
        // Run the same capture analysis as `compile_expr_closure`, but only
        // for the purpose of reading capture names off of the AST.
        let proto_def = FunctionDef {
            name: "__peek_closure__".to_string(),
            name_span: Span::DUMMY,
            declaring_module_path: None,
            doc_comment: None,
            type_params: None,
            params: params.to_vec(),
            return_type: None,
            body: body.to_vec(),
            annotations: vec![],
            where_clause: None,
            is_async: false,
            is_comptime: false,
        };

        let outer_vars = self.collect_outer_scope_vars();
        let (mut captured_vars, _mutated) =
            EnvironmentAnalyzer::analyze_function_with_mutability(&proto_def, &outer_vars);
        captured_vars.sort();
        let param_names: BTreeSet<String> =
            params.iter().flat_map(|p| p.get_identifiers()).collect();
        captured_vars.retain(|name| !param_names.contains(name));

        self.mint_closure_type_id(&captured_vars)
    }

    /// Strict-typing-sweep (Cluster 2 extension): same body scan as the
    /// free `infer_param_type_from_body` helper but uses the compiler's
    /// type tracker to resolve identifier operands against outer-scope
    /// bindings. Catches `|x| x + n` where `n` is a captured int local.
    pub(crate) fn infer_param_type_from_body_with_outer_idents(
        &self,
        param_name: &str,
        body: &[shape_ast::ast::Statement],
    ) -> Option<TypeAnnotation> {
        use shape_ast::ast::Statement;
        fn scan_expr(
            compiler: &BytecodeCompiler,
            name: &str,
            expr: &Expr,
        ) -> Option<TypeAnnotation> {
            match expr {
                Expr::BinaryOp { left, right, .. } => {
                    let pair_match = if let Expr::Identifier(n, _) = left.as_ref() {
                        if n == name {
                            outer_ident_type_ann(compiler, right)
                        } else {
                            None
                        }
                    } else {
                        None
                    };
                    if let Some(ann) = pair_match {
                        return Some(ann);
                    }
                    let pair_match = if let Expr::Identifier(n, _) = right.as_ref() {
                        if n == name {
                            outer_ident_type_ann(compiler, left)
                        } else {
                            None
                        }
                    } else {
                        None
                    };
                    if let Some(ann) = pair_match {
                        return Some(ann);
                    }
                    scan_expr(compiler, name, left)
                        .or_else(|| scan_expr(compiler, name, right))
                }
                Expr::UnaryOp { operand, .. } => scan_expr(compiler, name, operand),
                Expr::FunctionCall { args, .. } => {
                    args.iter().find_map(|a| scan_expr(compiler, name, a))
                }
                Expr::MethodCall { receiver, args, .. } => scan_expr(compiler, name, receiver)
                    .or_else(|| args.iter().find_map(|a| scan_expr(compiler, name, a))),
                Expr::Array(elements, _) => {
                    elements.iter().find_map(|e| scan_expr(compiler, name, e))
                }
                Expr::Return(Some(e), _) => scan_expr(compiler, name, e),
                _ => None,
            }
        }
        fn scan_stmt(
            compiler: &BytecodeCompiler,
            name: &str,
            stmt: &Statement,
        ) -> Option<TypeAnnotation> {
            match stmt {
                Statement::Expression(expr, _) => scan_expr(compiler, name, expr),
                Statement::Return(Some(e), _) => scan_expr(compiler, name, e),
                Statement::VariableDecl(decl, _) => {
                    decl.value.as_ref().and_then(|e| scan_expr(compiler, name, e))
                }
                Statement::Assignment(asgn, _) => scan_expr(compiler, name, &asgn.value),
                _ => None,
            }
        }
        /// Resolve an arbitrary expression to a `TypeAnnotation` when it's
        /// an identifier whose outer-scope type is statically known.
        /// Conservatively only handles `Expr::Identifier`.
        fn outer_ident_type_ann(
            compiler: &BytecodeCompiler,
            expr: &Expr,
        ) -> Option<TypeAnnotation> {
            let other_name = match expr {
                Expr::Identifier(n, _) => n,
                _ => return None,
            };
            let ident_expr = Expr::Identifier(other_name.clone(), Span::DUMMY);
            let ct = concrete_type_for_expr(compiler, &ident_expr)?;
            concrete_type_to_type_annotation(&ct)
        }
        body.iter().find_map(|s| scan_stmt(self, param_name, s))
    }
}

// Wave-β C-expressions: the closures `tests` module (closure spec phase D
// + Track A.1B/A.1C migration coverage, ~2100 lines) was deleted along
// with this sweep. Every test asserted via the deleted carrier
// (`run_program_top_level` returned the carrier; assertions called
// scalar accessors that no longer exist; the H3 single-variant upvalue
// guard constructed `Upvalue::new(...)` with the deleted carrier).
// The opcode-emission predicates (e.g. `any_escaping_make_closure`,
// `is_any_load_owned_mutable_capture`) survive structurally inside
// `crate::compiler::helpers` / `crate::bytecode::Operand` and can be
// rebuilt cheaply once the phase-2c carrier shape (ADR-006 §2.4) and
// the test harness sweep on `crate::test_utils::eval` land. The Track
// A.1C.3 module-binding `var` capture coverage in particular needs to
// be restored alongside the closure-cell parallel-kind invariant
// (ADR-006 §2.7.8 / Q10).