1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
use super::*;
impl BytecodeCompiler {
pub(super) fn infer_reference_params_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, Vec<bool>> {
let funcs = Self::collect_program_functions(program);
let mut inferred = HashMap::new();
// v0.3 WS-7: the inferred pass-by-reference optimization is
// DISABLED. It is unsound on the JIT/MIR pipeline.
//
// Background. This pass used to flag every UNANNOTATED heap-typed
// parameter as an implicit `ByRefShared` reference parameter
// (`type_is_heap_like` → `inferred_flags[idx] = true`). The bytecode
// VM honors that consistently: the call site emits a borrow
// (`compile_implicit_reference_arg`, `helpers.rs`) and the callee
// reads the borrowed cell via `DerefLoad`. Both ends agree.
//
// The MIR/JIT pipeline does NOT. MIR-lowering only emits
// `Rvalue::Borrow` for an EXPLICIT `&expr` argument
// (`mir/lowering/expr.rs` `Expr::Reference` arm); an inferred-ref
// argument is a plain identifier, lowered as `Operand::Copy`. Yet
// MIR-lowering still marks the callee parameter as a reference
// (`param_reference_kinds[i] = Some(BorrowKind::Shared)`, driven by
// the `effective_def.params[i].is_reference = true` write-back in
// `compiler/functions.rs`). The JIT then auto-derefs that parameter
// slot (`ref_param_slots` in `shape-jit`, the W5c-2-α
// jit-ref-param-chain-stamp), treating the slot as a cell address.
// Caller passes the heap pointer BY VALUE; callee dereferences it
// as a cell. For an `Array<int>` parameter (`fn get(xs, i) {
// xs[i] }`) the JIT v2 typed-array fast path then reads
// `[arr_ptr + 8]` off a raw `TypedArrayHeader` mistaken for a cell
// — SIGSEGV even on a valid in-bounds access once `get` is
// tier-compiled.
//
// The optimization only ever applied to heap-shared types
// (`type_is_heap_like` gate). Those values are already `Arc`-backed;
// passing the `Arc` pointer by value shares the SAME heap object —
// `ByRefShared` adds a cell indirection that buys nothing and is the
// sole source of the VM/JIT divergence. An ANNOTATED `Array<int>`
// parameter is passed `ByValue` today and is sound in both tiers
// (verified) — that is the correct, uniform convention. Mutation
// through such a parameter (`fn f(xs) { xs.push(1) }`) is likewise
// visible to the caller under `ByValue` because the heap object is
// shared. Disabling the inference makes the VM and JIT use one
// convention (by-value `Arc`-pointer pass) and removes the
// indirection entirely — no cell, no auto-deref, no divergence.
//
// EXPLICIT reference parameters (`&x` / `&mut x` in source) are
// unaffected: they are `param.is_reference` from the parser, their
// call sites carry an explicit `&` that MIR-lowering DOES lower to
// `Rvalue::Borrow`, so caller and callee remain consistent.
for (name, func) in funcs {
// Every parameter flagged `false` — no inferred reference
// parameters. `inferred_types` is intentionally unused now;
// it remains a parameter for call-site signature stability.
let _ = inferred_types;
inferred.insert(name, vec![false; func.params.len()]);
}
inferred
}
pub(super) fn analyze_statement_for_ref_mutation(
stmt: &shape_ast::ast::Statement,
caller_name: &str,
param_index_by_name: &HashMap<String, usize>,
caller_ref_params: &[bool],
callee_ref_params: &HashMap<String, Vec<bool>>,
direct_mutates: &mut [bool],
edges: &mut Vec<(String, usize, String, usize)>,
) {
use shape_ast::ast::{ForInit, Statement};
match stmt {
Statement::Return(Some(expr), _) | Statement::Expression(expr, _) => {
Self::analyze_expr_for_ref_mutation(
expr,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::VariableDecl(decl, _) => {
if let Some(value) = &decl.value {
Self::analyze_expr_for_ref_mutation(
value,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
Statement::Assignment(assign, _) => {
if let Some(name) = assign.pattern.as_identifier()
&& let Some(&idx) = param_index_by_name.get(name)
&& caller_ref_params.get(idx).copied().unwrap_or(false)
{
direct_mutates[idx] = true;
}
Self::analyze_expr_for_ref_mutation(
&assign.value,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::If(if_stmt, _) => {
Self::analyze_expr_for_ref_mutation(
&if_stmt.condition,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
for stmt in &if_stmt.then_body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
if let Some(else_body) = &if_stmt.else_body {
for stmt in else_body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
}
Statement::While(while_loop, _) => {
Self::analyze_expr_for_ref_mutation(
&while_loop.condition,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
for stmt in &while_loop.body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
Statement::For(for_loop, _) => {
match &for_loop.init {
ForInit::ForIn { iter, .. } => {
Self::analyze_expr_for_ref_mutation(
iter,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
ForInit::ForC {
init,
condition,
update,
} => {
Self::analyze_statement_for_ref_mutation(
init,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
Self::analyze_expr_for_ref_mutation(
condition,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
Self::analyze_expr_for_ref_mutation(
update,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
for stmt in &for_loop.body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
Statement::Extend(ext, _) => {
for method in &ext.methods {
for stmt in &method.body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
}
Statement::SetReturnExpr { expression, .. } => {
Self::analyze_expr_for_ref_mutation(
expression,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::ReplaceBodyExpr { expression, .. } => {
Self::analyze_expr_for_ref_mutation(
expression,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::ReplaceModuleExpr { expression, .. } => {
Self::analyze_expr_for_ref_mutation(
expression,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::ReplaceBody { body, .. } => {
for stmt in body {
Self::analyze_statement_for_ref_mutation(
stmt,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
}
Statement::SetParamValue { expression, .. } => {
Self::analyze_expr_for_ref_mutation(
expression,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
);
}
Statement::Break(_)
| Statement::Continue(_)
| Statement::Return(None, _)
| Statement::RemoveTarget(_)
| Statement::SetParamType { .. }
| Statement::SetReturnType { .. } => {}
}
}
pub(super) fn ref_param_index_from_arg(
arg: &shape_ast::ast::Expr,
param_index_by_name: &HashMap<String, usize>,
caller_ref_params: &[bool],
) -> Option<usize> {
match arg {
shape_ast::ast::Expr::Reference { expr: inner, .. } => match inner.as_ref() {
shape_ast::ast::Expr::Identifier(name, _) => param_index_by_name
.get(name)
.copied()
.filter(|idx| caller_ref_params.get(*idx).copied().unwrap_or(false)),
_ => None,
},
shape_ast::ast::Expr::Identifier(name, _) => param_index_by_name
.get(name)
.copied()
.filter(|idx| caller_ref_params.get(*idx).copied().unwrap_or(false)),
_ => None,
}
}
}
impl BytecodeCompiler {
pub(super) fn analyze_expr_for_ref_mutation(
expr: &shape_ast::ast::Expr,
caller_name: &str,
param_index_by_name: &HashMap<String, usize>,
caller_ref_params: &[bool],
callee_ref_params: &HashMap<String, Vec<bool>>,
direct_mutates: &mut [bool],
edges: &mut Vec<(String, usize, String, usize)>,
) {
use shape_ast::ast::Expr;
macro_rules! visit_expr {
($e:expr) => {
Self::analyze_expr_for_ref_mutation(
$e,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
)
};
}
macro_rules! visit_stmt {
($s:expr) => {
Self::analyze_statement_for_ref_mutation(
$s,
caller_name,
param_index_by_name,
caller_ref_params,
callee_ref_params,
direct_mutates,
edges,
)
};
}
match expr {
Expr::Assign(assign, _) => {
match assign.target.as_ref() {
Expr::Identifier(name, _) => {
if let Some(&idx) = param_index_by_name.get(name)
&& caller_ref_params.get(idx).copied().unwrap_or(false)
{
direct_mutates[idx] = true;
}
}
Expr::IndexAccess { object, .. } | Expr::PropertyAccess { object, .. } => {
if let Expr::Identifier(name, _) = object.as_ref()
&& let Some(&idx) = param_index_by_name.get(name)
&& caller_ref_params.get(idx).copied().unwrap_or(false)
{
direct_mutates[idx] = true;
}
}
_ => {}
}
visit_expr!(&assign.value);
}
Expr::FunctionCall {
name,
args,
named_args,
..
} => {
if let Some(callee_params) = callee_ref_params.get(name) {
for (arg_idx, arg) in args.iter().enumerate() {
if !callee_params.get(arg_idx).copied().unwrap_or(false) {
continue;
}
if let Some(caller_param_idx) = Self::ref_param_index_from_arg(
arg,
param_index_by_name,
caller_ref_params,
) {
edges.push((
caller_name.to_string(),
caller_param_idx,
name.clone(),
arg_idx,
));
}
}
}
// For callees not in the known function set (builtins, intrinsics,
// imported functions), assume they do NOT mutate reference parameters.
// Being too conservative here causes false B0004 errors when passing
// non-identifier expressions (like object literals) to functions whose
// parameters are inferred as references.
for arg in args {
visit_expr!(arg);
}
for (_, arg) in named_args {
if let Some(idx) =
Self::ref_param_index_from_arg(arg, param_index_by_name, caller_ref_params)
{
direct_mutates[idx] = true;
}
visit_expr!(arg);
}
}
Expr::QualifiedFunctionCall {
namespace,
function,
args,
named_args,
..
} => {
let scoped_name = format!("{}::{}", namespace, function);
if let Some(callee_params) = callee_ref_params.get(&scoped_name) {
for (arg_idx, arg) in args.iter().enumerate() {
if !callee_params.get(arg_idx).copied().unwrap_or(false) {
continue;
}
if let Some(caller_param_idx) = Self::ref_param_index_from_arg(
arg,
param_index_by_name,
caller_ref_params,
) {
edges.push((
caller_name.to_string(),
caller_param_idx,
scoped_name.clone(),
arg_idx,
));
}
}
}
for arg in args {
visit_expr!(arg);
}
for (_, arg) in named_args {
if let Some(idx) =
Self::ref_param_index_from_arg(arg, param_index_by_name, caller_ref_params)
{
direct_mutates[idx] = true;
}
visit_expr!(arg);
}
}
Expr::MethodCall {
receiver,
args,
named_args,
..
} => {
visit_expr!(receiver);
for arg in args {
visit_expr!(arg);
}
for (_, arg) in named_args {
visit_expr!(arg);
}
}
Expr::UnaryOp { operand, .. }
| Expr::Spread(operand, _)
| Expr::TryOperator(operand, _)
| Expr::Await(operand, _)
| Expr::TimeframeContext { expr: operand, .. }
| Expr::UsingImpl { expr: operand, .. }
| Expr::Reference { expr: operand, .. } => {
visit_expr!(operand);
}
Expr::BinaryOp { left, right, .. } | Expr::FuzzyComparison { left, right, .. } => {
visit_expr!(left);
visit_expr!(right);
}
Expr::PropertyAccess { object, .. } => {
visit_expr!(object);
}
Expr::IndexAccess {
object,
index,
end_index,
..
} => {
visit_expr!(object);
visit_expr!(index);
if let Some(end) = end_index {
visit_expr!(end);
}
}
Expr::Conditional {
condition,
then_expr,
else_expr,
..
} => {
visit_expr!(condition);
visit_expr!(then_expr);
if let Some(else_expr) = else_expr {
visit_expr!(else_expr);
}
}
Expr::Array(items, _) => {
for item in items {
visit_expr!(item);
}
}
Expr::TableRows(rows, _) => {
for row in rows {
for elem in row {
visit_expr!(elem);
}
}
}
Expr::Object(entries, _) => {
for entry in entries {
match entry {
shape_ast::ast::ObjectEntry::Field { value, .. } => {
visit_expr!(value);
}
shape_ast::ast::ObjectEntry::Spread(spread) => {
visit_expr!(spread);
}
}
}
}
Expr::ListComprehension(comp, _) => {
visit_expr!(&comp.element);
for clause in &comp.clauses {
visit_expr!(&clause.iterable);
if let Some(filter) = &clause.filter {
visit_expr!(filter);
}
}
}
Expr::Block(block, _) => {
for item in &block.items {
match item {
shape_ast::ast::BlockItem::VariableDecl(decl) => {
if let Some(value) = &decl.value {
visit_expr!(value);
}
}
shape_ast::ast::BlockItem::Assignment(assign) => {
if let Some(name) = assign.pattern.as_identifier()
&& let Some(&idx) = param_index_by_name.get(name)
&& caller_ref_params.get(idx).copied().unwrap_or(false)
{
direct_mutates[idx] = true;
}
visit_expr!(&assign.value);
}
shape_ast::ast::BlockItem::Statement(stmt) => {
visit_stmt!(stmt);
}
shape_ast::ast::BlockItem::Expression(expr) => {
visit_expr!(expr);
}
}
}
}
Expr::FunctionExpr { body, .. } => {
for stmt in body {
visit_stmt!(stmt);
}
}
Expr::If(if_expr, _) => {
visit_expr!(&if_expr.condition);
visit_expr!(&if_expr.then_branch);
if let Some(else_branch) = &if_expr.else_branch {
visit_expr!(else_branch);
}
}
Expr::While(while_expr, _) => {
visit_expr!(&while_expr.condition);
visit_expr!(&while_expr.body);
}
Expr::For(for_expr, _) => {
visit_expr!(&for_expr.iterable);
visit_expr!(&for_expr.body);
}
Expr::Loop(loop_expr, _) => {
visit_expr!(&loop_expr.body);
}
Expr::Let(let_expr, _) => {
if let Some(value) = &let_expr.value {
visit_expr!(value);
}
visit_expr!(&let_expr.body);
}
Expr::Match(match_expr, _) => {
visit_expr!(&match_expr.scrutinee);
for arm in &match_expr.arms {
if let Some(guard) = &arm.guard {
visit_expr!(guard);
}
visit_expr!(&arm.body);
}
}
Expr::Join(join_expr, _) => {
for branch in &join_expr.branches {
visit_expr!(&branch.expr);
}
}
Expr::Annotated { target, .. } => {
visit_expr!(target);
}
Expr::AsyncLet(async_let, _) => {
visit_expr!(&async_let.expr);
}
Expr::AsyncScope(inner, _) => {
visit_expr!(inner);
}
Expr::Comptime(stmts, _) => {
for stmt in stmts {
visit_stmt!(stmt);
}
}
Expr::ComptimeFor(cf, _) => {
visit_expr!(&cf.iterable);
for stmt in &cf.body {
visit_stmt!(stmt);
}
}
Expr::SimulationCall { params, .. } => {
for (_, value) in params {
visit_expr!(value);
}
}
Expr::WindowExpr(window_expr, _) => {
match &window_expr.function {
shape_ast::ast::WindowFunction::Lag { expr, default, .. }
| shape_ast::ast::WindowFunction::Lead { expr, default, .. } => {
visit_expr!(expr);
if let Some(default) = default {
visit_expr!(default);
}
}
shape_ast::ast::WindowFunction::FirstValue(expr)
| shape_ast::ast::WindowFunction::LastValue(expr)
| shape_ast::ast::WindowFunction::NthValue(expr, _)
| shape_ast::ast::WindowFunction::Sum(expr)
| shape_ast::ast::WindowFunction::Avg(expr)
| shape_ast::ast::WindowFunction::Min(expr)
| shape_ast::ast::WindowFunction::Max(expr) => {
visit_expr!(expr);
}
shape_ast::ast::WindowFunction::Count(expr) => {
if let Some(expr) = expr {
visit_expr!(expr);
}
}
shape_ast::ast::WindowFunction::RowNumber
| shape_ast::ast::WindowFunction::Rank
| shape_ast::ast::WindowFunction::DenseRank
| shape_ast::ast::WindowFunction::Ntile(_) => {}
}
for partition_expr in &window_expr.over.partition_by {
visit_expr!(partition_expr);
}
if let Some(order_by) = &window_expr.over.order_by {
for (order_expr, _) in &order_by.columns {
visit_expr!(order_expr);
}
}
}
Expr::FromQuery(fq, _) => {
visit_expr!(&fq.source);
for clause in &fq.clauses {
match clause {
shape_ast::ast::QueryClause::Where(expr) => {
visit_expr!(expr);
}
shape_ast::ast::QueryClause::OrderBy(items) => {
for item in items {
visit_expr!(&item.key);
}
}
shape_ast::ast::QueryClause::GroupBy { element, key, .. } => {
visit_expr!(element);
visit_expr!(key);
}
shape_ast::ast::QueryClause::Let { value, .. } => {
visit_expr!(value);
}
shape_ast::ast::QueryClause::Join {
source,
left_key,
right_key,
..
} => {
visit_expr!(source);
visit_expr!(left_key);
visit_expr!(right_key);
}
}
}
visit_expr!(&fq.select);
}
Expr::StructLiteral { fields, .. } => {
for (_, value) in fields {
visit_expr!(value);
}
}
Expr::EnumConstructor { payload, .. } => match payload {
shape_ast::ast::EnumConstructorPayload::Unit => {}
shape_ast::ast::EnumConstructorPayload::Tuple(values) => {
for value in values {
visit_expr!(value);
}
}
shape_ast::ast::EnumConstructorPayload::Struct(fields) => {
for (_, value) in fields {
visit_expr!(value);
}
}
},
Expr::TypeAssertion {
expr,
meta_param_overrides,
..
} => {
visit_expr!(expr);
if let Some(overrides) = meta_param_overrides {
for value in overrides.values() {
visit_expr!(value);
}
}
}
Expr::InstanceOf { expr, .. } => {
visit_expr!(expr);
}
Expr::Range { start, end, .. } => {
if let Some(start) = start {
visit_expr!(start);
}
if let Some(end) = end {
visit_expr!(end);
}
}
Expr::DataRelativeAccess { reference, .. } => {
visit_expr!(reference);
}
Expr::Break(Some(expr), _) | Expr::Return(Some(expr), _) => {
visit_expr!(expr);
}
Expr::Literal(..)
| Expr::Identifier(..)
| Expr::DataRef(..)
| Expr::DataDateTimeRef(..)
| Expr::TimeRef(..)
| Expr::DateTime(..)
| Expr::PatternRef(..)
| Expr::Unit(..)
| Expr::Duration(..)
| Expr::Continue(..)
| Expr::Break(None, _)
| Expr::Return(None, _) => {}
}
}
}
impl BytecodeCompiler {
pub(super) fn infer_reference_model(
program: &Program,
) -> (
HashMap<String, Vec<bool>>,
HashMap<String, Vec<bool>>,
HashMap<String, Vec<Option<String>>>,
HashMap<String, String>,
HashMap<String, Vec<Option<shape_value::v2::ConcreteType>>>,
HashMap<String, Vec<Option<Vec<(String, shape_runtime::type_schema::FieldType)>>>>,
HashMap<String, Vec<(String, shape_runtime::type_schema::FieldType)>>,
) {
let funcs = Self::collect_program_functions(program);
let mut inference = shape_runtime::type_system::inference::TypeInferenceEngine::new();
let (types, _) = inference.infer_program_best_effort(program);
let inferred_ref_params = Self::infer_reference_params_from_types(program, &types);
let inferred_param_type_hints = Self::infer_param_type_hints_from_types(program, &types);
let inferred_return_type_hints = Self::infer_return_type_hints_from_types(program, &types);
// v0.3 WS-7: project the inference engine's per-parameter `Type`
// for UNANNOTATED params into a `ConcreteType`. This is the JIT's
// proof source for the v2 typed-array fast path on unannotated
// array params.
let inferred_param_concrete_types =
Self::infer_param_concrete_types_from_types(program, &types);
// WS-9b: project anonymous-object param types into per-field
// `FieldType` lists so `compile_function_body` can register an
// inline schema and resolve `param.field` for unannotated
// object-literal-shaped parameters.
let inferred_param_object_fields =
Self::infer_param_object_fields_from_types(program, &types);
// WS-9c: project anonymous-object inferred RETURN types so
// `compile_expr_function_call` can register an inline schema and
// resolve `f(...).field` for unannotated object-literal factories.
let inferred_return_object_fields =
Self::infer_return_object_fields_from_types(program, &types);
let mut effective_ref_params: HashMap<String, Vec<bool>> = HashMap::new();
for (name, func) in &funcs {
let inferred = inferred_ref_params.get(name).cloned().unwrap_or_default();
let mut refs = vec![false; func.params.len()];
for (idx, param) in func.params.iter().enumerate() {
refs[idx] = param.is_reference || inferred.get(idx).copied().unwrap_or(false);
}
effective_ref_params.insert(name.clone(), refs);
}
let mut direct_mutates: HashMap<String, Vec<bool>> = HashMap::new();
let mut edges: Vec<(String, usize, String, usize)> = Vec::new();
for (name, func) in &funcs {
let caller_refs = effective_ref_params
.get(name)
.cloned()
.unwrap_or_else(|| vec![false; func.params.len()]);
let mut direct = vec![false; func.params.len()];
let mut param_index_by_name: HashMap<String, usize> = HashMap::new();
for (idx, param) in func.params.iter().enumerate() {
for param_name in param.get_identifiers() {
param_index_by_name.insert(param_name, idx);
}
}
for stmt in &func.body {
Self::analyze_statement_for_ref_mutation(
stmt,
name,
¶m_index_by_name,
&caller_refs,
&effective_ref_params,
&mut direct,
&mut edges,
);
}
direct_mutates.insert(name.clone(), direct);
}
let mut result = direct_mutates;
let mut changed = true;
while changed {
changed = false;
for (caller, caller_idx, callee, callee_idx) in &edges {
let callee_mutates = result
.get(callee)
.and_then(|flags| flags.get(*callee_idx))
.copied()
.unwrap_or(false);
if !callee_mutates {
continue;
}
if let Some(caller_flags) = result.get_mut(caller)
&& let Some(flag) = caller_flags.get_mut(*caller_idx)
&& !*flag
{
*flag = true;
changed = true;
}
}
}
(
inferred_ref_params,
result,
inferred_param_type_hints,
inferred_return_type_hints,
inferred_param_concrete_types,
inferred_param_object_fields,
inferred_return_object_fields,
)
}
/// WS-9b: project the program-wide type-inference engine's per-parameter
/// `Type` into a `Vec<(field_name, FieldType)>` for UNANNOTATED params
/// whose resolved type is an anonymous structural object.
///
/// Mirrors `infer_param_concrete_types_from_types` — same
/// `Type::Function`-keyed lookup, same annotated-param / non-simple-name
/// skip. Only `Type::Concrete(TypeAnnotation::Object(_))` params produce
/// `Some`; named structs (which resolve through the schema registry via
/// their hint name) and every non-object param keep `None`. A field
/// whose annotation projects to `FieldType::Any` is still recorded —
/// `Any` is the honest "field exists, kind not narrowed" marker, not a
/// fabricated primitive.
pub(super) fn infer_param_object_fields_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, Vec<Option<Vec<(String, shape_runtime::type_schema::FieldType)>>>> {
use shape_ast::ast::TypeAnnotation;
let funcs = Self::collect_program_functions(program);
let mut out = HashMap::new();
for (name, func) in funcs {
let mut param_fields: Vec<
Option<Vec<(String, shape_runtime::type_schema::FieldType)>>,
> = vec![None; func.params.len()];
let Some(Type::Function { params, .. }) = inferred_types.get(&name) else {
out.insert(name, param_fields);
continue;
};
for (idx, param) in func.params.iter().enumerate() {
if param.type_annotation.is_some() || param.simple_name().is_none() {
continue;
}
let Some(inferred_param_ty) = params.get(idx) else {
continue;
};
if let Type::Concrete(TypeAnnotation::Object(obj_fields)) = inferred_param_ty {
let fields: Vec<(String, shape_runtime::type_schema::FieldType)> = obj_fields
.iter()
.map(|f| {
(
f.name.clone(),
Self::type_annotation_to_field_type(&f.type_annotation),
)
})
.collect();
if !fields.is_empty() {
param_fields[idx] = Some(fields);
}
}
}
out.insert(name, param_fields);
}
out
}
/// WS-9c: project each function's inferred RETURN type into a
/// `Vec<(field_name, FieldType)>` when that return type is an anonymous
/// structural object.
///
/// Mirrors `infer_param_object_fields_from_types` for the return
/// position. The motivating shape is an anonymous-object factory:
/// `fn aabb(lo, hi) { {min: lo, max: hi} }`. The program-wide inference
/// pass resolves the return type to `Object({min: int, max: int})` once
/// callsite propagation binds the parameters; this projection hands the
/// bytecode compiler the per-field types so it can register an anonymous
/// schema for the return value and resolve `aabb(...).field` /
/// `let a = aabb(...); a.field` — exactly the resolution a named struct
/// return type already gets. A return type that is not an anonymous
/// object (a primitive, a named struct, an array, or still-unresolved)
/// keeps `None`.
pub(super) fn infer_return_object_fields_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, Vec<(String, shape_runtime::type_schema::FieldType)>> {
use shape_ast::ast::TypeAnnotation;
let funcs = Self::collect_program_functions(program);
let mut out = HashMap::new();
for (name, func) in funcs {
// A function with an explicit return-type annotation already
// resolves through the annotation path in
// `compile_expr_function_call`; only unannotated functions need
// the inferred-return projection.
if func.return_type.is_some() {
continue;
}
let Some(Type::Function { returns, .. }) = inferred_types.get(&name) else {
continue;
};
if let Type::Concrete(TypeAnnotation::Object(obj_fields)) = returns.as_ref() {
let fields: Vec<(String, shape_runtime::type_schema::FieldType)> = obj_fields
.iter()
.map(|f| {
(
f.name.clone(),
Self::type_annotation_to_field_type(&f.type_annotation),
)
})
.collect();
if !fields.is_empty() {
out.insert(name, fields);
}
}
}
out
}
/// WS-9c: register an inline anonymous schema for every unannotated
/// function whose inferred return type is an anonymous object, recording
/// the schema id under the function name in `function_return_schema_ids`
/// and the precise per-field types as schema field contracts.
///
/// The schema is Any-uniform (mirroring
/// `extract_object_schema_id_from_annotation` so the layout matches the
/// pre-existing inline-object shape); the precise field types live in the
/// parallel field-contract side table consulted by `infer_expr_type`.
fn register_inferred_return_object_schemas(&mut self) {
use shape_runtime::type_schema::FieldType;
let return_fields = self.inferred_return_object_fields.clone();
for (fn_name, fields) in return_fields {
if fields.is_empty() {
continue;
}
let typed_fields: Vec<(&str, FieldType)> = fields
.iter()
.map(|(name, _)| (name.as_str(), FieldType::Any))
.collect();
let schema_id = self
.type_tracker
.register_inline_object_schema_typed(&typed_fields);
let mut contracts = std::collections::HashMap::with_capacity(fields.len());
for (name, field_ty) in &fields {
if let Some(ann) =
crate::compiler::expressions::function_calls::field_type_contract_annotation(
field_ty,
)
{
contracts.insert(name.clone(), ann);
}
}
if !contracts.is_empty() {
self.type_tracker
.register_object_field_contracts(schema_id, contracts);
}
self.function_return_schema_ids
.insert(fn_name, schema_id);
}
}
/// v0.3 WS-7: project the program-wide type-inference engine's
/// per-parameter `Type` into a `ConcreteType` for UNANNOTATED params.
///
/// The JIT's v2 typed-array fast path is gated on
/// `function_local_concrete_types[fn][param_slot]` carrying a precise
/// `ConcreteType::Array(elem)`. For an annotated param that stamp comes
/// from the annotation; for an UNANNOTATED param (`fn get(xs, i) {
/// xs[i] }`) there is no annotation to read, so without this projection
/// the slot stays `ConcreteType::Void`. The JIT then mis-takes the v2
/// `TypedArray<T>` pointer (data@+8/len@+16) for a NaN-boxed v1 array
/// (data@+0/len@+8 after an 8-byte header) and the inline index load
/// reads garbage / SIGSEGVs even on a valid in-bounds access.
///
/// Mirrors `infer_param_type_hints_from_types` exactly — same
/// `Type::Function`-keyed lookup, same annotated-param skip — but
/// projects to `ConcreteType` (the JIT's proof carrier) instead of a
/// display string. Annotated params keep `None`; their `ConcreteType`
/// is stamped from the annotation in the per-fn seeding pass.
pub(super) fn infer_param_concrete_types_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, Vec<Option<shape_value::v2::ConcreteType>>> {
let funcs = Self::collect_program_functions(program);
let mut out = HashMap::new();
for (name, func) in funcs {
let mut param_cts: Vec<Option<shape_value::v2::ConcreteType>> =
vec![None; func.params.len()];
let Some(Type::Function { params, .. }) = inferred_types.get(&name) else {
out.insert(name, param_cts);
continue;
};
for (idx, param) in func.params.iter().enumerate() {
// Annotated params are stamped from the annotation directly
// in the `function_local_concrete_types` per-fn seeding pass;
// a destructuring param has no single slot ConcreteType.
if param.type_annotation.is_some() || param.simple_name().is_none() {
continue;
}
let Some(inferred_param_ty) = params.get(idx) else {
continue;
};
// `Type::to_annotation()` reconstructs the `TypeAnnotation`
// for resolved concrete / generic types and yields `None`
// for unresolved type variables — exactly the gate we want
// (no fabricated kind, no Bool-default). The existing
// `concrete_type_from_annotation` then projects
// `Array<int>` → `ConcreteType::Array(I64)`.
let Some(ann) = inferred_param_ty.to_annotation() else {
continue;
};
param_cts[idx] =
crate::compiler::v2_map_emission::concrete_type_from_annotation(&ann);
}
out.insert(name, param_cts);
}
out
}
pub(crate) fn inferred_type_to_hint_name(ty: &Type) -> Option<String> {
match ty {
Type::Concrete(annotation) => Some(annotation.to_type_string()),
Type::Generic { base, args } => {
let base_name = Self::inferred_type_to_hint_name(base)?;
if args.is_empty() {
return Some(base_name);
}
let mut arg_names = Vec::with_capacity(args.len());
for arg in args {
arg_names.push(Self::inferred_type_to_hint_name(arg)?);
}
Some(format!("{}<{}>", base_name, arg_names.join(", ")))
}
Type::Variable(_) | Type::Constrained { .. } | Type::Function { .. } => None,
}
}
pub(super) fn infer_param_type_hints_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, Vec<Option<String>>> {
let funcs = Self::collect_program_functions(program);
let mut hints = HashMap::new();
for (name, func) in funcs {
let mut param_hints = vec![None; func.params.len()];
let Some(Type::Function { params, .. }) = inferred_types.get(&name) else {
hints.insert(name, param_hints);
continue;
};
for (idx, param) in func.params.iter().enumerate() {
if param.type_annotation.is_some() || param.simple_name().is_none() {
continue;
}
if let Some(inferred_param_ty) = params.get(idx) {
param_hints[idx] = Self::inferred_type_to_hint_name(inferred_param_ty);
}
}
hints.insert(name, param_hints);
}
hints
}
/// Phase 3e: extract a hint name for each function's inferred return
/// type. Used to populate `type_tracker.function_return_types` so call
/// expressions can recover numeric types (and string/bool primitives
/// via `set_function_return_type`) when the source has no explicit
/// return-type annotation.
pub(super) fn infer_return_type_hints_from_types(
program: &Program,
inferred_types: &HashMap<String, Type>,
) -> HashMap<String, String> {
let funcs = Self::collect_program_functions(program);
let mut hints = HashMap::new();
for (name, _) in funcs {
let Some(Type::Function { returns, .. }) = inferred_types.get(&name) else {
continue;
};
if let Some(rt_name) = Self::inferred_type_to_hint_name(returns) {
hints.insert(name, rt_name);
}
}
hints
}
pub(crate) fn resolve_compiled_annotation_name(
&self,
annotation: &shape_ast::ast::Annotation,
) -> Option<String> {
self.resolve_compiled_annotation_name_str(&annotation.name)
}
pub(crate) fn resolve_compiled_annotation_name_str(&self, name: &str) -> Option<String> {
if self.program.compiled_annotations.contains_key(name) {
return Some(name.to_string());
}
// W9: handle qualified `@local::name` form by resolving the local
// namespace prefix to its canonical module path, then looking up
// `canonical::name` in compiled_annotations.
if let Some((local_prefix, rest)) = name.split_once("::") {
// First try graph-driven namespace map (canonical for graph compile).
if let Some(canonical) = self.graph_namespace_map.get(local_prefix) {
let qualified = Self::qualify_module_symbol(canonical, rest);
if self.program.compiled_annotations.contains_key(&qualified) {
return Some(qualified);
}
}
// Fall back to module_scope_sources (legacy / non-graph compile).
if let Some(canonical) = self.module_scope_sources.get(local_prefix) {
let qualified = Self::qualify_module_symbol(canonical, rest);
if self.program.compiled_annotations.contains_key(&qualified) {
return Some(qualified);
}
}
return None;
}
for module_path in self.module_scope_stack.iter().rev() {
let scoped = Self::qualify_module_symbol(module_path, name);
if self.program.compiled_annotations.contains_key(&scoped) {
return Some(scoped);
}
}
if let Some(imported) = self.imported_annotations.get(name) {
let hidden_name =
Self::qualify_module_symbol(&imported.hidden_module_name, &imported.original_name);
if self.program.compiled_annotations.contains_key(&hidden_name) {
return Some(hidden_name);
}
}
None
}
pub(crate) fn lookup_compiled_annotation(
&self,
annotation: &shape_ast::ast::Annotation,
) -> Option<(String, crate::bytecode::CompiledAnnotation)> {
let resolved_name = self.resolve_compiled_annotation_name(annotation)?;
let compiled = self
.program
.compiled_annotations
.get(&resolved_name)?
.clone();
Some((resolved_name, compiled))
}
pub(crate) fn annotation_matches_compiled_name(
&self,
annotation: &shape_ast::ast::Annotation,
compiled_name: &str,
) -> bool {
self.resolve_compiled_annotation_name(annotation).as_deref() == Some(compiled_name)
}
pub(crate) fn annotation_args_for_compiled_name(
&self,
annotations: &[shape_ast::ast::Annotation],
compiled_name: &str,
) -> Vec<shape_ast::ast::Expr> {
annotations
.iter()
.find(|annotation| self.annotation_matches_compiled_name(annotation, compiled_name))
.map(|annotation| annotation.args.clone())
.unwrap_or_default()
}
pub(crate) fn is_definition_annotation_target(
target_kind: shape_ast::ast::functions::AnnotationTargetKind,
) -> bool {
matches!(
target_kind,
shape_ast::ast::functions::AnnotationTargetKind::Function
| shape_ast::ast::functions::AnnotationTargetKind::Type
| shape_ast::ast::functions::AnnotationTargetKind::Module
)
}
/// Validate that an annotation is applicable to the requested target kind.
pub(crate) fn validate_annotation_target_usage(
&self,
ann: &shape_ast::ast::Annotation,
target_kind: shape_ast::ast::functions::AnnotationTargetKind,
fallback_span: shape_ast::ast::Span,
) -> Result<()> {
let Some((_, compiled)) = self.lookup_compiled_annotation(ann) else {
let span = if ann.span == shape_ast::ast::Span::DUMMY {
fallback_span
} else {
ann.span
};
return Err(ShapeError::SemanticError {
message: format!("Unknown annotation '@{}'", ann.name),
location: Some(self.span_to_source_location(span)),
});
};
let has_definition_lifecycle =
compiled.on_define_handler.is_some() || compiled.metadata_handler.is_some();
if has_definition_lifecycle && !Self::is_definition_annotation_target(target_kind) {
let target_label = format!("{:?}", target_kind).to_lowercase();
let span = if ann.span == shape_ast::ast::Span::DUMMY {
fallback_span
} else {
ann.span
};
return Err(ShapeError::SemanticError {
message: format!(
"Annotation '{}' defines definition-time lifecycle hooks (`on_define`/`metadata`) and cannot be applied to a {}. Allowed targets for these hooks are: function, type, module",
ann.name, target_label
),
location: Some(self.span_to_source_location(span)),
});
}
if compiled.allowed_targets.is_empty() || compiled.allowed_targets.contains(&target_kind) {
return Ok(());
}
let allowed: Vec<String> = compiled
.allowed_targets
.iter()
.map(|k| format!("{:?}", k).to_lowercase())
.collect();
let target_label = format!("{:?}", target_kind).to_lowercase();
let span = if ann.span == shape_ast::ast::Span::DUMMY {
fallback_span
} else {
ann.span
};
Err(ShapeError::SemanticError {
message: format!(
"Annotation '{}' cannot be applied to a {}. Allowed targets: {}",
ann.name,
target_label,
allowed.join(", ")
),
location: Some(self.span_to_source_location(span)),
})
}
/// Compile a program to bytecode
pub fn compile(mut self, program: &Program) -> Result<BytecodeProgram> {
// First: desugar the program (converts FromQuery to method chains, etc.)
let mut program = program.clone();
shape_ast::transform::desugar_program(&mut program);
let analysis_program =
shape_ast::transform::augment_program_with_generated_extends(&program);
// Run the shared analyzer and surface diagnostics that are currently
// proven reliable in the compiler execution path.
let mut known_bindings: Vec<String> = self.module_bindings.keys().cloned().collect();
let namespace_bindings = Self::collect_namespace_import_bindings(&analysis_program);
// Inline: collect namespace and annotation import scope sources
for item in &analysis_program.items {
if let shape_ast::ast::Item::Import(import_stmt, _) = item {
if import_stmt.from.is_empty() {
continue;
}
match &import_stmt.items {
shape_ast::ast::ImportItems::Namespace { name, alias } => {
let local_name = alias.clone().unwrap_or_else(|| name.clone());
self.module_scope_sources
.entry(local_name)
.or_insert_with(|| import_stmt.from.clone());
}
shape_ast::ast::ImportItems::Named(specs) => {
// W9: register annotation-import scope source against
// the canonical module path. The synthetic hidden-module
// name is no longer used; use-site annotation resolution
// looks up `canonical_path::name` directly.
if specs.iter().any(|spec| spec.is_annotation) {
self.module_scope_sources
.entry(import_stmt.from.clone())
.or_insert_with(|| import_stmt.from.clone());
}
}
}
}
}
known_bindings.extend(namespace_bindings.iter().cloned());
// R8 W8 Cluster A: imported `pub const` names are valid identifier
// bindings at consumer-side use sites; teach the analyzer about
// them so `unknown-binding` warnings don't blanket the use site
// before the const-inline path replaces the identifier reference.
known_bindings.extend(self.imported_consts.keys().cloned());
self.module_namespace_bindings
.extend(namespace_bindings.into_iter());
for namespace in self.module_namespace_bindings.clone() {
let binding_idx = self.get_or_create_module_binding(&namespace);
self.register_extension_module_schema(&namespace);
let module_schema_name = format!("__mod_{}", namespace);
if self
.type_tracker
.schema_registry()
.get(&module_schema_name)
.is_some()
{
self.set_module_binding_type_info(binding_idx, &module_schema_name);
}
}
known_bindings.sort();
known_bindings.dedup();
let analysis_mode = if matches!(self.type_diagnostic_mode, TypeDiagnosticMode::RecoverAll) {
TypeAnalysisMode::RecoverAll
} else {
TypeAnalysisMode::FailFast
};
if let Err(errors) = analyze_program_with_mode(
&analysis_program,
self.source_text.as_deref(),
None,
Some(&known_bindings),
analysis_mode,
) {
match self.type_diagnostic_mode {
TypeDiagnosticMode::Strict => {
return Err(Self::type_errors_to_shape(errors));
}
TypeDiagnosticMode::ReliableOnly => {
let strict_errors: Vec<_> = errors
.into_iter()
.filter(|error| Self::should_emit_type_diagnostic(&error.error))
.collect();
if !strict_errors.is_empty() {
return Err(Self::type_errors_to_shape(strict_errors));
}
}
TypeDiagnosticMode::RecoverAll => {
self.errors.extend(
errors
.into_iter()
.map(Self::type_error_with_location_to_shape),
);
}
}
}
let (
inferred_ref_params,
inferred_ref_mutates,
inferred_param_type_hints,
inferred_return_type_hints,
inferred_param_concrete_types,
inferred_param_object_fields,
inferred_return_object_fields,
) = Self::infer_reference_model(&program);
self.inferred_param_pass_modes =
Self::build_param_pass_mode_map(&program, &inferred_ref_params, &inferred_ref_mutates);
self.inferred_ref_params = inferred_ref_params;
self.inferred_ref_mutates = inferred_ref_mutates;
self.inferred_param_type_hints = inferred_param_type_hints;
self.inferred_param_concrete_types = inferred_param_concrete_types;
self.inferred_param_object_fields = inferred_param_object_fields;
self.inferred_return_object_fields = inferred_return_object_fields;
// WS-9c: eagerly register an inline anonymous schema (+ per-field
// contracts) for every unannotated function whose inferred return
// type is an anonymous object. Registering up-front — before any
// body compiles — makes the return-object schema available both to
// `compile_expr_function_call` (which stamps it on the call's
// `last_expr_schema` so a `let` binding inherits it) and to the
// read-only `infer_expr_type` property-access path (which resolves
// `f(...).field` directly). `register_inline_object_schema_typed` is
// idempotent on the field set, so this never duplicates a schema.
self.register_inferred_return_object_schemas();
// Phase 3e: register inferred return types so function-call
// compilation can recover the numeric type even for sources with
// no explicit `-> T` annotation.
for (fn_name, ret_ty) in &inferred_return_type_hints {
self.type_tracker
.register_function_return_type(fn_name, ret_ty);
}
// Two-phase TypedObject field hoisting:
//
// Phase 1 (here, AST pre-pass): Collect all property assignments (e.g.,
// `a.y = 2`) from the entire program BEFORE any function compilation.
// This populates `hoisted_fields` so that `compile_typed_object_literal`
// can allocate schema slots for future fields at object-creation time.
// Without this pre-pass, the schema would be too small and a later
// `a.y = 2` would require a schema migration at runtime.
//
// Phase 2 (per-function, MIR): During function compilation, MIR field
// analysis (`mir::field_analysis::analyze_fields`) runs flow-sensitive
// definite-initialization and liveness analysis. This detects:
// - `dead_fields`: fields that are written but never read (wasted slots)
// - `conditionally_initialized`: fields only assigned on some paths
//
// After MIR analysis, the compiler can cross-reference
// `mir_field_analyses[func].dead_fields` to prune unused hoisted fields
// from schemas. The dead_fields set uses `(SlotId, FieldIdx)` which must
// be mapped to field names via the schema registry — see the integration
// note in `compile_typed_object_literal`.
{
use shape_runtime::type_system::inference::PropertyAssignmentCollector;
use shape_ast::ast::{Expr, Literal};
use shape_runtime::type_schema::FieldType;
let assignments = PropertyAssignmentCollector::collect(&program);
let grouped = PropertyAssignmentCollector::group_by_variable(&assignments);
// Phase 3e: infer a primitive FieldType for each hoisted field
// when the RHS is a literal whose type is statically known.
// Falls back to FieldType::Any (the prior behavior) for
// non-literal RHS or types we can't map.
let infer_lit = |expr: &Expr| -> Option<FieldType> {
match expr {
Expr::Literal(Literal::Int(_), _) => Some(FieldType::I64),
Expr::Literal(Literal::Number(_), _) => Some(FieldType::F64),
Expr::Literal(Literal::Decimal(_), _) => Some(FieldType::Decimal),
Expr::Literal(Literal::Bool(_), _) => Some(FieldType::Bool),
Expr::Literal(Literal::String(_), _) => Some(FieldType::String),
_ => None,
}
};
for (var_name, var_assignments) in grouped {
let field_names: Vec<String> =
var_assignments.iter().map(|a| a.property.clone()).collect();
let mut type_map: std::collections::HashMap<String, FieldType> =
std::collections::HashMap::new();
for a in &var_assignments {
if let Some(ft) = infer_lit(&a.value_expr) {
type_map.insert(a.property.clone(), ft);
}
}
if !type_map.is_empty() {
self.hoisted_field_types.insert(var_name.clone(), type_map);
}
self.hoisted_fields.insert(var_name, field_names);
}
}
// First pass: collect all function definitions
for item in &program.items {
self.register_item_functions(item)?;
}
// WS-9b: pre-register struct type SCHEMAS (runtime fields only — no
// comptime-handler execution, that stays in the pass-2
// `register_struct_type`). This makes `type` definitions
// order-independent the same way `register_item_functions` makes
// function definitions order-independent: a function declared
// *before* the `type` it takes as a parameter (`fn ov(a, b) { a.lo
// <= b.hi }` ahead of `type Box`) can now resolve `a.lo` against the
// `Box` schema during its body compilation. Without the prepass the
// schema is registered only when the later `type` item compiles, so
// `tracker_schema_id_for_expr` misses it and the property access
// types as `unknown`.
for item in &program.items {
self.predeclare_item_struct_schemas(item);
}
// MIR authority for non-function items: run borrow analysis on top-level
// code before compilation. Errors in cleanly-lowered regions are emitted;
// errors in fallback regions are suppressed (span-granular filtering).
if let Err(e) = self.analyze_non_function_items_with_mir("__main__", &program.items) {
self.errors.push(e);
}
// Start __main__ blob builder for top-level code.
self.current_blob_builder = Some(FunctionBlobBuilder::new(
"__main__".to_string(),
self.program.current_offset(),
self.program.constants.len(),
self.program.strings.len(),
));
// Push a top-level drop scope so that block expressions and
// statement-level VarDecls can track locals for auto-drop.
self.push_drop_scope();
self.non_function_mir_context_stack
.push("__main__".to_string());
// Register root's imports from the module graph. This emits alias
// copy instructions (e.g. `set = std::core::set`) and MUST happen
// INSIDE the `__main__` blob — emitting before the blob started
// would leave the copies in an unreachable gap, so at runtime the
// alias binding would remain None and `set::contains(...)` would
// read a None callable and raise `InvalidCall`.
if let Some(graph) = self.module_graph.clone() {
let root_id = graph.root_id();
self.register_graph_imports_for_module(root_id, &graph)?;
}
// Second pass: compile all items (collect errors instead of early-returning)
let item_count = program.items.len();
for (idx, item) in program.items.iter().enumerate() {
let is_last = idx == item_count - 1;
let future_names =
self.future_reference_use_names_for_remaining_items(&program.items[idx + 1..]);
self.push_future_reference_use_names(future_names);
let compile_result = self.compile_item_with_context(item, is_last);
self.pop_future_reference_use_names();
if let Err(e) = compile_result {
self.errors.push(e);
}
// E+5.5 Unit C step 2: capture the final expression's return-kind
// signal RIGHT AFTER the last item compiles, before drop-scope
// emission and Halt overwrite `last_expr_*`. The captured value
// is consumed in `populate_program_storage_hints` to populate
// `top_level_frame.return_kind` for the host-boundary
// ValueWord synthesis.
if is_last && self.errors.is_empty() {
// Per ADR-006 §2.7.5.1, `infer_top_level_return_kind` /
// `infer_top_level_return_kind_from_item` carry "kind not
// yet proven" as `Option::None` — `.or_else(...)` falls
// back to the AST-driven path when the state-driven one
// produced no kind.
let kind = self
.infer_top_level_return_kind()
.or_else(|| self.infer_top_level_return_kind_from_item(item));
self.top_level_program_return_kind = kind;
}
self.release_unused_module_reference_borrows_for_remaining_items(
&program.items[idx + 1..],
);
}
self.non_function_mir_context_stack.pop();
// Phase 4b Round 6 WS-1b W16.2-C residual: surface-and-stop any
// top-level bare empty-array accumulator (`let mut out = []`) whose
// element type was never resolved by a downstream `.push(...)`.
if let Err(e) = self.finalize_unresolved_empty_array_accumulators() {
self.errors.push(e);
}
// Return collected errors before emitting Halt
if !self.errors.is_empty() {
if self.errors.len() == 1 {
return Err(self.errors.remove(0));
}
return Err(shape_ast::error::ShapeError::MultiError(self.errors));
}
// Emit drops for top-level locals (from the top-level drop scope)
self.pop_drop_scope()?;
// Emit drops for top-level module bindings that have Drop impls
{
let bindings: Vec<(u16, bool)> = std::mem::take(&mut self.drop_module_bindings);
for (binding_idx, is_async) in bindings.into_iter().rev() {
self.emit_drop_call_for_module_binding(binding_idx, is_async);
}
}
// Add halt instruction at the end
self.emit(Instruction::simple(OpCode::Halt));
// Store module_binding variable names for REPL persistence
// Build a Vec<String> where index matches the module_binding variable index
let mut module_binding_names = vec![String::new(); self.module_bindings.len()];
for (name, &idx) in &self.module_bindings {
module_binding_names[idx as usize] = name.clone();
}
self.program.module_binding_names = module_binding_names;
// Store top-level locals count so executor can advance sp past them
self.program.top_level_locals_count = self.next_local;
// Persist storage hints for JIT width-aware lowering.
self.populate_program_storage_hints();
// Transfer type schema registry for TypedObject field resolution
self.program.type_schema_registry = self.type_tracker.schema_registry().clone();
// Transfer final function definitions after comptime mutation/specialization.
self.program.expanded_function_defs = self.function_defs.clone();
// Transfer monomorphization cache keys for diagnostics/testing.
self.program.monomorphization_keys = self.monomorphization_cache.keys().cloned().collect();
// Cache top-level MIR data for JIT v2 (MirToIR compilation of __main__).
// The MIR and borrow analysis were computed by analyze_non_function_items_with_mir
// above; we combine them with a storage plan here.
{
let mir_opt = self.mir_functions.get("__main__").cloned();
let borrow_opt = self.mir_borrow_analyses.get("__main__").cloned();
if let (Some(mut mir), Some(borrow_analysis)) = (mir_opt, borrow_opt) {
if !self.closure_function_ids.is_empty() {
let mut closure_idx = 0;
let closure_ids = self.closure_function_ids.clone();
let mut has_capture = false;
for block in &mut mir.blocks {
for stmt in &mut block.statements {
let is_placeholder = matches!(
&stmt.kind,
crate::mir::types::StatementKind::Assign(
_,
crate::mir::types::Rvalue::Use(
crate::mir::types::Operand::Constant(
crate::mir::types::MirConstant::ClosurePlaceholder
)
)
)
);
if is_placeholder {
if has_capture {
stmt.kind = crate::mir::types::StatementKind::Nop;
has_capture = false;
} else if closure_idx < closure_ids.len() {
let (ref name, _) = closure_ids[closure_idx];
let slot = match &stmt.kind {
crate::mir::types::StatementKind::Assign(p, _) => {
p.root_local()
}
_ => unreachable!(),
};
stmt.kind = crate::mir::types::StatementKind::Assign(
crate::mir::types::Place::Local(slot),
crate::mir::types::Rvalue::Use(
crate::mir::types::Operand::Constant(
crate::mir::types::MirConstant::Function(
name.clone(),
),
),
),
);
closure_idx += 1;
}
continue;
}
if let crate::mir::types::StatementKind::ClosureCapture {
function_id,
..
} = &mut stmt.kind
{
if closure_idx < closure_ids.len() {
let (_, idx) = closure_ids[closure_idx];
*function_id = Some(idx);
closure_idx += 1;
has_capture = true;
}
}
}
}
}
use std::collections::{HashMap as StdHashMap, HashSet as StdHashSet};
let planner_input = crate::mir::storage_planning::StoragePlannerInput {
mir: &mir,
analysis: &borrow_analysis,
binding_semantics: &StdHashMap::new(),
closure_captures: &StdHashSet::new(),
mutable_captures: &StdHashSet::new(),
had_fallbacks: true, // conservative: top-level MIR often has fallbacks
callee_summaries: Some(&self.function_borrow_summaries),
};
let storage_plan = crate::mir::storage_planning::plan_storage(&planner_input);
// ADR-006 §2.7.5 stamp-at-compile-time, Phase 3
// cluster-0 Round 16 W17-narrow-follow-up-A: thread
// schema ids on top-level MIR `ObjectStore`
// statements (canonical Smoke 3 site — `let t = X {}`
// is top-level). Same back-patch as the per-function
// path at `compiler/functions.rs` post-closure-id
// patching; reads `mir.local_struct_type_names` +
// `type_tracker.schema_registry()` to align with the
// parallel bytecode-side `OpCode::NewTypedObject`
// operand.
crate::compiler::mir_schema_threading::back_patch_schema_ids(
&mut mir,
&mut self.type_tracker,
);
self.program.top_level_mir =
Some(std::sync::Arc::new(crate::bytecode::MirFunctionData {
mir,
storage_plan,
borrow_analysis,
}));
}
}
// ADR-006 §2.7.5 conduit: stamp per-MIR-slot `ConcreteType` for
// top-level code by walking the cached top-level MIR. The JIT
// MirToIR reads this side-table (`BytecodeProgram.
// top_level_local_concrete_types`) to drive the v2 typed-array
// fast path (avoiding `Rvalue::Aggregate` surface-and-stop) and
// the TypedObject `ObjectStore` short-circuit.
//
// Why MIR-walk rather than bytecode-compiler slot mapping: top-
// level code allocates the user's bindings as module_bindings
// (NOT bytecode locals — `self.next_local` is 0 at top level),
// so the bytecode-compiler's per-local side-tables do not
// carry top-level `let p = Point{...}` slots. The cached top-
// level MIR already encodes the structural type information
// through `StatementKind::{ObjectStore, ArrayStore, EnumStore}`
// — the MIR-level kind-source statements emitted for
// struct/enum/array construction. The walk is purely from the
// proven MIR shape; no runtime decode, no Bool-default fallback.
//
// The result is indexed by MIR `SlotId` (matching MirToIR's
// `concrete_type_for_slot` / `is_v2_typed_array_slot` indexing
// exactly). `ConcreteType::Void` per slot means "no
// information inferred" — a real enum variant per §2.7.5.1, not
// a Bool-default fallback per forbidden #9.
//
// The top-level conduit walk is deferred a few lines down — it
// runs AFTER the per-function return-type side-table is built,
// so the Call-terminator destination stamping in the walk has
// access to callee return types via the resolver. See the
// W12-jit-call-return-kind block below.
// ADR-006 §2.7.5 conduit (W12-jit-call-return-kind close, 2026-05-12):
// Per-user-function declared return ConcreteType, built first so the
// per-function and top-level conduit passes can consume it via the
// callee-return resolver. Returns are classified from the AST
// `FunctionDef.return_type` (preserved via `expanded_function_defs`)
// through `concrete_type_from_annotation` (already used for HashMap
// key/value extraction). When the function has no annotation or the
// annotation doesn't reduce to a known shape, the entry stays
// `ConcreteType::Void` per §2.7.5.1 — NOT a Bool-default fallback.
let mut per_fn_ret: Vec<shape_value::v2::ConcreteType> =
Vec::with_capacity(self.program.functions.len());
for func in &self.program.functions {
let ct = self
.program
.expanded_function_defs
.get(&func.name)
.and_then(|fd| fd.return_type.as_ref())
.and_then(|ann| {
crate::compiler::v2_map_emission::concrete_type_from_annotation(
ann,
)
})
.unwrap_or(shape_value::v2::ConcreteType::Void);
per_fn_ret.push(ct);
}
self.program.function_return_concrete_types = per_fn_ret;
// Build the callee-return resolver: maps `MirConstant::Function(name)`
// to the callee's declared return ConcreteType via the side-table
// just populated. Used by the conduit passes below to stamp
// `TerminatorKind::Call` destination slots. `None` for unknown /
// unannotated / void-returning functions — the destination slot
// stays `Void` (no fabrication).
let name_to_idx: std::collections::HashMap<String, usize> = self
.program
.functions
.iter()
.enumerate()
.map(|(i, f)| (f.name.clone(), i))
.collect();
let returns_vec = self.program.function_return_concrete_types.clone();
let callee_returns = |name: &str| -> Option<shape_value::v2::ConcreteType> {
let idx = *name_to_idx.get(name)?;
let ct = returns_vec.get(idx)?;
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct.clone())
}
};
// ADR-006 §2.7.5 — Phase 3 cluster-0 Round 13 T1' commit 2:
// method-returns resolver for trait-method dispatch return-kind
// classification. Chains:
// `find_default_trait_impl_for_type_method(type_name, method_name)
// → trait impl function name (e.g. "X::name")
// → function_return_concrete_types[function_index]
// → declared return ConcreteType (e.g. ConcreteType::String)`
//
// Used by the conduit producer to stamp `TerminatorKind::Call`
// destination slots for `MirConstant::Method(_)` arms with a
// receiver slot whose struct type name was recorded in MIR
// (`mir.local_struct_type_names`, T1' gap 1 closure). `None` at
// any link in the chain means "no information" — the destination
// slot stays `Void` per §2.7.5.1 (no fabricated default).
//
// Gap 3 closure (commit 1, `desugar_impl_method` trait
// declaration return-type substitution) ensures
// `function_return_concrete_types["X::name"]` carries the trait's
// declared `ConcreteType::String` even when the impl source
// doesn't repeat the `: string` annotation.
let trait_method_symbols = self.program.trait_method_symbols.clone();
let find_trait_impl_default_suffix =
|type_name: &str, method_name: &str| -> Option<String> {
// Mirror BytecodeProgram::find_default_trait_impl_for_type_method
// semantics (the canonical helper at
// `crates/shape-vm/src/bytecode/program_impl.rs:151`)
// without borrowing `self.program` — the closure must be
// passable by reference to the conduit producer
// alongside `callee_returns`. The "__default__" selector
// string is `DEFAULT_TRAIT_IMPL_SELECTOR` at
// `crates/shape-vm/src/bytecode.rs:15`; inlined here to
// avoid the borrow.
let default_suffix = format!(
"::{}::__default__::{}",
type_name, method_name
);
for (key, func_name) in &trait_method_symbols {
if key.ends_with(&default_suffix) {
return Some(func_name.clone());
}
}
let type_segment = format!("::{}::", type_name);
let suffix = format!("::{}", method_name);
let mut matches: Vec<String> = Vec::new();
for (key, func_name) in &trait_method_symbols {
if key.contains(&type_segment) && key.ends_with(&suffix) {
matches.push(func_name.clone());
}
}
// Multi-trait method-name disambiguation (audit §5):
// when multiple traits declare `method()` for the same
// receiver type, we cannot determine the return
// ConcreteType uniquely from name alone — return None so
// the downstream classifier surfaces unstamped.
if matches.len() == 1 {
Some(matches.pop().unwrap())
} else {
None
}
};
let method_returns =
|type_name: &str, method_name: &str| -> Option<shape_value::v2::ConcreteType> {
let func_name = find_trait_impl_default_suffix(type_name, method_name)?;
let idx = *name_to_idx.get(&func_name)?;
let ct = returns_vec.get(idx)?;
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct.clone())
}
};
// ADR-006 §2.7.5 V3-S6b conduit consumer: monomorph-method
// resolver. Reads `BytecodeProgram.monomorphized_method_call_sites`
// populated by `try_monomorphize_method_call` /
// `_with_closures` at bytecode-compile time, then chains the
// looked-up specialized FunctionId through `returns_vec` (the
// local clone of `function_return_concrete_types`) to recover the
// callee specialization's declared return type. The closure
// closes over the `current_function` half of the composite key
// — top-level uses `None`; per-fn loop below uses
// `Some(fn_idx)`.
let monomorph_call_sites =
self.program.monomorphized_method_call_sites.clone();
let monomorph_method_returns_top = |span: shape_ast::ast::span::Span|
-> Option<shape_value::v2::ConcreteType>
{
let idx = *monomorph_call_sites.get(&(span, None))?;
let ct = returns_vec.get(idx)?;
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct.clone())
}
};
// cluster-2-cw-IB-class-b (2026-05-16, supervisor R3 binding-
// ratified): value-call return-ConcreteType resolver. Consumes
// the side-table populated at `compile_expr_function_call`'s
// value-call branch and returns the inferred ConcreteType
// result for closure-bound calls. Top-level conduit closes
// over `None` for the caller half of the composite key — same
// convention as `monomorph_method_returns_top`.
let value_call_sites =
self.program.value_call_return_concrete_types.clone();
let value_call_returns_top = |span: shape_ast::ast::span::Span|
-> Option<shape_value::v2::ConcreteType>
{
let ct = value_call_sites.get(&(span, None))?.clone();
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct)
}
};
// Re-run top-level conduit with the callee-return resolver so the
// `let r = divide(10, 2)` slot picks up `Result(I64, String)` from
// the Call terminator. (The first run above stamped `Void` for
// Call destinations since no resolver was available.) The
// method-returns resolver is also threaded so `t.name()`-style
// trait-method dispatch destinations pick up the trait's declared
// return ConcreteType. The V3-S6b monomorph-method resolver is
// threaded so `arr.map(...).sum()` chains have the `.map()`
// destination stamped with the specialized callee's return
// ConcreteType.
if let Some(ref mir_data) = self.program.top_level_mir {
let concrete_types =
crate::compiler::helpers::infer_top_level_concrete_types_from_mir_with_resolvers(
&mir_data.mir,
Some(&callee_returns),
Some(&method_returns),
Some(&monomorph_method_returns_top),
Some(&value_call_returns_top),
);
self.program.top_level_local_concrete_types = concrete_types;
}
// ADR-006 §2.7.5 conduit (W12-jit-aggregate-non-array close,
// 2026-05-12): same MIR-walk inference applied per user function.
// The producer (`infer_top_level_concrete_types_from_mir`) is
// generic over any MirFunction — its name is historical from the
// earlier top-level-only landing (Round 3). User-function bodies
// hit the JIT consumer at
// `crates/shape-jit/src/compiler/program.rs::compile_function_with_user_funcs`,
// which currently passes `concrete_types: Vec::new()` and therefore
// surfaces `Rvalue::Aggregate` for every `Ok(v)` / `Err(e)` /
// `Some(x)` / struct-literal construction inside a user function
// body (Smoke 1.5 `divide`, Smoke 2 `first_positive`, 28 stdlib
// helpers verified at audit time).
//
// The callee-return resolver is also threaded here so user-function
// bodies that call other user functions (e.g. `divide` calls a
// helper) propagate the helper's return ConcreteType into their
// own slot, recursing through the conduit.
//
// `ConcreteType::Void` per slot per §2.7.5.1 — NOT a Bool-default
// fallback per forbidden #9. Functions without `mir_data` get an
// empty inner vec; downstream consumers fall back to the legacy
// NaN-boxed path naturally.
let mut per_fn: Vec<Vec<shape_value::v2::ConcreteType>> =
Vec::with_capacity(self.program.functions.len());
for (fn_idx, func) in self.program.functions.iter().enumerate() {
if let Some(ref mir_data) = func.mir_data {
// ADR-006 §2.7.5 V3-S6b conduit consumer: per-fn variant
// of the monomorph-method resolver. Closes over the
// calling function's index for the composite-key lookup
// — must match the value `try_monomorphize_method_call`
// recorded in `self.current_function` at populate time
// (i.e. `Some(fn_idx)` here matches the populator's
// post-monomorphization specialized caller FunctionId).
let current_fn = Some(fn_idx);
let monomorph_method_returns_per_fn = |span: shape_ast::ast::span::Span|
-> Option<shape_value::v2::ConcreteType>
{
let idx = *monomorph_call_sites.get(&(span, current_fn))?;
let ct = returns_vec.get(idx)?;
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct.clone())
}
};
// cluster-2-cw-IB-class-b: per-fn variant of the value-call
// return-ConcreteType resolver. Same composite-key
// discipline as monomorph_method_returns_per_fn above —
// closes over `Some(fn_idx)` so calls inside user-function
// bodies pick up their own caller-context entries.
let value_call_returns_per_fn = |span: shape_ast::ast::span::Span|
-> Option<shape_value::v2::ConcreteType>
{
let ct = value_call_sites.get(&(span, current_fn))?.clone();
if matches!(ct, shape_value::v2::ConcreteType::Void) {
None
} else {
Some(ct)
}
};
let mut concrete_types =
crate::compiler::helpers::infer_top_level_concrete_types_from_mir_with_resolvers(
&mir_data.mir,
Some(&callee_returns),
Some(&method_returns),
Some(&monomorph_method_returns_per_fn),
Some(&value_call_returns_per_fn),
);
// W15.2-LANG-4 jit-filter-predicate fix (2026-05-18). Seed
// parameter slots from the function definition's parameter
// type annotations. ADR-006 §2.7.5 producer-side
// classification — the parameter's declared type IS the
// proof source for the slot's ConcreteType. Without this
// pass parameter slots stay `ConcreteType::Void`, the JIT
// side's `infer_slot_kinds_with_concrete` projects `None`,
// and `operand_slot_kind_or_carrier` falls back to the
// §2.7.5 carrier `UInt64`. For closure-typed parameters
// (e.g. `Vec.filter::i64`'s `predicate: (int) -> bool`)
// that fallback drives `jit_call_value` into the UInt64
// arm where `is_inline_function` / `is_heap_kind(_,
// HK_CLOSURE)` both fail on the raw-Arc
// `HeapValue::ClosureRaw` callee bits, surfacing the
// §2.7.5 `callee_bits stamped UInt64 but is neither
// inline function nor unified-heap HK_CLOSURE` diagnostic
// and returning TAG_NULL — visible in the wild as
// `samples.filter(|v| v > threshold)` returning the
// unfiltered receiver under JIT (book-truth
// `getting-started/first-query.mdx:41` snippet).
//
// Only seed slots whose current classification is `Void`
// (the §2.7.5.1 "no kind proven" placeholder); the
// MIR-walk inference's classifications dominate when both
// sources are present.
if let Some(def) = self.function_defs.get(&func.name) {
// v0.3 WS-7: inference-resolved per-param `ConcreteType`
// for UNANNOTATED params (projected in
// `infer_param_concrete_types_from_types`). Used as the
// seed source when a param has no annotation to read.
let inferred_param_cts =
self.inferred_param_concrete_types.get(&func.name);
for (i, ¶m_slot) in mir_data.mir.param_slots.iter().enumerate() {
let idx = param_slot.0 as usize;
if idx >= concrete_types.len() {
continue;
}
if !matches!(
concrete_types[idx],
shape_value::v2::ConcreteType::Void
) {
continue;
}
let Some(param) = def.params.get(i) else {
continue;
};
match param.type_annotation {
Some(ref ann) => {
// Annotated param: the declared type IS the
// proof source for the slot's ConcreteType.
if let Some(ct) =
crate::compiler::v2_map_emission::concrete_type_from_annotation(ann)
{
concrete_types[idx] = ct;
}
}
None => {
// v0.3 WS-7: UNANNOTATED param. The bytecode
// compiler's MIR-walk inference could not
// prove a `ConcreteType` for the slot from
// MIR-observable statements alone (it stayed
// `Void`), but the program-wide
// type-inference engine DID resolve the
// parameter's type — and the VM relies on
// that resolution (strict typing has no
// dynamic fallback). Thread the
// inference-resolved `ConcreteType` so the
// JIT's v2 typed-array / typed-object fast
// paths use the SAME proven type the VM
// uses, instead of mis-classifying a v2
// heap pointer as a NaN-boxed v1 value.
if let Some(ct) = inferred_param_cts
.and_then(|v| v.get(i))
.and_then(|opt| opt.clone())
{
concrete_types[idx] = ct;
}
}
}
}
}
per_fn.push(concrete_types);
} else {
per_fn.push(Vec::new());
}
}
self.program.function_local_concrete_types = per_fn;
// Closure-spec Phase H1: build a `function_id → ClosureLayout` side
// table for the JIT worker. `emit_heap_closure` consumes this to lay
// out captures at their natural-width offsets without going through
// the `jit_make_closure` FFI. Closure spec §14.6 (H6.5) moves this
// ABOVE `build_content_addressed_program` so the layouts propagate
// through the `ContentAddressedProgram` → `LinkedProgram` →
// `BytecodeProgram` path into the VM's producer.
//
// Track A.1C.2: the compiler derives per-capture `CaptureKind`s
// from the source binding form (see `compile_expr_closure`) and
// stores them in `closure_capture_kinds`. For each closure literal
// we rebuild the layout so the `capture_kinds` vector reflects
// those kinds AND the `owned_mutable_capture_mask` /
// `shared_capture_mask` bits are flipped for the corresponding
// capture indices. `op_make_closure` reads those masks to pick
// the per-capture allocation discipline:
// * `CaptureKind::Immutable` — write the capture bits as-is
// at the typed offset.
// * `CaptureKind::OwnedMutable` — `Box::into_raw` a fresh
// `Box<ValueWord>` around the stack value, write the pointer.
// * `CaptureKind::Shared` — the stack value carries the
// raw `*const SharedCell` pointer bits of a previously-
// promoted outer slot. `op_make_closure` does
// `Arc::increment_strong_count` to give the closure its own
// refcount share, then writes the same pointer.
//
// This was gated to "masks stay zero" during A.1C partial so the
// legacy `HeapValue::Closure + SharedCell` fallback could keep
// running while the compiler migration was incomplete. With
// A.1C.2 rerouting the outer-scope var lifecycle onto
// `AllocSharedLocal` / `LoadSharedLocal` / `StoreSharedLocal` /
// `DropSharedLocal` and the closure-body reads/writes onto
// `Load/StoreSharedCapture` and `Load/StoreOwnedMutableCapture`,
// the Raw-path guard can flip bits freely — there is no longer
// any SharedCell-wrapped ValueWord sitting on the stack at
// closure-creation time.
{
use shape_value::v2::closure_layout::{CaptureKind, ClosureLayout};
let total_fns = self.program.functions.len();
let mut layouts: Vec<Option<std::sync::Arc<ClosureLayout>>> = vec![None; total_fns];
// Map function index → per-capture CaptureKind vector.
let kinds_by_fn: std::collections::HashMap<u16, &Vec<CaptureKind>> = self
.closure_capture_kinds
.iter()
.map(|(fid, kinds)| (*fid, kinds))
.collect();
for (fn_idx, type_id) in self.closure_type_ids.iter().copied() {
if let Some(registry_layout) = self.closure_registry.get(type_id) {
if (fn_idx as usize) < total_fns {
// Track A.1C.3: authoritative per-function kinds.
// Both `Shared` AND `OwnedMutable` captures flip
// their corresponding mask bits; `op_make_closure`
// allocates `Box::into_raw(Box::new(initial))` for
// OwnedMutable slots and `Arc::into_raw(Arc::new(
// parking_lot::Mutex<ValueWord>))` / `Arc::increment_
// strong_count` for Shared slots. Module-binding
// `var` captures (migrated in A.1C.3) are also
// Shared and follow the same closure-side
// allocation discipline; the outer-scope promotion
// emits `AllocSharedModuleBinding` (vs.
// `AllocSharedLocal` for locals).
let per_fn_kinds = kinds_by_fn.get(&fn_idx);
let layout_arc = if let Some(kinds) = per_fn_kinds
&& kinds.len() == registry_layout.capture_types.len()
{
let rebuilt = ClosureLayout::from_capture_types(
®istry_layout.capture_types,
kinds,
);
// Preserve the authoritative per-capture
// `capture_kinds` for diagnostics and
// A.1D/E JIT lowering.
let mut rebuilt = rebuilt;
rebuilt.capture_kinds = (*kinds).clone();
std::sync::Arc::new(rebuilt)
} else {
std::sync::Arc::new(registry_layout.clone())
};
layouts[fn_idx as usize] = Some(layout_arc);
}
}
}
self.program.closure_function_layouts = layouts;
}
// Finalize the __main__ blob and build the content-addressed program.
self.build_content_addressed_program();
// Transfer content-addressed program to the bytecode output.
self.program.content_addressed = self.content_addressed_program.take();
if self.program.functions.is_empty() {
self.program.function_blob_hashes.clear();
} else {
if self.function_hashes_by_id.len() < self.program.functions.len() {
self.function_hashes_by_id
.resize(self.program.functions.len(), None);
} else if self.function_hashes_by_id.len() > self.program.functions.len() {
self.function_hashes_by_id
.truncate(self.program.functions.len());
}
self.program.function_blob_hashes = self.function_hashes_by_id.clone();
}
// Transfer source text for error messages
if let Some(source) = self.source_text {
// Set in legacy field for backward compatibility
self.program.debug_info.source_text = source.clone();
// Also set in source map if not already set
if self.program.debug_info.source_map.files.is_empty() {
self.program
.debug_info
.source_map
.add_file("<main>".to_string());
}
if self.program.debug_info.source_map.source_texts.is_empty() {
self.program
.debug_info
.source_map
.set_source_text(0, source);
}
}
// v0.3 Phase 4b Round 5 W17.2-A — post-inference `FieldType::Any`
// boundary verification. Per user 2026-05-18 binding ("after the
// pass, any needs to be gone, if not it is a compile time error")
// + audit §5 / §8 / §9.B.1 / §9.B.3 + user 2026-05-19 R5a 5-
// parallel ratify (transitional whitelist §4.D.1-9 + permanent
// whitelist §4.D.10-15). The verification pass walks the post-
// inference `type_schema_registry` and surfaces E0900 for any
// `FieldType::Any` outside the named-exception classes. ADR-006
// §2.7.5 (producer-side stamp) + §2.7.26 (parallel-`field_kinds`
// carrier for the permanent classes) anchor the discipline.
crate::compiler::post_inference_verify::verify_no_post_inference_any(
&self.program,
)?;
Ok(self.program)
}
/// Compile a program to bytecode with source text for error messages
pub fn compile_with_source(
mut self,
program: &Program,
source: &str,
) -> Result<BytecodeProgram> {
self.set_source(source);
self.compile(program)
}
/// Compile a program using the module graph for import resolution.
///
/// This is the graph-driven compilation pipeline. Modules compile in
/// topological order using the graph for cross-module name resolution.
/// No AST inlining occurs — each module's imports are resolved from
/// the graph's `ResolvedImport` entries.
pub fn compile_with_graph(
self,
root_program: &Program,
graph: std::sync::Arc<crate::module_graph::ModuleGraph>,
) -> Result<BytecodeProgram> {
self.compile_with_graph_and_prelude(root_program, graph, &[])
}
/// Compile with graph and prelude information.
///
/// All modules (including prelude dependencies) compile uniformly
/// through the normal module path. The `prelude_paths` parameter is
/// retained for API compatibility but no longer used.
pub fn compile_with_graph_and_prelude(
mut self,
root_program: &Program,
graph: std::sync::Arc<crate::module_graph::ModuleGraph>,
_prelude_paths: &[String],
) -> Result<BytecodeProgram> {
use crate::module_graph::ModuleSourceKind;
self.module_graph = Some(graph.clone());
// Phase 1: Compile dependency modules in topological order.
for &dep_id in graph.topo_order() {
let dep_node = graph.node(dep_id);
match dep_node.source_kind {
ModuleSourceKind::NativeModule => {
self.register_graph_imports_for_module(dep_id, &graph)?;
}
ModuleSourceKind::ShapeSource | ModuleSourceKind::Hybrid => {
self.compile_module_from_graph(dep_id, &graph)?;
}
ModuleSourceKind::CompiledBytecode => {
// Should have been rejected during graph construction.
return Err(shape_ast::error::ShapeError::ModuleError {
message: format!(
"Module '{}' is only available as pre-compiled bytecode",
dep_node.canonical_path
),
module_path: None,
});
}
}
}
// Phase 2: Compile the root module using the graph for its imports.
// NOTE: root's imports are registered INSIDE `compile()` after the
// `__main__` blob builder starts, so any emitted Load/Store for
// namespace-alias bindings (e.g. `use std::core::set` creates a
// runtime copy from canonical binding `std::core::set` to alias
// binding `set`) lands inside `__main__`. Registering them here —
// before `compile()` opens the `__main__` blob — would leave those
// instructions in an unreachable gap between module bodies and
// `__main__`'s entry point.
// Strip import items from root program (imports already resolved via graph)
let mut stripped_program = root_program.clone();
stripped_program
.items
.retain(|item| !matches!(item, shape_ast::ast::Item::Import(..)));
// Compile the stripped root program using the standard two-pass pipeline
self.compile(&stripped_program)
}
/// Compile a single module from the graph.
///
/// All modules (including prelude dependencies) compile uniformly:
/// pushes the module scope, qualifies items, registers all symbol kinds,
/// compiles bodies, creates module binding object.
fn compile_module_from_graph(
&mut self,
module_id: crate::module_graph::ModuleId,
graph: &crate::module_graph::ModuleGraph,
) -> Result<()> {
let node = graph.node(module_id);
let ast = match &node.ast {
Some(ast) => ast.clone(),
None => return Ok(()), // NativeModule / CompiledBytecode
};
let module_path = node.canonical_path.clone();
// All modules compile uniformly through the normal module path.
// Set allow_internal_builtins for stdlib modules.
let prev_allow = self.allow_internal_builtins;
if module_path.starts_with("std::") {
self.allow_internal_builtins = true;
}
self.module_scope_stack.push(module_path.clone());
// 1. Register this module's imports from the graph
self.register_graph_imports_for_module(module_id, graph)?;
// 2. Filter out import statements, qualify remaining items
let mut qualified_items = Vec::new();
for item in &ast.items {
if matches!(item, shape_ast::ast::Item::Import(..)) {
continue;
}
qualified_items.push(self.qualify_module_item(item, &module_path)?);
}
// 3. Phase 1: Register functions in global table with qualified names
for item in &qualified_items {
self.register_missing_module_items(item)?;
}
// 4. Phase 2: Compile function bodies
self.non_function_mir_context_stack
.push(module_path.clone());
let compile_result = (|| -> Result<()> {
for (idx, qualified) in qualified_items.iter().enumerate() {
let future_names = self
.future_reference_use_names_for_remaining_items(&qualified_items[idx + 1..]);
self.push_future_reference_use_names(future_names);
let result = self.compile_item_with_context(qualified, false);
self.pop_future_reference_use_names();
result?;
self.release_unused_module_reference_borrows_for_remaining_items(
&qualified_items[idx + 1..],
);
}
Ok(())
})();
self.non_function_mir_context_stack.pop();
compile_result?;
// 5. Build module object and store in canonical binding
let exports = self.collect_module_runtime_exports(
&ast.items
.iter()
.filter(|i| !matches!(i, shape_ast::ast::Item::Import(..)))
.cloned()
.collect::<Vec<_>>(),
&module_path,
);
let span = shape_ast::ast::Span::default();
let entries: Vec<shape_ast::ast::ObjectEntry> = exports
.into_iter()
.map(|(name, value_ident)| shape_ast::ast::ObjectEntry::Field {
key: name,
value: shape_ast::ast::Expr::Identifier(value_ident, span),
type_annotation: None,
})
.collect();
let module_object = shape_ast::ast::Expr::Object(entries, span);
self.compile_expr(&module_object)?;
let binding_idx = self.get_or_create_module_binding(&module_path);
self.emit(Instruction::new(
OpCode::StoreModuleBinding,
Some(Operand::ModuleBinding(binding_idx)),
));
self.propagate_initializer_type_to_slot(binding_idx, false, false);
self.module_scope_stack.pop();
self.allow_internal_builtins = prev_allow;
Ok(())
}
/// Compile an imported module's AST to a standalone BytecodeProgram.
///
/// This takes the Module's AST (Program), compiles all exported functions
/// to bytecode, and returns the compiled program along with a mapping of
/// exported function names to their function indices in the compiled output.
///
/// The returned `BytecodeProgram` and function name mapping allow the import
/// handler to resolve imported function calls to the correct bytecode indices.
///
/// Currently handles function exports only. Types and values can be added later.
pub fn compile_module_ast(
module_ast: &Program,
) -> Result<(BytecodeProgram, HashMap<String, usize>)> {
let mut compiler = BytecodeCompiler::new();
// Stdlib modules need access to __* builtins (intrinsics, into, etc.)
compiler.allow_internal_builtins = true;
let bytecode = compiler.compile(module_ast)?;
// Build name → function index mapping for exported functions
let mut export_map = HashMap::new();
for (idx, func) in bytecode.functions.iter().enumerate() {
export_map.insert(func.name.clone(), idx);
}
Ok((bytecode, export_map))
}
}