1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
//! Binary operation expression compilation
use crate::bytecode::{Instruction, NumericWidth, OpCode, Operand};
use crate::type_tracking::{NumericType, VariableTypeInfo};
use shape_ast::ast::operators::{FuzzyOp, FuzzyTolerance};
use shape_ast::ast::{BinaryOp, Expr, Literal, Span, Spanned, UnaryOp};
use shape_ast::error::{Result, ShapeError};
use shape_runtime::type_schema::{FieldType, SchemaId};
use super::super::BytecodeCompiler;
use super::numeric_ops::{
CoercionPlan, apply_coercion, inferred_type_to_numeric, is_function_type,
is_ordered_comparison, is_strict_arithmetic, is_type_numeric, plan_coercion,
type_display_name, typed_opcode_for,
};
/// Map a BinaryOp to its operator trait name, if one exists.
///
/// R5.2B: `Add` is included so `try_emit_trait_dispatch` covers the Add
/// branch's `CoercedNeedsGeneric | NoPlan` fallback uniformly with the
/// strict-arithmetic path. The other three strict-arithmetic callers
/// (L1092, L1192, L1229) are gated by `is_strict_arithmetic(op)` which
/// excludes Add, so they remain unaffected.
fn operator_trait_for_op(op: &BinaryOp) -> Option<&'static str> {
match op {
BinaryOp::Add => Some("Add"),
BinaryOp::Sub => Some("Sub"),
BinaryOp::Mul => Some("Mul"),
BinaryOp::Div => Some("Div"),
BinaryOp::Mod => Some("Mod"),
BinaryOp::BitAnd => Some("BitAnd"),
BinaryOp::BitOr => Some("BitOr"),
BinaryOp::BitXor => Some("BitXor"),
BinaryOp::BitShl => Some("Shl"),
BinaryOp::BitShr => Some("Shr"),
BinaryOp::Greater | BinaryOp::Less | BinaryOp::GreaterEq | BinaryOp::LessEq => {
Some("Ord")
}
// W1.7: Eq/Neq dispatch for user-defined types. Built-in
// scalar types take typed `EqInt`/`EqString`/... before this
// mapping is consulted (`compile_typed_equality` resolves
// operand types via `resolve_eq_type` and emits typed opcodes
// first; only when both operands lack a recognised primitive
// shape does the user-type Eq dispatch fire).
BinaryOp::Equal | BinaryOp::NotEqual => Some("Eq"),
_ => None, // Pow has no operator trait
}
}
/// Map a binary op to the user-facing trait method name (lowercase).
/// Used by Phase 2.5 to emit `CallMethod("add"/"sub"/...)` for operator
/// overloading on user-defined types. The runtime dispatches via
/// `function_name_index["{Type}::{method}"]` (see `op_call_method` →
/// `handle_typed_object_method`).
fn operator_trait_method_for_op(op: &BinaryOp) -> Option<&'static str> {
match op {
BinaryOp::Add => Some("add"),
BinaryOp::Sub => Some("sub"),
BinaryOp::Mul => Some("mul"),
BinaryOp::Div => Some("div"),
BinaryOp::Mod => Some("mod"),
BinaryOp::BitAnd => Some("bitand"),
BinaryOp::BitOr => Some("bitor"),
BinaryOp::BitXor => Some("bitxor"),
BinaryOp::BitShl => Some("shl"),
BinaryOp::BitShr => Some("shr"),
BinaryOp::Greater | BinaryOp::Less | BinaryOp::GreaterEq | BinaryOp::LessEq => {
Some("cmp")
}
// W1.7: `Eq::eq(self, other) -> bool`. Both `==` and `!=` map
// to the same method; the negation for `!=` is emitted by the
// caller (`compile_typed_equality`) after the dispatch.
BinaryOp::Equal | BinaryOp::NotEqual => Some("eq"),
_ => None,
}
}
fn emit_cmp_result_comparison(compiler: &mut BytecodeCompiler, op: &BinaryOp) {
use crate::bytecode::Constant;
let zero_idx = compiler.program.add_constant(Constant::Int(0));
compiler.emit(Instruction::new(OpCode::PushConst, Some(Operand::Const(zero_idx))));
let cmp_op = match op {
BinaryOp::Greater => OpCode::GtInt,
BinaryOp::Less => OpCode::LtInt,
BinaryOp::GreaterEq => OpCode::GteInt,
BinaryOp::LessEq => OpCode::LteInt,
_ => unreachable!(),
};
compiler.emit(Instruction::simple(cmp_op));
}
fn try_emit_trait_dispatch(compiler: &mut BytecodeCompiler, op: &BinaryOp, left_schema: Option<SchemaId>, left_expr: &Expr, op_span: Span) -> bool {
let trait_name = match operator_trait_for_op(op) { Some(t) => t, None => return false };
let method_name = match operator_trait_method_for_op(op) { Some(m) => m, None => return false };
let has_trait_via_schema = left_schema
.and_then(|sid| compiler.type_tracker.schema_registry().get_by_id(sid))
.is_some_and(|schema| compiler.type_inference.env.type_implements_trait(&schema.name, trait_name));
let has_trait = has_trait_via_schema || compiler.infer_expr_type(left_expr).ok().is_some_and(|ty| {
let name = type_display_name(&ty);
compiler.type_inference.env.type_implements_trait(&name, trait_name)
});
if !has_trait { return false; }
emit_operator_trait_call(compiler, method_name, op_span);
if is_ordered_comparison(op) { emit_cmp_result_comparison(compiler, op); }
true
}
/// Emit a `CallMethod` instruction targeting an operator trait method
/// (e.g. `Vec2::add`). Both operands must already be on the stack: receiver
/// first, then the right-hand-side argument.
///
/// `op_span` is the source span of the parent `Expr::BinaryOp` /
/// `Expr::UnaryOp` node. W10 jit-call-method-user-trait-fix (2026-05-17):
/// records the dispatch in `BytecodeProgram.operator_trait_dispatch_sites`
/// so the JIT MIR consumer at `crates/shape-jit/src/mir_compiler/rvalues.
/// rs::compile_rvalue` can re-emit the same dispatch at the matching
/// `Rvalue::BinaryOp` / `Rvalue::UnaryOp` site (keyed by the same span
/// the MIR lowering at `crates/shape-vm/src/mir/lowering/expr.rs::
/// lower_expr_to_temp` stamps on the statement via `expr.span()`).
fn emit_operator_trait_call(compiler: &mut BytecodeCompiler, method_name: &'static str, op_span: Span) {
let method_id = shape_value::MethodId::from_name(method_name);
let string_id = compiler.program.add_string(method_name.to_string());
compiler.emit(Instruction::new(
OpCode::CallMethod,
Some(Operand::TypedMethodCall {
method_id: method_id.0,
arg_count: 1,
string_id,
receiver_type_tag: 0xFF, }),
));
// ADR-006 §2.7.5 W10 conduit: persist the bytecode-time trait-dispatch
// decision so the JIT MIR consumer can lift `Rvalue::BinaryOp` at the
// same source span to a method-call equivalent. arg_count = 1 (binary
// ops dispatch a single explicit RHS argument; receiver is implicit).
compiler
.program
.operator_trait_dispatch_sites
.insert(op_span, (method_name.to_string(), 1));
compiler.last_expr_schema = None;
compiler.last_expr_type_info = None;
compiler.last_expr_numeric_type = None;
}
fn combined_span(left: &Expr, right: &Expr) -> Span {
let ls = left.span();
let rs = right.span();
Span::new(ls.start.min(rs.start), ls.end.max(rs.end))
}
/// Strict-typing sweep (Phase 1): produce a `ShapeError::SemanticError`
/// for a binary operation whose operand types could not be proven at
/// compile time. Replaces the former `*Dynamic`-emission shim
/// (`emit_generic_via_helper` and direct `emit_binary_op(... Unknown,
/// Unknown)` calls).
///
/// The error includes the operator symbol, both operand types (as
/// inferred — falling back to `"unknown"` when inference declines), and a
/// span covering both operands so editors can underline the offending
/// expression.
fn strict_typing_binop_error(
compiler: &mut BytecodeCompiler,
op: &BinaryOp,
left: &Expr,
right: &Expr,
) -> ShapeError {
let lhs_type = compiler
.infer_expr_type(left)
.map(|t| type_display_name(&t))
.unwrap_or_else(|_| "unknown".to_string());
let rhs_type = compiler
.infer_expr_type(right)
.map(|t| type_display_name(&t))
.unwrap_or_else(|_| "unknown".to_string());
ShapeError::SemanticError {
message: format!(
"Cannot infer types for binary operation `{:?}`: operand types are `{}` and `{}`. \
Strict typing requires both operands to have a known concrete type at compile time. \
Add a type annotation to disambiguate.",
op, lhs_type, rhs_type
),
location: Some(compiler.span_to_source_location(combined_span(left, right))),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NumericEmitResult {
EmittedTyped,
CoercedNeedsGeneric,
NoPlan,
}
/// Simplified type category for equality dispatch.
/// Collapses int-width variants to `Int` and char to `String` (EqString
/// handles both heap-boxed string and char values via `as_str()`).
///
/// WS-8 (2026-05-22): `Bool` added — `bool == bool` lowers to `EqInt`
/// (bools are 0/1 bits, so bitwise comparison is correct). Pre-WS-8 the
/// missing bool arm fell through to `Eq`-trait dispatch which surfaced
/// `no method 'eq' on receiver kind Bool` for both direct `a == b` and
/// for `vec.shape`'s generic `.includes`/`.indexOf` that compare bool
/// elements element-by-element.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EqOperandType {
Int,
Number,
Decimal,
String,
Bool,
}
impl BytecodeCompiler {
/// ε-1 PART 1 — emit-side soundness guard.
///
/// Returns a `ProofGap`-derived compile error when a typed numeric opcode
/// is about to be emitted for `operand` (its `numeric` hint is `Some`, so
/// a typed opcode WOULD fire) but the operand's actual compile-time type
/// is still an unresolved `Type::Variable`/`Type::Constrained`.
///
/// That combination means the `NumericType` claim is *fabricated* — no
/// signal proved the kind, so emitting `MulInt`/`MulNumber`/... would
/// stamp a default kind on a value of unknown type (the exact silent-wrong
/// path that reinterpreted the integer `40` as the denormal `2e-321`).
///
/// Restricted to identifiers bound to an *untyped function parameter slot*
/// with no tracker type info: those are the only operands whose numeric
/// hint can be set without a proving signal (literals, typed locals and
/// for-loop variables all carry a real proven kind). This keeps the guard
/// from false-positiving on ordinary well-typed code.
fn numeric_operand_proof_gap(
&mut self,
op: &BinaryOp,
operand: &Expr,
numeric: Option<NumericType>,
) -> Option<ShapeError> {
// No typed opcode would fire for this operand → nothing to prove.
numeric?;
let Expr::Identifier(name, _) = operand else {
return None;
};
let local_idx = self.resolve_local(name)?;
// Only untyped function parameters can carry an unproven numeric hint.
if !self.param_locals.contains(&local_idx) {
return None;
}
// A param with concrete tracker type info has a proven kind.
if let Some(info) = self.type_tracker.get_local_type(local_idx) {
if info.type_name.is_some() || info.storage_hint.is_some() {
return None;
}
}
// The decisive check: ask the inference engine for the operand's
// resolved type. A bare unresolved variable (or still-bounded
// constrained variable) is an unprovable kind.
let inferred = self.infer_expr_type(operand).ok()?;
if !matches!(
inferred,
shape_runtime::type_system::Type::Variable(_)
| shape_runtime::type_system::Type::Constrained { .. }
) {
return None;
}
let gap = crate::type_tracking::proof_gap_unresolved_operand(
"emit_typed_arithmetic",
format!(
"operand `{}` of `{:?}` has an unresolved type — no signal \
proves its NativeKind, so a typed numeric opcode cannot be \
emitted. Add a type annotation to the parameter.",
name, op
),
);
Some(ShapeError::SemanticError {
message: gap.to_string(),
location: Some(self.span_to_source_location(operand.span())),
})
}
fn infer_numeric_pair(
&mut self,
left: &Expr,
right: &Expr,
) -> (Option<NumericType>, Option<NumericType>) {
let inferred_left = self
.infer_expr_type(left)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
let inferred_right = self
.infer_expr_type(right)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
(inferred_left, inferred_right)
}
fn adopt_missing_numeric_operand_hint(
&mut self,
left: &Expr,
right: &Expr,
left_numeric: &mut Option<NumericType>,
right_numeric: &mut Option<NumericType>,
) {
if let (Some(known), None) = (*left_numeric, *right_numeric)
&& matches!(right, Expr::Identifier(..) | Expr::IndexAccess { .. })
&& self.last_expr_schema.is_none()
{
// Adopt Int only if the identifier has a confirmed Int type.
// Otherwise promote to Number to avoid misclassifying floats as ints.
let safe = self.safe_adopt_numeric_hint(right, known);
// Only adopt if the type didn't change (confirmed match).
// If safe != known, skip adoption — let the operation fall through
// to inference or generic opcodes that handle mixed types at runtime.
if safe == known {
*right_numeric = Some(safe);
self.seed_numeric_hint_from_expr(right, safe);
}
return;
}
if let (None, Some(known)) = (*left_numeric, *right_numeric)
&& matches!(left, Expr::Identifier(..) | Expr::IndexAccess { .. })
{
// Do not adopt a numeric hint for identifiers that are typed objects.
let has_object_schema = if let Expr::Identifier(name, _) = left {
self.resolve_local(name)
.and_then(|idx| self.type_tracker.get_local_type(idx))
.and_then(|info| info.schema_id)
.is_some()
} else {
false
};
if !has_object_schema {
let safe = self.safe_adopt_numeric_hint(left, known);
// Only adopt if the type didn't change (confirmed match).
if safe == known {
*left_numeric = Some(safe);
self.seed_numeric_hint_from_expr(left, safe);
}
}
}
}
/// When adopting a numeric hint from one operand to another, check if adopting
/// Int is safe. If the target identifier has no confirmed Int type from the
/// type tracker, promote to Number to avoid emitting Int-typed opcodes for
/// values that may actually be floats at runtime.
fn safe_adopt_numeric_hint(&self, expr: &Expr, hint: NumericType) -> NumericType {
if hint != NumericType::Int {
return hint;
}
// Check if the identifier has a confirmed numeric type
if let Expr::Identifier(name, _) = expr {
if let Some(local_idx) = self.resolve_local(name) {
if let Some(info) = self.type_tracker.get_local_type(local_idx) {
// Post-§2.7.5.1: `info.storage_hint` is
// `Option<StorageHint>`; `Some(Int64)` is the proven-Int
// case, anything else (including `None` for
// not-yet-proven) falls through to the safe Number path.
if info.storage_hint == Some(crate::type_tracking::StorageHint::Int64) {
return NumericType::Int;
}
}
}
}
// For unconfirmed types, use Number (safe for both int and float values)
NumericType::Number
}
/// Returns `true` when the expression is syntactically guaranteed to be numeric.
/// This does NOT consult the type tracker — it only looks at the AST node itself.
fn is_expr_confirmed_numeric(expr: &Expr) -> bool {
match expr {
Expr::Literal(Literal::Int(_), _)
| Expr::Literal(Literal::Number(_), _)
| Expr::Literal(Literal::TypedInt(..), _)
| Expr::Literal(Literal::UInt(_), _)
| Expr::Literal(Literal::Decimal(_), _) => true,
Expr::UnaryOp {
op: UnaryOp::Neg,
operand,
..
} => Self::is_expr_confirmed_numeric(operand),
_ => false,
}
}
/// If `expr` is a bare integer literal (`Literal::Int` / `Literal::UInt`),
/// return its value (`Literal::UInt` always non-negative). `None` for any
/// non-literal expression.
///
/// `Literal::TypedInt` is excluded: an explicitly-suffixed literal
/// (`5i32`, `7u8`) has a declared width that the programmer chose; it
/// does not adapt.
fn bare_int_literal_value(expr: &Expr) -> Option<i128> {
match expr {
Expr::Literal(Literal::Int(v), _) => Some(*v as i128),
Expr::Literal(Literal::UInt(v), _) => Some(*v as i128),
_ => None,
}
}
/// Returns `true` when a bare integer literal of value `v` can soundly
/// adopt the integer width `w` of a sibling operand. A negative literal
/// cannot adopt an unsigned width (it has no representation there);
/// every other case is allowed — sub-range overflow truncates per the
/// two's-complement wrapping semantics that `let x: i8 = 1000` already
/// applies (2026-05-20 integer-semantics ruling #3).
fn int_literal_fits_width(v: i128, w: shape_ast::IntWidth) -> bool {
!(v < 0 && !w.is_signed())
}
/// ADR-006 §2.7.5 stamp-at-compile-time — int-literal width inference.
///
/// A bare integer literal is width-polymorphic: as an operand of a
/// width-typed binary op it must be inferred and kind-stamped with the
/// sibling's width, exactly as it would be when bound to a width
/// annotation (`let x: u64 = 2`, `let y: i8 = 28`). When one operand
/// carries `NumericType::IntWidth(W)` and the other is a bare integer
/// literal currently classified as the default `NumericType::Int`,
/// promote the literal to `IntWidth(W)` so `plan_coercion` keeps the
/// operation on `W`'s carrier (`AddTyped`/`DivTyped`/... with the
/// matching `NumericWidth`) instead of widening to the signed default
/// `i64` `NumericType::Int`.
///
/// Without this, `plan_coercion(IntWidth(W), Int)` returns
/// `NoCoercion(Int)`: `a / 2` on `a: u64` emits the signed `DivInt`
/// (`u64::MAX / 2` computes `(-1) / 2 == 0`), and `x + 28` on `x: i8`
/// emits `AddInt` (`100 + 28 == 128` instead of the wrapped `-128`).
///
/// Only the literal side is promoted; a genuinely width-typed sibling
/// (`let b: int = 3; a / b`) is left untouched (its `Int` hint stands).
fn promote_int_literal_to_width_sibling(
left: &Expr,
right: &Expr,
left_numeric: &mut Option<NumericType>,
right_numeric: &mut Option<NumericType>,
) {
if let (Some(NumericType::IntWidth(w)), Some(NumericType::Int)) =
(*left_numeric, *right_numeric)
{
if let Some(v) = Self::bare_int_literal_value(right) {
if Self::int_literal_fits_width(v, w) {
*right_numeric = Some(NumericType::IntWidth(w));
}
}
} else if let (Some(NumericType::Int), Some(NumericType::IntWidth(w))) =
(*left_numeric, *right_numeric)
{
if let Some(v) = Self::bare_int_literal_value(left) {
if Self::int_literal_fits_width(v, w) {
*left_numeric = Some(NumericType::IntWidth(w));
}
}
}
}
/// Get the compile-time StorageHint for an expression, if it can be determined.
///
/// Only returns a hint for identifiers that are immutable (`let` bindings),
/// since mutable variables (`var`) can be modified through reference parameters
/// (DerefStore) and their runtime type may diverge from the tracker's static view.
fn storage_hint_for_expr(&self, expr: &Expr) -> Option<crate::type_tracking::StorageHint> {
match expr {
Expr::Identifier(name, _) => {
let local_idx = self.resolve_local(name)?;
// Don't trust storage hints for function parameters with no explicit
// type annotation — their inferred types (from inferred_param_type_hints)
// can be wrong (e.g., a string param inferred as numeric → B19).
if self.param_locals.contains(&local_idx) {
return None;
}
let info = self.type_tracker.get_local_type(local_idx)?;
// Per ADR-006 §2.7.5.1, `NativeKind::Unknown` was deleted —
// the in-memory analysis state for "not yet known" is held
// as `Option<StorageHint>` on `info.storage_hint` itself.
// Returning that field flat propagates `None` (not yet
// proven) through this getter's `Option` return type.
info.storage_hint
}
Expr::Literal(Literal::Int(_), _) => Some(crate::type_tracking::StorageHint::Int64),
Expr::Literal(Literal::Number(_), _) => {
Some(crate::type_tracking::StorageHint::Float64)
}
_ => None,
}
}
#[allow(dead_code)]
fn emit_numeric_binary_with_coercion(
&mut self,
op: &BinaryOp,
left_numeric: Option<NumericType>,
right_numeric: Option<NumericType>,
is_comparison: bool,
) -> NumericEmitResult {
self.emit_numeric_binary_with_coercion_inner(
op,
left_numeric,
right_numeric,
is_comparison,
None,
None,
)
}
fn emit_numeric_binary_with_coercion_trusted(
&mut self,
op: &BinaryOp,
left_numeric: Option<NumericType>,
right_numeric: Option<NumericType>,
is_comparison: bool,
left_expr: &Expr,
right_expr: &Expr,
) -> NumericEmitResult {
let lhs_hint = self.storage_hint_for_expr(left_expr);
let rhs_hint = self.storage_hint_for_expr(right_expr);
self.emit_numeric_binary_with_coercion_inner(
op,
left_numeric,
right_numeric,
is_comparison,
lhs_hint,
rhs_hint,
)
}
fn emit_numeric_binary_with_coercion_inner(
&mut self,
op: &BinaryOp,
left_numeric: Option<NumericType>,
right_numeric: Option<NumericType>,
is_comparison: bool,
_lhs_hint: Option<crate::type_tracking::StorageHint>,
_rhs_hint: Option<crate::type_tracking::StorageHint>,
) -> NumericEmitResult {
let Some(plan) = plan_coercion(left_numeric, right_numeric) else {
return NumericEmitResult::NoPlan;
};
// u64 + signed is a compile error — must use explicit `as` cast
if let CoercionPlan::IncompatibleWidths(a, b) = plan {
self.errors
.push(shape_ast::error::ShapeError::SemanticError {
message: format!(
"cannot mix `{}` and `{}` in arithmetic — use an explicit `as` cast",
a.type_name(),
b.type_name()
),
location: None,
});
return NumericEmitResult::NoPlan;
}
let result_type = apply_coercion(self, plan);
if let Some(opcode) = typed_opcode_for(op, result_type) {
// Compact typed opcodes (AddTyped, etc.) need Width operand
if let NumericType::IntWidth(w) = result_type {
self.emit(Instruction::new(
opcode,
Some(Operand::Width(NumericWidth::from_int_width(w))),
));
} else {
self.emit(Instruction::simple(opcode));
}
// After a typed comparison, the result is a bool — record
// that in `last_expr_type_info` so the implicit-return path
// (`emit_return_value_with_ownership` →
// `last_expr_numeric_type_to_storage_hint`) routes to
// `ReturnValueBool`. Without this, the post-comparison
// `last_expr_*` state is `None`/`None`, the implicit return
// emits the legacy untyped `ReturnValue`, and `last_program_
// return_kind` stays `None` — so the host-boundary synthesizer
// falls back to passthrough on raw native 0u64/1u64 bits and
// `as_bool()` returns `None`.
if is_comparison {
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::with_storage(
"bool".to_string(),
crate::type_tracking::StorageHint::Bool,
),
);
} else {
self.last_expr_type_info = None;
}
self.last_expr_numeric_type = if is_comparison {
None
} else {
Some(result_type)
};
NumericEmitResult::EmittedTyped
} else {
NumericEmitResult::CoercedNeedsGeneric
}
}
/// Phase 2.6.5.3/4: inference-driven typed equality dispatch.
///
/// Architectural shift: resolve operand types from multiple sources
/// BEFORE compiling them, then pick the typed `Eq*`/`Neq*` opcode.
///
/// Type resolution priority:
/// 1. Type inference engine (`infer_expr_type`)
/// 2. AST literal type (for `Literal::Int`, `Literal::String`, etc.)
/// 3. Asymmetric propagation: if one side is typed and the other is not,
/// assume both sides have the same type. This is safe because typed
/// comparison opcodes return false for mismatched runtime types.
///
/// Returns `Ok(true)` if a typed opcode was emitted, `Ok(false)` to
/// fall through to the legacy slot-tracker dispatch.
fn compile_typed_equality(
&mut self,
op: &BinaryOp,
left: &Expr,
right: &Expr,
op_span: Span,
) -> Result<bool> {
if !matches!(op, BinaryOp::Equal | BinaryOp::NotEqual) {
return Ok(false);
}
let is_neq = matches!(op, BinaryOp::NotEqual);
// Desugar `x == None` / `None == x` to IsNull(x).
// This covers Option<T> comparisons and any None-literal equality.
if matches!(right, Expr::Literal(Literal::None, _)) {
self.compile_expr(left)?;
self.emit(Instruction::simple(OpCode::IsNull));
if is_neq {
self.emit(Instruction::simple(OpCode::Not));
}
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(true);
}
if matches!(left, Expr::Literal(Literal::None, _)) {
self.compile_expr(right)?;
self.emit(Instruction::simple(OpCode::IsNull));
if is_neq {
self.emit(Instruction::simple(OpCode::Not));
}
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(true);
}
// Resolve operand types from inference + literal fallback.
let mut lhs_eq = self.resolve_eq_type(left);
let mut rhs_eq = self.resolve_eq_type(right);
// Asymmetric propagation: if one side is typed and the other is not,
// propagate the known type. For `x == 5` where x is an untracked
// loop counter, the literal 5 tells us to use EqInt.
if lhs_eq.is_none() && rhs_eq.is_some() {
lhs_eq = rhs_eq;
} else if rhs_eq.is_none() && lhs_eq.is_some() {
rhs_eq = lhs_eq;
}
// Pick the typed opcode and whether to negate after.
// EqString/EqDecimal have no Neq variants → emit Eq + Not for NotEqual.
// EqInt/EqNumber have NeqInt/NeqNumber variants → use them directly.
let emission = match (lhs_eq, rhs_eq) {
(Some(EqOperandType::Int), Some(EqOperandType::Int)) => Some(if is_neq {
(OpCode::NeqInt, false)
} else {
(OpCode::EqInt, false)
}),
(Some(EqOperandType::Number), Some(EqOperandType::Number)) => Some(if is_neq {
(OpCode::NeqNumber, false)
} else {
(OpCode::EqNumber, false)
}),
(Some(EqOperandType::Decimal), Some(EqOperandType::Decimal)) => {
Some((OpCode::EqDecimal, is_neq))
}
(Some(EqOperandType::String), Some(EqOperandType::String)) => {
Some((OpCode::EqString, is_neq))
}
// WS-8 (2026-05-22): bool == bool lowers to EqInt — bools carry
// 0/1 bits on the §2.7.7 parallel-kind track and EqInt compares
// raw 64-bit slot bits, so the bitwise comparison is correct for
// bool values regardless of which slot bits represent {true,
// false}. Routes through the existing typed integer opcode
// without introducing a per-kind PHF entry. Result kind is
// already Bool downstream.
(Some(EqOperandType::Bool), Some(EqOperandType::Bool)) => Some(if is_neq {
(OpCode::NeqInt, false)
} else {
(OpCode::EqInt, false)
}),
_ => None,
};
if let Some((opcode, needs_negate)) = emission {
self.compile_expr(left)?;
self.compile_expr(right)?;
self.emit(Instruction::simple(opcode));
if needs_negate {
self.emit(Instruction::simple(OpCode::Not));
}
self.last_expr_schema = None;
// Result is bool — record so the implicit-return path
// emits `ReturnValueBool` and the host-boundary synthesizer
// re-tags the raw native bool bits.
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::with_storage(
"bool".to_string(),
crate::type_tracking::StorageHint::Bool,
),
);
self.last_expr_numeric_type = None;
return Ok(true);
}
// Strict-typing-sweep: cross-numeric-kind equality where one side
// is a literal int (e.g. `mean_val == 0` with `mean_val: number`).
// Symmetric to plan_coercion's CoerceLeft / CoerceRight rules in
// numeric_ops.rs, just for equality ops. This is the same
// literal-int-into-number coercion arithmetic already does and
// doesn't introduce a new fallback path: the resulting opcode is
// a typed `EqNumber`/`NeqNumber`, not a Dynamic.
let cross_emission = match (lhs_eq, rhs_eq) {
(Some(EqOperandType::Number), Some(EqOperandType::Int))
if matches!(right, Expr::Literal(Literal::Int(_), _)) =>
{
Some((OpCode::EqNumber, true /* coerce_right_int_to_number */))
}
(Some(EqOperandType::Int), Some(EqOperandType::Number))
if matches!(left, Expr::Literal(Literal::Int(_), _)) =>
{
Some((OpCode::EqNumber, false /* coerce_left_int_to_number */))
}
_ => None,
};
if let Some((opcode, coerce_right)) = cross_emission {
self.compile_expr(left)?;
if !coerce_right {
self.emit(Instruction::simple(OpCode::IntToNumber));
}
self.compile_expr(right)?;
if coerce_right {
self.emit(Instruction::simple(OpCode::IntToNumber));
}
// EqNumber → NeqNumber via Not when needed.
let final_op = if is_neq { OpCode::NeqNumber } else { opcode };
self.emit(Instruction::simple(final_op));
self.last_expr_schema = None;
// Result is bool — record so the implicit-return path
// emits `ReturnValueBool` and the host-boundary synthesizer
// re-tags the raw native bool bits.
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::with_storage(
"bool".to_string(),
crate::type_tracking::StorageHint::Bool,
),
);
self.last_expr_numeric_type = None;
return Ok(true);
}
// W1.7: user-defined `impl Eq for X` dispatch. Mirrors the
// arithmetic-trait retargets at L1461-1475 / L1493 / L1512.
// `compile_typed_equality` runs BEFORE either operand has been
// compiled, so `last_expr_schema` reflects whatever the previous
// expression left behind — not the left operand's schema. We
// therefore consult three sources in order of decreasing
// certainty: the slot tracker's `local_types` schema-id for an
// identifier, the slot tracker's `binding_types` for a module
// binding, and finally the inference engine (mirrors the second
// half of `try_emit_trait_dispatch` at L88).
//
// For `!=` an extra `Not` opcode follows so user code only
// authors `eq`. No separate `Neq` trait — Shape mirrors Rust's
// single-method shape (`PartialEq::eq` + auto-derived `!=`).
let trait_name = "Eq";
let slot_type_name: Option<String> = if let Expr::Identifier(name, _) = left {
if let Some(slot) = self.resolve_local(name) {
self.type_tracker
.get_local_type(slot)
.and_then(|info| info.type_name.clone())
} else if let Some(slot) = self.module_bindings.get(name).copied() {
self.type_tracker
.get_binding_type(slot)
.and_then(|info| info.type_name.clone())
} else {
None
}
} else {
None
};
let mut has_eq_impl = slot_type_name
.as_ref()
.is_some_and(|name| self.type_inference.env.type_implements_trait(name, trait_name));
if !has_eq_impl {
has_eq_impl = self.infer_expr_type(left).ok().is_some_and(|ty| {
let name = type_display_name(&ty);
self.type_inference
.env
.type_implements_trait(&name, trait_name)
});
}
if has_eq_impl {
self.compile_expr(left)?;
self.compile_expr(right)?;
emit_operator_trait_call(self, "eq", op_span);
if is_neq {
self.emit(Instruction::simple(OpCode::Not));
}
// Eq::eq returns bool — match the typed-equality path's
// type_info bookkeeping so the implicit-return path emits
// `ReturnValueBool` and the host-boundary synthesizer
// re-tags the raw native bool bits.
self.last_expr_schema = None;
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::with_storage(
"bool".to_string(),
crate::type_tracking::StorageHint::Bool,
),
);
self.last_expr_numeric_type = None;
return Ok(true);
}
// Strict-typing sweep (Phase 1): the typed-equality dispatch above
// declined for both operands, which historically routed through the
// `emit_binary_op` shim with `BinOperandKind::Unknown` operands and
// emitted `EqDynamic` / `NeqDynamic`. That dynamic-fallback path is
// now a hard compile error.
let typed_op = if is_neq { BinaryOp::NotEqual } else { BinaryOp::Equal };
Err(strict_typing_binop_error(self, &typed_op, left, right))
}
/// Resolve the equality-relevant type of an expression from multiple
/// sources: inference engine, then AST literal kind.
fn resolve_eq_type(&mut self, expr: &Expr) -> Option<EqOperandType> {
// Source 1: type inference engine
if let Ok(ty) = self.infer_expr_type(expr) {
if let Some(nt) = inferred_type_to_numeric(&ty) {
return Some(match nt {
NumericType::Int | NumericType::IntWidth(_) => EqOperandType::Int,
NumericType::Number => EqOperandType::Number,
NumericType::Decimal => EqOperandType::Decimal,
});
}
let name = type_display_name(&ty);
match name.as_str() {
"string" | "char" => return Some(EqOperandType::String),
// WS-8 (2026-05-22): bool inferred type lights up the
// typed-equality fast path (EqInt over bool bits).
"bool" => return Some(EqOperandType::Bool),
_ => {}
}
}
// Source 2: AST literal type
match expr {
Expr::Literal(Literal::Int(_) | Literal::UInt(_) | Literal::TypedInt(..), _) => {
Some(EqOperandType::Int)
}
Expr::Literal(Literal::Number(_), _) => Some(EqOperandType::Number),
Expr::Literal(Literal::Decimal(_), _) => Some(EqOperandType::Decimal),
Expr::Literal(Literal::String(_), _) => Some(EqOperandType::String),
// WS-8 (2026-05-22): bool literal type for the AST-fallback
// source (handles `x == true` where `x` is untyped).
Expr::Literal(Literal::Bool(_), _) => Some(EqOperandType::Bool),
_ => None,
}
}
/// Compile a binary operation expression.
///
/// `op_span` is the source span of the parent `Expr::BinaryOp` node
/// (W10 jit-call-method-user-trait-fix, 2026-05-17). Threaded into
/// `emit_operator_trait_call` / `try_emit_trait_dispatch` so the
/// operator-trait-dispatch side-table keys match the MIR lowering's
/// statement span (see `crates/shape-vm/src/mir/lowering/expr.rs:1716`).
pub(super) fn compile_expr_binary_op(
&mut self,
left: &Expr,
op: &BinaryOp,
right: &Expr,
op_span: Span,
) -> Result<()> {
match op {
BinaryOp::And => {
self.compile_expr(left)?;
let false_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
self.compile_expr(right)?;
self.emit(Instruction::simple(OpCode::Not));
self.emit(Instruction::simple(OpCode::Not));
let end_jump = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(false_jump);
self.emit_bool(false);
self.patch_jump(end_jump);
// Boolean result — not a TypedObject or numeric
self.last_expr_schema = None;
self.last_expr_numeric_type = None;
}
BinaryOp::Or => {
self.compile_expr(left)?;
let true_jump = self.emit_jump(OpCode::JumpIfTrue, 0);
self.compile_expr(right)?;
self.emit(Instruction::simple(OpCode::Not));
self.emit(Instruction::simple(OpCode::Not));
let end_jump = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(true_jump);
self.emit_bool(true);
self.patch_jump(end_jump);
// Boolean result — not a TypedObject or numeric
self.last_expr_schema = None;
self.last_expr_numeric_type = None;
}
BinaryOp::NullCoalesce => {
// Short-circuit null coalescing: a ?? b
// Only evaluate RHS if LHS is None.
//
// Stack discipline (Stage 2.6.5.2: typed IsNull replaces PushNull;Eq):
// 1. compile LHS -> [lhs]
// 2. Dup -> [lhs, lhs]
// 3. IsNull -> [lhs, is_none]
// 4. JumpIfFalse use_lhs -> [lhs] (lhs is not None)
// 5. Pop -> [] (discard None lhs)
// 6. compile RHS -> [rhs]
// 7. Jump end
// use_lhs: -> [lhs] (already on stack)
// end:
self.compile_expr(left)?;
self.emit(Instruction::simple(OpCode::Dup));
self.emit(Instruction::simple(OpCode::IsNull));
let use_lhs_jump = self.emit_jump(OpCode::JumpIfFalse, 0);
// LHS was None — pop it, compile RHS
self.emit(Instruction::simple(OpCode::Pop));
self.compile_expr(right)?;
let end_jump = self.emit_jump(OpCode::Jump, 0);
// LHS was not None — it's already on the stack
self.patch_jump(use_lhs_jump);
self.patch_jump(end_jump);
self.last_expr_schema = None;
self.last_expr_numeric_type = None;
}
BinaryOp::ErrorContext => {
// WS-3 F3: the `!!` error-context operator. Before this
// arm existed, `ErrorContext` fell into the generic `_ =>`
// arithmetic arm, whose strict-operand-type gate rejected
// the `Result<…>` left operand — so a core operator could
// not be compiled at all.
//
// `value !! context`: the `op_error_context` handler
// (`executor/exceptions/mod.rs`) pops `context` (top of
// stack) then `value`, so we compile `left` (value) then
// `right` (context). On the success leg the handler
// unwraps to the inner value (`Ok(v) => v`, `Some(v) => v`,
// bare `v => v`); on the failure leg it builds an AnyError
// and throws. The opcode + handler already exist; this arm
// is the only missing dispatch piece.
self.compile_expr(left)?;
self.compile_expr(right)?;
self.emit(Instruction::simple(OpCode::ErrorContext));
// `!!` yields the UNWRAPPED success value `T` (same as `?`
// — both unwrap `Ok(v)`/`Some(v)` to `v` on success).
// Stamp the tracker with the unwrapped success type so a
// downstream `let v = expr !! "ctx"` records `v`'s type.
self.stamp_unwrapped_success_type(left);
}
BinaryOp::Pipe => {
// Pipe operator: a |> f transforms to f(a)
// a |> f(x) transforms to f(a, x)
match right {
Expr::FunctionCall {
name,
args,
named_args,
span,
} => {
// a |> f(x, y) -> f(a, x, y)
let mut new_args = vec![left.clone()];
new_args.extend(args.iter().cloned());
let new_call = Expr::FunctionCall {
name: name.clone(),
args: new_args,
named_args: named_args.clone(),
span: *span,
};
self.compile_expr(&new_call)?;
}
Expr::MethodCall {
receiver,
method,
args,
named_args,
optional,
span,
} => {
// a |> obj.method(x) -> obj.method(a, x)
let mut new_args = vec![left.clone()];
new_args.extend(args.iter().cloned());
let new_call = Expr::MethodCall {
receiver: receiver.clone(),
method: method.clone(),
args: new_args,
named_args: named_args.clone(),
optional: *optional,
span: *span,
};
self.compile_expr(&new_call)?;
}
Expr::Identifier(name, span) => {
// a |> f -> f(a)
let new_call = Expr::FunctionCall {
name: name.clone(),
args: vec![left.clone()],
named_args: vec![],
span: *span,
};
self.compile_expr(&new_call)?;
}
_ => {
return Err(ShapeError::RuntimeError {
message:
"Pipe operator requires a function or method call on the right side"
.to_string(),
location: None,
});
}
}
}
BinaryOp::Add => {
// R5.4E: retarget typed element-wise Matrix/Vec arithmetic
// ahead of any operand compilation. These helpers compile
// both operands + an arg-count constant + emit `BuiltinCall`
// for the matching `IntrinsicMat*` / `IntrinsicVec*`; they
// never fall through to the dynamic-fallback `AddDynamic`.
// Vector first (covers `Vec<number>+Vec<number>` and
// `Vec<int>+Vec<int>`), then matrix (`Mat<number>+Mat<number>`).
// The operand shapes are disjoint so ordering is not
// observable, but we mirror the pattern used in the generic
// `_ => {}` arm below.
if self.try_compile_typed_vec_arithmetic(&BinaryOp::Add, left, right)? {
return Ok(());
}
if self.try_compile_typed_matrix_arithmetic(&BinaryOp::Add, left, right)? {
return Ok(());
}
// For Add, check if we can do typed merge optimization
self.compile_expr(left)?;
let left_schema = self.last_expr_schema.take();
let mut left_numeric = self.last_expr_numeric_type;
self.compile_expr(right)?;
let right_schema = self.last_expr_schema.take();
let mut right_numeric = self.last_expr_numeric_type;
// If one side is numeric and the other is an identifier/index read with no
// hint yet, adopt the known numeric kind and seed slot hints.
self.adopt_missing_numeric_operand_hint(
left,
right,
&mut left_numeric,
&mut right_numeric,
);
// ADR-006 §2.7.5 stamp-at-compile-time — int-literal width
// inference. A bare integer literal adopts the width of its
// sibling so `a + 1` (u64) stays on the unsigned carrier and
// `x + 1` (i8) stays on the truncating narrow carrier.
Self::promote_int_literal_to_width_sibling(
left,
right,
&mut left_numeric,
&mut right_numeric,
);
// Priority 1: typed object merge (both operands are TypedObjects)
// Exception: if the left type implements Add, skip merge and emit
// generic Add so the executor's operator trait dispatch handles it.
if let (Some(left_id), Some(right_id)) = (left_schema, right_schema) {
let left_has_add = self
.type_tracker
.schema_registry()
.get_by_id(left_id)
.is_some_and(|schema| {
self.type_inference
.env
.type_implements_trait(&schema.name, "Add")
});
if left_has_add {
// Phase 2.5: operator trait dispatch via CallMethod.
// The left operand (receiver) and right operand (arg)
// are already on the stack from compile_expr above.
emit_operator_trait_call(self, "add", op_span);
} else {
self.compile_typed_merge(left_id, right_id)?;
self.last_expr_numeric_type = None;
}
}
// Priority 2: typed numeric add (same types or mixed Int/Number with coercion)
//
// Add is overloaded (numeric add, string concat, array concat,
// object merge). Only emit typed numeric opcodes when we have
// *direct* evidence that both operands are numeric — i.e. each
// is either a numeric literal or an immutable local whose
// storage hint is a numeric family. Without that evidence the
// `last_expr_numeric_type` values may come from speculative
// inference hints (inferred_param_type_hints) which can be wrong
// when a param is actually a string.
else {
// Priority 1.5: dedicated StringConcat / ArrayConcat for
// built-in heap types whose operand kinds the compiler can
// prove. These replace the heap-heap arms in `exec_arithmetic`
// (Phase 2.3 / 2.4) without going through the generic Add
// dispatch.
let inferred_lhs = self.infer_expr_type(left).ok();
let inferred_rhs = self.infer_expr_type(right).ok();
let lhs_name = inferred_lhs.as_ref().map(type_display_name);
let rhs_name = inferred_rhs.as_ref().map(type_display_name);
// String / Char concat: any combination of string + char,
// as long as at least one operand is a string. Char + Char
// also produces a string (matches the legacy heap-heap arms).
let is_strish =
|n: &Option<String>| matches!(n.as_deref(), Some("string") | Some("char"));
let either_is_string = matches!(lhs_name.as_deref(), Some("string"))
|| matches!(rhs_name.as_deref(), Some("string"));
if is_strish(&lhs_name) && is_strish(&rhs_name) && either_is_string {
// Use the typed string concatenation opcode when both
// operands are proven strings/chars.
self.emit(Instruction::simple(OpCode::StringConcatTyped));
self.last_expr_schema = None;
// Phase 3e: result of string concat is a string —
// propagate so chained concats and assignment-target
// type tracking see the type.
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::named(
"string".to_string(),
),
);
self.last_expr_numeric_type = None;
return Ok(());
}
// R5.5: typed string + scalar concat. When LHS is proved
// `string` and RHS is a scalar primitive (`int`, `number`,
// or `bool`), emit a dedicated typed opcode instead of
// falling through to the dynamic `AddDynamic` handler's
// string-coercion branch (`try_heap_arithmetic` Case 2 at
// arithmetic/mod.rs:1815).
//
// Gate: `SHAPE_V2_STRING_COERCE_CONCAT` (default ON via
// `typed_string_coerce_concat_enabled()`). With the flag
// off, emission is byte-identical to pre-R5.5 (falls
// through to the generic AddDynamic path below).
//
// Asymmetric: only string-LHS fires the typed path. The
// commutative form `int + string` is rare in Shape code
// and continues to work via the dynamic fallback. See
// R5.5 commit body.
//
// Resolve operand types via multiple sources — the
// order matches the surrounding arithmetic branch:
// 1. `infer_expr_type` when it produces a display
// name (often `None` for locals whose tracker
// info came from an annotation rather than
// full inference).
// 2. `storage_hint_for_expr` fallback, which reads
// the tracker's `NativeKind` hint (set by
// `let x: string = ...` annotations and by
// literals). This is the same helper the numeric
// path uses via `storage_hint_for_expr` below.
let lhs_is_string = matches!(lhs_name.as_deref(), Some("string"))
|| matches!(
self.storage_hint_for_expr(left),
Some(crate::type_tracking::NativeKind::String)
);
if lhs_is_string
&& crate::compiler::helpers::typed_string_coerce_concat_enabled()
{
let rhs_hint = self.storage_hint_for_expr(right);
let typed_opcode = match rhs_name.as_deref() {
Some("int") => Some(OpCode::StringConcatInt),
Some("number") => Some(OpCode::StringConcatNumber),
Some("bool") => Some(OpCode::StringConcatBool),
_ => match rhs_hint {
Some(crate::type_tracking::NativeKind::Int64) => {
Some(OpCode::StringConcatInt)
}
Some(crate::type_tracking::NativeKind::Float64) => {
Some(OpCode::StringConcatNumber)
}
Some(crate::type_tracking::NativeKind::Bool) => {
Some(OpCode::StringConcatBool)
}
_ => None,
},
};
if let Some(op) = typed_opcode {
self.emit(Instruction::simple(op));
self.last_expr_schema = None;
// Phase 3e: result of string + scalar concat is
// a string — propagate the type so chained
// concats track it.
self.last_expr_type_info = Some(
crate::type_tracking::VariableTypeInfo::named(
"string".to_string(),
),
);
// Result is a freshly-allocated string; clear
// the numeric hint so downstream Add chains
// don't think the result is a scalar.
self.last_expr_numeric_type = None;
return Ok(());
}
}
// Array concat: both operands proven to be arrays. We
// intentionally only fire for the generic `Array<T>` shape,
// not for `Vec<number>`-style FloatArray/IntArray/BoolArray
// (which use element-wise SIMD broadcast for `+`, not concat).
// Display name comes from `type_display_name`: a generic
// `Array<T>` formats as "Array", and a legacy `T[]` formats
// as "T[]".
let is_arrayish = |n: &Option<String>| match n.as_deref() {
Some("Array") => true,
Some(s) if s.ends_with("[]") => true,
_ => false,
};
if is_arrayish(&lhs_name) && is_arrayish(&rhs_name) {
self.emit(Instruction::simple(OpCode::ArrayConcat));
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(());
}
// DateTime/Duration addition: at least one side is
// DateTime or Duration (TimeSpan). Dispatch via
// CallMethod("add") so the executor's PHF-backed
// datetime/timespan method registry handles the
// type combinations. Replaces the generic Add path.
//
// Phase 3e: accept both PascalCase and lowercase
// forms — the compiler's tracker uses PascalCase
// but the runtime inference engine returns lowercase.
let is_temporal = |n: &Option<String>| {
matches!(
n.as_deref(),
Some("DateTime") | Some("Duration") | Some("TimeSpan")
| Some("datetime") | Some("duration") | Some("timespan")
)
};
if is_temporal(&lhs_name) || is_temporal(&rhs_name) {
let method_id = shape_value::MethodId::from_name("add");
let string_id = self.program.add_string("add".to_string());
self.emit(Instruction::new(OpCode::CallMethod, Some(Operand::TypedMethodCall {
method_id: method_id.0, arg_count: 1, string_id,
receiver_type_tag: 0xFF, })));
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(());
}
// Path 4: if infer_expr_type resolved a numeric type
// name, fill in missing NumericType for the coercion
// planner.
let inferred_numeric = |n: &Option<String>| -> Option<NumericType> {
match n.as_deref() {
Some("int") => Some(NumericType::Int),
Some("number") => Some(NumericType::Number),
Some("decimal") => Some(NumericType::Decimal),
_ => None,
}
};
let lhs_inferred_num = inferred_numeric(&lhs_name);
let rhs_inferred_num = inferred_numeric(&rhs_name);
if left_numeric.is_none() && lhs_inferred_num.is_some() {
left_numeric = lhs_inferred_num;
}
if right_numeric.is_none() && rhs_inferred_num.is_some() {
right_numeric = rhs_inferred_num;
}
// Confirm each operand is numeric via one of four paths:
// 1. Syntactic: it's a numeric literal
// 2. Storage hint: it's a local with a known numeric hint
// (excludes untyped function params — see param_locals)
// 3. Type tracker info, excluding only untyped function
// params (param_locals) whose inferred hints can be
// wrong (B19). Non-param identifiers (locals, for-loop
// vars, module bindings) have reliable tracker info.
// 4. infer_expr_type resolved a numeric type name
let is_untyped_param = |e: &Expr| -> bool {
if let Expr::Identifier(name, _) = e {
if let Some(idx) = self.resolve_local(name) {
return self.param_locals.contains(&idx);
}
}
false
};
// Path 5: check if identifier resolves to a local whose
// type_name in the type tracker is numeric. This covers
// locals and for-loop variables that have a known type
// name but whose storage_hint is Unknown (not yet
// propagated).
let local_has_numeric_type_name = |e: &Expr| -> Option<NumericType> {
if let Expr::Identifier(name, _) = e {
if let Some(idx) = self.resolve_local(name) {
if self.param_locals.contains(&idx) {
return None;
}
if let Some(info) = self.type_tracker.get_local_type(idx) {
if let Some(ref tn) = info.type_name {
return match tn.as_str() {
"int" | "Int" | "Integer" | "i64" => Some(NumericType::Int),
"number" | "Number" | "Float" | "f64" => Some(NumericType::Number),
"decimal" | "Decimal" => Some(NumericType::Decimal),
_ => None,
};
}
}
}
}
None
};
let lhs_local_num = local_has_numeric_type_name(left);
let rhs_local_num = local_has_numeric_type_name(right);
if left_numeric.is_none() && lhs_local_num.is_some() {
left_numeric = lhs_local_num;
}
if right_numeric.is_none() && rhs_local_num.is_some() {
right_numeric = rhs_local_num;
}
let lhs_confirmed = Self::is_expr_confirmed_numeric(left)
|| self
.storage_hint_for_expr(left)
.is_some_and(|h| h.is_numeric_family())
|| (!is_untyped_param(left) && left_numeric.is_some())
|| lhs_inferred_num.is_some()
|| lhs_local_num.is_some();
let rhs_confirmed = Self::is_expr_confirmed_numeric(right)
|| self
.storage_hint_for_expr(right)
.is_some_and(|h| h.is_numeric_family())
|| (!is_untyped_param(right) && right_numeric.is_some())
|| rhs_inferred_num.is_some()
|| rhs_local_num.is_some();
let primary = if lhs_confirmed && rhs_confirmed {
self.emit_numeric_binary_with_coercion_trusted(
&BinaryOp::Add,
left_numeric,
right_numeric,
false,
left,
right,
)
} else {
NumericEmitResult::NoPlan
};
match primary {
NumericEmitResult::EmittedTyped => {
self.last_expr_schema = None;
}
NumericEmitResult::CoercedNeedsGeneric | NumericEmitResult::NoPlan => {
// R5.2B: retarget user-defined `impl Add for T` to
// `CallMethod` at compile time, mirroring the
// symmetric strict-arithmetic path at L1230-1244 and
// the numeric-declined paths at L1260/L1279. Uses
// `left_schema` captured at L646. When the helper
// emits `CallMethod`, we skip the dynamic fallthrough
// so that `exec_arithmetic_dynamic_fallback::
// try_binary_operator_trait` is never reached for
// user-op Add. No new opcode is required; CallMethod
// with `Operand::TypedMethodCall` already dispatches
// to user impl methods via the function_name_index
// (see `executor/objects/mod.rs::op_call_method`,
// L1427-L1458).
//
// When the helper declines (no schema / no matching
// impl), the historical path emitted `AddDynamic`
// for non-numeric operand combinations (DateTime,
// mixed string, polyglot value). Strict-typing
// sweep (Phase 1): that dynamic-fallback emission
// is now a hard compile error.
if !try_emit_trait_dispatch(self, &BinaryOp::Add, left_schema, left, op_span) {
return Err(strict_typing_binop_error(
self,
&BinaryOp::Add,
left,
right,
));
}
}
}
}
}
BinaryOp::BitAnd
| BinaryOp::BitOr
| BinaryOp::BitXor
| BinaryOp::BitShl
| BinaryOp::BitShr => {
// Phase R5.1C: emit typed bitwise opcodes (`BitAndInt`,
// `BitOrInt`, `BitXorInt`, `BitShlInt`, `BitShrInt`) when
// both operand types are provably `int` at compile time.
// Mixed-type / unresolved cases fall through to the
// Dynamic (`BitAnd`/`BitOr`/...) variants emitted by
// `compile_binary_op`.
//
// Semantics match the Dynamic variants exactly: no
// shift-count masking, i48 payload truncation applies.
// See R5.1B commit body for the edge-case notes.
//
// Gate: `SHAPE_V2_TYPED_BITWISE` (default ON via
// `typed_bitwise_enabled()`). With the flag off, emission
// is byte-identical to pre-R5.1C.
self.compile_expr(left)?;
let mut left_numeric = self.last_expr_numeric_type;
let left_schema = self.last_expr_schema;
self.compile_expr(right)?;
let mut right_numeric = self.last_expr_numeric_type;
// W1.9: user-defined `impl BitAnd / BitOr / BitXor for X`
// dispatch — if the left-operand's TypedObject schema
// implements the matching operator trait, emit a
// `CallMethod("bitand"/"bitor"/"bitxor")` and return.
// Both operands are already on the stack from the
// compile_expr calls above. Mirrors the Add arm's
// pattern at L756-790 and Sub/Mul/Div/Mod's trait
// dispatch at L1462-1475.
if matches!(op, BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXor) {
if let (Some(trait_name), Some(method_name)) = (
operator_trait_for_op(op),
operator_trait_method_for_op(op),
) {
let left_implements = left_schema
.and_then(|sid| self.type_tracker.schema_registry().get_by_id(sid))
.is_some_and(|schema| {
self.type_inference
.env
.type_implements_trait(&schema.name, trait_name)
});
if left_implements {
emit_operator_trait_call(self, method_name, op_span);
return Ok(());
}
}
}
// Don't trust inferred numeric types for untyped function
// parameters (same rationale as the `param_locals` guard
// in the `_ => {}` arithmetic branch below).
if let Expr::Identifier(name, _) = left {
if let Some(local_idx) = self.resolve_local(name) {
if self.param_locals.contains(&local_idx) {
left_numeric = None;
}
}
}
if let Expr::Identifier(name, _) = right {
if let Some(local_idx) = self.resolve_local(name) {
if self.param_locals.contains(&local_idx) {
right_numeric = None;
}
}
}
// Fall back to the inference engine when slot tracking
// did not produce a numeric hint. This mirrors the
// `NoPlan` path in the `_ => {}` arithmetic branch.
if left_numeric.is_none() {
left_numeric = self
.infer_expr_type(left)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
}
if right_numeric.is_none() {
right_numeric = self
.infer_expr_type(right)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
}
let both_int = matches!(left_numeric, Some(NumericType::Int))
&& matches!(right_numeric, Some(NumericType::Int));
let emit_typed = both_int
&& crate::compiler::helpers::typed_bitwise_enabled();
// W1.10 (v0.3 R2): user-type operator trait dispatch for
// `<<` / `>>`. When the left operand has a TypedObject
// schema implementing `Shl` / `Shr`, emit a `CallMethod`
// dispatch via the shared `emit_operator_trait_call`
// path (mirrors the Phase 2.5 dispatch in the generic
// `_ =>` arithmetic arm at L1456-1475 + Add's dedicated
// arm at L775-794). Runs only when typed-int emission
// is not eligible — the typed bitwise path takes
// precedence for `int << int` to preserve the existing
// zero-dispatch behavior. BitAnd/BitOr/BitXor handled
// by sibling W1.9 dispatch.
if !emit_typed
&& matches!(op, BinaryOp::BitShl | BinaryOp::BitShr)
{
let trait_name = operator_trait_for_op(op);
let method_name = operator_trait_method_for_op(op);
if let (Some(trait_name), Some(method_name)) =
(trait_name, method_name)
{
let has_trait_via_schema = left_schema
.and_then(|sid| {
self.type_tracker.schema_registry().get_by_id(sid)
})
.is_some_and(|schema| {
self.type_inference
.env
.type_implements_trait(&schema.name, trait_name)
});
let has_trait = has_trait_via_schema
|| self
.infer_expr_type(left)
.ok()
.is_some_and(|ty| {
let name = type_display_name(&ty);
self.type_inference
.env
.type_implements_trait(&name, trait_name)
});
if has_trait {
emit_operator_trait_call(self, method_name, op_span);
return Ok(());
}
}
}
if emit_typed {
let typed_opcode = match op {
BinaryOp::BitAnd => OpCode::BitAndInt,
BinaryOp::BitOr => OpCode::BitOrInt,
BinaryOp::BitXor => OpCode::BitXorInt,
BinaryOp::BitShl => OpCode::BitShlInt,
BinaryOp::BitShr => OpCode::BitShrInt,
_ => unreachable!(),
};
self.emit(Instruction::simple(typed_opcode));
// Typed bitwise op on two ints yields an int — preserve
// the numeric hint so downstream typed emission keeps
// working (e.g. (a & b) + c stays on the int path).
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = Some(NumericType::Int);
} else {
// Dynamic fallback: mixed / unresolved operand types,
// or flag disabled. Preserves pre-R5.1C semantics
// byte-identically.
self.compile_binary_op(op)?;
self.last_expr_schema = None;
self.last_expr_type_info = None;
// The dynamic bitwise opcodes (`BitAnd`, `BitOr`, ...)
// post-Wave-E+5.5 push raw native i64 bits via
// `exec_dyn_bit_binary` / `exec_dyn_bit_unary`. When both
// operands were proven `int` at compile time (we just
// didn't take the typed-emit path because the flag was
// off), preserve the Int numeric hint so the top-level
// return-kind inference can pair this producer with
// the inferred Int kind.
self.last_expr_numeric_type = if both_int {
Some(NumericType::Int)
} else {
None
};
}
}
_ => {
// Typed matrix kernels: Mat<number> * Vec<number>/Mat<number>.
// Lower before generic strict-arithmetic checks so typed matrix
// paths never fall back to scalar arithmetic dispatch.
if matches!(op, BinaryOp::Mul) && self.try_compile_typed_matrix_mul(left, right)? {
return Ok(());
}
// R5.4E: retarget typed element-wise vector arithmetic for
// Sub/Mul/Div on `Vec<number>`. The Add case is handled in
// the dedicated `BinaryOp::Add` arm above. Running before
// the strict-arithmetic gate below is intentional: the
// gate rejects non-numeric operand types, but a typed
// `Vec<number>` param is non-numeric at the type level and
// would otherwise produce a misleading "Cannot apply '-'
// to Vec<number> and Vec<number>" error.
//
// Vector before matrix to match the generic fallback ordering
// (the pre-R5.4E path routes vector ops through
// `TypedArrayData::F64` SIMD while matrix ops go through the
// heap-matrix arm). Ordering here is not semantically load-
// bearing — the two helpers classify disjoint operand shapes
// — but mirrors the shape of other compile-time retargets
// in this file.
if self.try_compile_typed_vec_arithmetic(op, left, right)? {
return Ok(());
}
if self.try_compile_typed_matrix_arithmetic(op, left, right)? {
return Ok(());
}
// Phase 2.6.5.3: inference-driven typed Eq/Neq dispatch.
// Queries the inference engine for both operand types BEFORE
// compiling them and emits the typed opcode directly. This is
// the PRIMARY path for Equal/NotEqual; the legacy slot-tracker
// dispatch below is the secondary fallback for cases inference
// can't resolve.
if self.compile_typed_equality(op, left, right, op_span)? {
return Ok(());
}
// Stage 4.2: typed string ordered comparison.
// When both operands are proven strings and the op is an
// ordered comparison (>, <, >=, <=), emit the specialized
// string comparison opcode for zero-dispatch execution.
if is_ordered_comparison(op) {
if let (Ok(lt), Ok(rt)) = (self.infer_expr_type(left), self.infer_expr_type(right)) {
let lt_name = type_display_name(<);
let rt_name = type_display_name(&rt);
let is_strish = |n: &str| matches!(n, "string" | "char");
if is_strish(<_name) && is_strish(&rt_name) {
let string_cmp_op = match op {
BinaryOp::Greater => OpCode::GtString,
BinaryOp::Less => OpCode::LtString,
BinaryOp::GreaterEq => OpCode::GteString,
BinaryOp::LessEq => OpCode::LteString,
_ => unreachable!(),
};
self.compile_expr(left)?;
self.compile_expr(right)?;
self.emit(Instruction::simple(string_cmp_op));
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(());
}
}
}
// Stage 4.2: temporal Sub dispatch via CallMethod("sub").
// When one operand is DateTime or Duration/TimeSpan, emit
// CallMethod instead of falling through to the strict
// arithmetic check which would reject non-numeric types.
if matches!(op, BinaryOp::Sub) {
if let (Ok(lt), Ok(rt)) = (self.infer_expr_type(left), self.infer_expr_type(right)) {
let lt_name = type_display_name(<);
let rt_name = type_display_name(&rt);
// Phase 3e: accept both PascalCase ("DateTime") and
// lowercase ("datetime") forms — the compiler's
// tracker uses PascalCase but the runtime
// inference engine returns lowercase for
// Expr::DateTime / Expr::Duration literals.
let is_temporal = |n: &str| matches!(
n,
"DateTime" | "Duration" | "TimeSpan"
| "datetime" | "duration" | "timespan"
);
if is_temporal(<_name) || is_temporal(&rt_name) {
self.compile_expr(left)?;
self.compile_expr(right)?;
let method_id = shape_value::MethodId::from_name("sub");
let string_id = self.program.add_string("sub".to_string());
self.emit(Instruction::new(OpCode::CallMethod, Some(Operand::TypedMethodCall {
method_id: method_id.0, arg_count: 1, string_id,
receiver_type_tag: 0xFF, })));
self.last_expr_schema = None;
self.last_expr_type_info = None;
self.last_expr_numeric_type = None;
return Ok(());
}
}
}
// ── Compile-time type safety for strict arithmetic ──
// Sub, Mul, Div, Mod, Pow require numeric operands.
// If both types are known and either is non-numeric → compile error.
if is_strict_arithmetic(op) {
if let (Ok(lt), Ok(rt)) =
(self.infer_expr_type(left), self.infer_expr_type(right))
{
// `infer_expr_type` runs outside the compiler's local-slot context.
// For identifiers that are currently bound in bytecode locals/module_bindings,
// an inferred Function type may be a shadowed builtin (e.g. `len`).
// In that case, defer to slot-based tracking below to avoid false errors.
let left_shadowed_builtin = matches!(left, Expr::Identifier(name, _)
if (self.resolve_local(name).is_some() || self.module_bindings.contains_key(name))
&& is_function_type(<));
let right_shadowed_builtin = matches!(right, Expr::Identifier(name, _)
if (self.resolve_local(name).is_some() || self.module_bindings.contains_key(name))
&& is_function_type(&rt));
if left_shadowed_builtin || right_shadowed_builtin {
// Skip this early semantic gate for shadowed identifiers.
// The typed/local tracking pass below will still enforce arithmetic safety.
} else if !is_type_numeric(<) || !is_type_numeric(&rt) {
// Check if the left operand's type implements an operator trait
// for this operation (e.g. impl Mul for Vec2). If so, allow the
// generic opcode through to the executor's trait dispatch.
let has_operator_trait = operator_trait_for_op(op)
.and_then(|trait_name| {
let type_name = type_display_name(<);
if self
.type_inference
.env
.type_implements_trait(&type_name, trait_name)
{
Some(())
} else {
None
}
})
.is_some();
if !has_operator_trait {
let op_symbol = match op {
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Mod => "%",
BinaryOp::Pow => "**",
_ => "?",
};
return Err(ShapeError::SemanticError {
message: format!(
"Cannot apply '{}' to {} and {}. Both operands must be numeric (int, number, or decimal).",
op_symbol,
type_display_name(<),
type_display_name(&rt),
),
location: Some(
self.span_to_source_location(combined_span(left, right)),
),
});
}
}
}
}
// ── Compile operands, capture numeric types and schemas ──
self.compile_expr(left)?;
let mut left_numeric = self.last_expr_numeric_type;
let left_schema = self.last_expr_schema;
self.compile_expr(right)?;
let mut right_numeric = self.last_expr_numeric_type;
let right_schema = self.last_expr_schema;
// Don't trust inferred numeric types for untyped function parameters.
// Their inferred_param_type_hints can be wrong (same rationale as the
// param_locals guard in storage_hint_for_expr for Add). Without an
// explicit type annotation the parameter may receive values of any
// type at runtime, so fall back to generic opcodes.
if let Expr::Identifier(name, _) = left {
if let Some(local_idx) = self.resolve_local(name) {
if self.param_locals.contains(&local_idx) {
left_numeric = None;
}
}
}
if let Expr::Identifier(name, _) = right {
if let Some(local_idx) = self.resolve_local(name) {
if self.param_locals.contains(&local_idx) {
right_numeric = None;
}
}
}
// WS-9 / WS-9b: an access operand (`a[0]` index access, or
// `a.lo` property access) carries no numeric hint from
// `compile_expr` when the receiver is an unannotated
// parameter — the access reads an untyped slot. Recover the
// operand kind from the proven access type:
//
// * Index access — `infer_expr_type` resolves `a[i]` for an
// array-tracked receiver via `tracked_array_element_type`.
// This REPLACES the former blanket `IndexAccess` → `Number`
// default, which stamped `Float64` on a statically-`int`
// element and silently turned `7 / 2 = 3` into `3.5`.
//
// * Property access (WS-9b) — `infer_expr_type` resolves
// `a.lo` via `tracker_schema_id_for_expr`: once inference
// widens the unannotated parameter to its callsite struct
// type (`Box`), the parameter's local slot carries the
// `Box` schema id, and the field type is read from the
// proven struct schema. The field kind is PROVEN from the
// schema, never fabricated — when it cannot be proven the
// hint stays `None` and the strict-arithmetic proof guard /
// `NoPlan` path raises a loud compile error (no `Number`
// default is introduced for property access).
if is_strict_arithmetic(op) || is_ordered_comparison(op) {
let is_access = |e: &Expr| {
matches!(
e,
Expr::IndexAccess { .. } | Expr::PropertyAccess { .. }
)
};
if left_numeric.is_none() && is_access(left) {
left_numeric = self
.infer_expr_type(left)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
}
if right_numeric.is_none() && is_access(right) {
right_numeric = self
.infer_expr_type(right)
.ok()
.and_then(|t| inferred_type_to_numeric(&t));
}
}
if is_strict_arithmetic(op) || is_ordered_comparison(op) {
self.adopt_missing_numeric_operand_hint(
left,
right,
&mut left_numeric,
&mut right_numeric,
);
}
// ADR-006 §2.7.5 stamp-at-compile-time — int-literal width
// inference. A bare integer literal adopts the width of its
// sibling so the operation stays on the declared-width
// carrier (`DivTyped`/`ModTyped` with the matching
// `NumericWidth`) rather than widening to the signed default
// `Int` (`DivInt`) — covering both `u64` (unsigned div/mod)
// and the narrow signed/unsigned widths (truncating arith).
Self::promote_int_literal_to_width_sibling(
left,
right,
&mut left_numeric,
&mut right_numeric,
);
// ── Schema-based type safety (catches objects in arithmetic) ──
// If an operand has a schema (it's a TypedObject) but no numeric type,
// it's an object being used in arithmetic → compile error.
// Exception: if the left type implements an operator trait for this op.
if is_strict_arithmetic(op) {
let left_is_object = left_schema.is_some() && left_numeric.is_none();
let right_is_object = right_schema.is_some() && right_numeric.is_none();
if left_is_object || right_is_object {
// Check if the left operand's type implements an operator trait
let has_operator_trait = left_schema
.and_then(|sid| self.type_tracker.schema_registry().get_by_id(sid))
.and_then(|schema| {
operator_trait_for_op(op).filter(|trait_name| {
self.type_inference
.env
.type_implements_trait(&schema.name, trait_name)
})
})
.is_some();
if !has_operator_trait {
let op_symbol = match op {
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Mod => "%",
BinaryOp::Pow => "**",
_ => "?",
};
let left_desc = if left_is_object { "object" } else { "numeric" };
let right_desc = if right_is_object { "object" } else { "numeric" };
return Err(ShapeError::SemanticError {
message: format!(
"Cannot apply '{}' to {} and {}. Both operands must be numeric (int, number, or decimal).",
op_symbol, left_desc, right_desc,
),
location: Some(
self.span_to_source_location(combined_span(left, right)),
),
});
}
}
}
// ── Phase 2.5: operator trait dispatch via CallMethod ──
// If the left operand is a typed object whose schema implements
// the operator trait (Sub/Mul/Div/Ord/...), emit a method call
// instead of falling through to a generic arithmetic opcode. The
// receiver and the right-hand-side operand are already on the stack.
//
// W1.8 (v0.3 R2): for ordered comparison ops (`<`, `<=`, `>`, `>=`)
// the trait method is `Ord::cmp(other: Self) -> int`; lower the
// returned int via `emit_cmp_result_comparison` to produce the
// per-op boolean result. Mirrors the post-call step in
// `try_emit_trait_dispatch` at L83.
if let Some(trait_name) = operator_trait_for_op(op) {
let dispatches_via_trait = left_schema
.and_then(|sid| self.type_tracker.schema_registry().get_by_id(sid))
.is_some_and(|schema| {
self.type_inference
.env
.type_implements_trait(&schema.name, trait_name)
});
if dispatches_via_trait {
if let Some(method_name) = operator_trait_method_for_op(op) {
emit_operator_trait_call(self, method_name, op_span);
if is_ordered_comparison(op) {
emit_cmp_result_comparison(self, op);
}
return Ok(());
}
}
}
// ── ε-1 PART 1: emit-side soundness guard ──
// A typed numeric opcode requires the compiler to PROVE both
// operand kinds (CLAUDE.md §Mechanical enforcement). If an
// operand's compile-time type is still an unresolved
// `Type::Variable` the `NumericType` claim is fabricated —
// surface a clean `ProofGap` diagnostic instead of stamping a
// default kind and emitting a typed opcode (the silent-wrong
// path that produced the `2e-321` denormal).
if let Some(gap) = self.numeric_operand_proof_gap(op, left, left_numeric) {
return Err(gap);
}
if let Some(gap) = self.numeric_operand_proof_gap(op, right, right_numeric) {
return Err(gap);
}
// ── Emit typed opcode (with coercion for mixed Int/Number) ──
let is_comparison = is_ordered_comparison(op);
let emit_result = self.emit_numeric_binary_with_coercion_trusted(
op,
left_numeric,
right_numeric,
is_comparison,
left,
right,
);
match emit_result {
NumericEmitResult::EmittedTyped => {}
NumericEmitResult::CoercedNeedsGeneric => {
// Op has no typed variant for this type combination.
// Strict-typing sweep (Phase 1): the historical
// dynamic-opcode fallback is now a hard compile error.
if !try_emit_trait_dispatch(self, op, left_schema, left, op_span) {
return Err(strict_typing_binop_error(self, op, left, right));
}
}
NumericEmitResult::NoPlan => {
// Types unknown from slot tracking — try inference engine.
let (inferred_left, inferred_right) = self.infer_numeric_pair(left, right);
match self.emit_numeric_binary_with_coercion_trusted(
op,
inferred_left,
inferred_right,
is_comparison,
left,
right,
) {
NumericEmitResult::EmittedTyped => {}
_ => {
// Strict-typing sweep (Phase 1): the historical
// dynamic-opcode fallback is now a hard compile error.
if !try_emit_trait_dispatch(self, op, left_schema, left, op_span) {
return Err(strict_typing_binop_error(
self, op, left, right,
));
}
}
}
}
}
self.last_expr_schema = None;
}
}
Ok(())
}
/// Compile a fuzzy comparison expression with tolerance.
/// Desugars to arithmetic operations — no dedicated fuzzy VM opcodes needed.
pub(super) fn compile_expr_fuzzy_comparison(
&mut self,
left: &Expr,
op: &FuzzyOp,
right: &Expr,
tolerance: &FuzzyTolerance,
) -> Result<()> {
use crate::bytecode::{Constant, Operand};
// Store left and right in temp locals to avoid re-evaluation
let temp_a = self.declare_temp_local("__fuzzy_a")?;
let temp_b = self.declare_temp_local("__fuzzy_b")?;
self.compile_expr(left)?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(temp_a)),
));
self.compile_expr(right)?;
self.emit(Instruction::new(
OpCode::StoreLocal,
Some(Operand::Local(temp_b)),
));
// Helper: emit abs(a - b) → load a, load b, SubNumber, Dup, push 0, LtNumber, JumpIfFalse(skip), NegNumber, skip:
// This computes abs(top-of-stack) inline. All fuzzy comparison operands are f64.
let emit_abs_diff = |compiler: &mut BytecodeCompiler| {
compiler.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
compiler.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
compiler.emit(Instruction::simple(OpCode::SubNumber));
// abs: dup, push 0, LtNumber, JumpIfFalse(skip), NegNumber
compiler.emit(Instruction::simple(OpCode::Dup));
let zero_idx = compiler.program.add_constant(Constant::Number(0.0));
compiler.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_idx)),
));
compiler.emit(Instruction::simple(OpCode::LtNumber));
let skip = compiler.emit_jump(OpCode::JumpIfFalse, 0);
compiler.emit(Instruction::simple(OpCode::NegNumber));
compiler.patch_jump(skip);
};
match (op, tolerance) {
(FuzzyOp::Equal, FuzzyTolerance::Absolute(tol)) => {
// abs(a - b) <= tol
emit_abs_diff(self);
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
}
(FuzzyOp::Equal, FuzzyTolerance::Percentage(tol)) => {
// abs(a - b) / ((abs(a) + abs(b)) / 2) <= tol
// numerator: abs(a - b)
emit_abs_diff(self);
// denominator: (abs(a) + abs(b)) / 2
// abs(a)
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::simple(OpCode::Dup));
let zero_idx2 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_idx2)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let skip_a = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(skip_a);
// abs(b)
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::Dup));
let zero_idx3 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(zero_idx3)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let skip_b = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(skip_b);
// (abs(a) + abs(b)) / 2
self.emit(Instruction::simple(OpCode::AddNumber));
let two_idx = self.program.add_constant(Constant::Number(2.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(two_idx)),
));
self.emit(Instruction::simple(OpCode::DivNumber));
// numerator / denominator <= tol
self.emit(Instruction::simple(OpCode::DivNumber));
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
}
(FuzzyOp::Greater, FuzzyTolerance::Absolute(tol)) => {
// a > b || abs(a - b) <= tol
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::GtNumber));
let end = self.emit_jump(OpCode::JumpIfTrue, 0);
emit_abs_diff(self);
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
let end2 = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(end);
self.emit_bool(true);
self.patch_jump(end2);
}
(FuzzyOp::Greater, FuzzyTolerance::Percentage(tol)) => {
// a > b || (percentage within tolerance)
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::GtNumber));
let end = self.emit_jump(OpCode::JumpIfTrue, 0);
// Reuse percentage tolerance check
emit_abs_diff(self);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::simple(OpCode::Dup));
let z1 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(z1)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let sa = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(sa);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::Dup));
let z2 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(z2)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let sb = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(sb);
self.emit(Instruction::simple(OpCode::AddNumber));
let two = self.program.add_constant(Constant::Number(2.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(two)),
));
self.emit(Instruction::simple(OpCode::DivNumber));
self.emit(Instruction::simple(OpCode::DivNumber));
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
let end2 = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(end);
self.emit_bool(true);
self.patch_jump(end2);
}
(FuzzyOp::Less, FuzzyTolerance::Absolute(tol)) => {
// a < b || abs(a - b) <= tol
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let end = self.emit_jump(OpCode::JumpIfTrue, 0);
emit_abs_diff(self);
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
let end2 = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(end);
self.emit_bool(true);
self.patch_jump(end2);
}
(FuzzyOp::Less, FuzzyTolerance::Percentage(tol)) => {
// a < b || (percentage within tolerance)
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let end = self.emit_jump(OpCode::JumpIfTrue, 0);
emit_abs_diff(self);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_a)),
));
self.emit(Instruction::simple(OpCode::Dup));
let z1 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(z1)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let sa = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(sa);
self.emit(Instruction::new(
OpCode::LoadLocal,
Some(Operand::Local(temp_b)),
));
self.emit(Instruction::simple(OpCode::Dup));
let z2 = self.program.add_constant(Constant::Number(0.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(z2)),
));
self.emit(Instruction::simple(OpCode::LtNumber));
let sb = self.emit_jump(OpCode::JumpIfFalse, 0);
self.emit(Instruction::simple(OpCode::NegNumber));
self.patch_jump(sb);
self.emit(Instruction::simple(OpCode::AddNumber));
let two = self.program.add_constant(Constant::Number(2.0));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(two)),
));
self.emit(Instruction::simple(OpCode::DivNumber));
self.emit(Instruction::simple(OpCode::DivNumber));
let tol_idx = self.program.add_constant(Constant::Number(*tol));
self.emit(Instruction::new(
OpCode::PushConst,
Some(Operand::Const(tol_idx)),
));
self.emit(Instruction::simple(OpCode::LteNumber));
let end2 = self.emit_jump(OpCode::Jump, 0);
self.patch_jump(end);
self.emit_bool(true);
self.patch_jump(end2);
}
}
Ok(())
}
/// Compile a typed object merge (a + b where both are TypedObjects)
///
/// This registers the intersection schema at compile time and emits
/// TypedMergeObject for O(1) memcpy-based merge.
fn compile_typed_merge(&mut self, left_id: SchemaId, right_id: SchemaId) -> Result<()> {
let registry = self.type_tracker.schema_registry();
let left_schema = registry
.get_by_id(left_id)
.ok_or_else(|| ShapeError::RuntimeError {
message: format!("Unknown left schema ID: {}", left_id),
location: None,
})?;
let right_schema =
registry
.get_by_id(right_id)
.ok_or_else(|| ShapeError::RuntimeError {
message: format!("Unknown right schema ID: {}", right_id),
location: None,
})?;
// Calculate sizes (8 bytes per field)
let left_size = left_schema.fields.len() * 8;
let right_size = right_schema.fields.len() * 8;
// Build merged field list
let mut merged_fields: Vec<(String, FieldType)> = Vec::new();
for f in &left_schema.fields {
merged_fields.push((f.name.clone(), f.field_type.clone()));
}
for f in &right_schema.fields {
merged_fields.push((f.name.clone(), f.field_type.clone()));
}
// Register intersection schema
let merged_name = format!("__intersection_{}_{}", left_id, right_id);
let target_id = self
.type_tracker
.schema_registry_mut()
.register_type(merged_name, merged_fields);
// Emit TypedMergeObject
self.emit(Instruction::new(
OpCode::TypedMergeObject,
Some(Operand::TypedMerge {
target_schema_id: target_id as u16,
left_size: left_size as u16,
right_size: right_size as u16,
}),
));
// Track result schema for chained operations (e.g., a + b + c)
self.last_expr_schema = Some(target_id);
self.last_expr_type_info = Some(VariableTypeInfo::known(
target_id,
format!("__intersection_{}_{}", left_id, right_id),
));
Ok(())
}
}
#[cfg(test)]
mod u64_literal_inference_tests {
//! ADR-006 §2.7.5 stamp-at-compile-time — int-literal width inference.
//!
//! Regression coverage for `r5c-2-bg-b2-u64-literal-inference`: a bare
//! integer literal that is a sibling operand of a width-typed binary op
//! must adopt the sibling's width so the operation stays on the
//! declared-width carrier — emitting `DivTyped`/`ModTyped`/... with the
//! matching `NumericWidth` instead of the signed-default `DivInt`.
use super::*;
use shape_ast::IntWidth;
// ── promote_int_literal_to_width_sibling unit coverage ──
fn lit_int(v: i64) -> Expr {
Expr::Literal(Literal::Int(v), Span::DUMMY)
}
fn lit_uint(v: u64) -> Expr {
Expr::Literal(Literal::UInt(v), Span::DUMMY)
}
fn ident() -> Expr {
Expr::Identifier("x".to_string(), Span::DUMMY)
}
#[test]
fn u64_sibling_promotes_right_int_literal() {
// `a / 2`: a:u64, 2:Int literal → 2 adopts IntWidth(U64).
let mut l = Some(NumericType::IntWidth(IntWidth::U64));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&lit_int(2),
&mut l,
&mut r,
);
assert_eq!(l, Some(NumericType::IntWidth(IntWidth::U64)));
assert_eq!(r, Some(NumericType::IntWidth(IntWidth::U64)));
}
#[test]
fn u64_sibling_promotes_left_int_literal() {
// `100 / a`: 100:Int literal, a:u64 → 100 adopts IntWidth(U64).
let mut l = Some(NumericType::Int);
let mut r = Some(NumericType::IntWidth(IntWidth::U64));
BytecodeCompiler::promote_int_literal_to_width_sibling(
&lit_int(100),
&ident(),
&mut l,
&mut r,
);
assert_eq!(l, Some(NumericType::IntWidth(IntWidth::U64)));
assert_eq!(r, Some(NumericType::IntWidth(IntWidth::U64)));
}
#[test]
fn narrow_sibling_promotes_int_literal() {
// `x + 28`: x:i8, 28:Int literal → 28 adopts IntWidth(I8).
for w in [IntWidth::I8, IntWidth::I16, IntWidth::I32, IntWidth::U8, IntWidth::U16, IntWidth::U32] {
let mut l = Some(NumericType::IntWidth(w));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&lit_int(28),
&mut l,
&mut r,
);
assert_eq!(
r,
Some(NumericType::IntWidth(w)),
"literal must adopt {:?}",
w
);
}
}
#[test]
fn negative_literal_does_not_adopt_unsigned_width() {
// `a + (-5)`: a:u64, -5:Int literal → -5 must NOT silently adopt u64.
let mut l = Some(NumericType::IntWidth(IntWidth::U64));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&lit_int(-5),
&mut l,
&mut r,
);
assert_eq!(r, Some(NumericType::Int), "negative literal stays Int for u64 sibling");
}
#[test]
fn negative_literal_adopts_signed_width() {
// `x + (-5)`: x:i8, -5:Int literal → -5 adopts i8 (signed, fits).
let mut l = Some(NumericType::IntWidth(IntWidth::I8));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&lit_int(-5),
&mut l,
&mut r,
);
assert_eq!(r, Some(NumericType::IntWidth(IntWidth::I8)));
}
#[test]
fn signed_typed_sibling_is_not_promoted() {
// `a / b`: a:u64, b:Int (a genuine variable, not a literal) →
// the `Int` operand is NOT a literal so it stays untouched.
let mut l = Some(NumericType::IntWidth(IntWidth::U64));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&ident(), // RHS is an identifier, not a literal
&mut l,
&mut r,
);
assert_eq!(r, Some(NumericType::Int), "non-literal Int sibling stays Int");
}
#[test]
fn uint_literal_adopts_u64_sibling() {
// `a / 18446744073709551615u64`-shaped literal classified as UInt.
let mut l = Some(NumericType::IntWidth(IntWidth::U64));
let mut r = Some(NumericType::Int);
BytecodeCompiler::promote_int_literal_to_width_sibling(
&ident(),
&lit_uint(9_000_000_000_000_000_000),
&mut l,
&mut r,
);
assert_eq!(r, Some(NumericType::IntWidth(IntWidth::U64)));
}
// ── end-to-end opcode-emission coverage ──
/// Compile a top-level program and return its instructions.
fn compile_top_level(code: &str) -> Vec<Instruction> {
let program = shape_ast::parser::parse_program(code).expect("parse failed");
let compiler = super::super::super::BytecodeCompiler::new();
let bc = compiler.compile(&program).expect("compile failed");
bc.instructions
}
/// Returns `true` when the instruction stream contains `opcode` carrying
/// `Operand::Width(width)`.
fn has_width_typed(instrs: &[Instruction], opcode: OpCode, width: NumericWidth) -> bool {
instrs.iter().any(|i| {
i.opcode == opcode && matches!(i.operand, Some(Operand::Width(w)) if w == width)
})
}
fn has_opcode(instrs: &[Instruction], opcode: OpCode) -> bool {
instrs.iter().any(|i| i.opcode == opcode)
}
#[test]
fn u64_var_div_literal_emits_div_typed_u64() {
// `a / 2` on `a: u64` must emit `DivTyped` width U64 — the unsigned
// carrier — NOT the signed `DivInt`.
let instrs = compile_top_level(
"let a: u64 = 100\nlet b: u64 = a / 2\n",
);
assert!(
has_width_typed(&instrs, OpCode::DivTyped, NumericWidth::U64),
"u64 / literal must emit DivTyped(U64): {:?}",
instrs.iter().map(|i| i.opcode).collect::<Vec<_>>()
);
assert!(
!has_opcode(&instrs, OpCode::DivInt),
"u64 / literal must NOT emit signed DivInt"
);
}
#[test]
fn u64_var_mod_literal_emits_mod_typed_u64() {
let instrs = compile_top_level(
"let a: u64 = 100\nlet b: u64 = a % 10\n",
);
assert!(
has_width_typed(&instrs, OpCode::ModTyped, NumericWidth::U64),
"u64 % literal must emit ModTyped(U64)"
);
assert!(!has_opcode(&instrs, OpCode::ModInt));
}
#[test]
fn u64_literal_on_left_emits_div_typed_u64() {
// `100 / a` — literal on the LEFT.
let instrs = compile_top_level(
"let a: u64 = 7\nlet b: u64 = 100 / a\n",
);
assert!(
has_width_typed(&instrs, OpCode::DivTyped, NumericWidth::U64),
"literal / u64 must emit DivTyped(U64)"
);
}
#[test]
fn u64_var_add_literal_stays_u64_carrier() {
// `a + 1` on `a: u64` must emit `AddTyped` width U64.
let instrs = compile_top_level(
"let a: u64 = 100\nlet b: u64 = a + 1\n",
);
assert!(
has_width_typed(&instrs, OpCode::AddTyped, NumericWidth::U64),
"u64 + literal must emit AddTyped(U64)"
);
assert!(!has_opcode(&instrs, OpCode::AddInt));
}
#[test]
fn u64_var_sub_mul_literal_stay_u64_carrier() {
let sub = compile_top_level("let a: u64 = 100\nlet b: u64 = a - 1\n");
assert!(has_width_typed(&sub, OpCode::SubTyped, NumericWidth::U64));
let mul = compile_top_level("let a: u64 = 100\nlet b: u64 = a * 2\n");
assert!(has_width_typed(&mul, OpCode::MulTyped, NumericWidth::U64));
}
#[test]
fn narrow_var_add_literal_stays_narrow_carrier() {
// `x + 28` on `x: i8` must emit `AddTyped` width I8 — the truncating
// narrow carrier — NOT the signed-default `AddInt`.
let instrs = compile_top_level(
"let x: i8 = 100\nlet y: i8 = x + 28\n",
);
assert!(
has_width_typed(&instrs, OpCode::AddTyped, NumericWidth::I8),
"i8 + literal must emit AddTyped(I8): {:?}",
instrs.iter().map(|i| i.opcode).collect::<Vec<_>>()
);
assert!(!has_opcode(&instrs, OpCode::AddInt));
}
#[test]
fn narrow_u32_div_literal_stays_narrow_carrier() {
let instrs = compile_top_level(
"let x: u32 = 4000000000\nlet y: u32 = x / 4\n",
);
assert!(
has_width_typed(&instrs, OpCode::DivTyped, NumericWidth::U32),
"u32 / literal must emit DivTyped(U32)"
);
assert!(!has_opcode(&instrs, OpCode::DivInt));
}
#[test]
fn plain_int_var_div_literal_still_emits_div_int() {
// Guard: the default `int` (i64) path is unchanged — `n / 2` on
// `n: int` still emits the signed `DivInt`, not `DivTyped`.
let instrs = compile_top_level("let n: int = 100\nlet m: int = n / 2\n");
assert!(
has_opcode(&instrs, OpCode::DivInt),
"int / literal must still emit DivInt"
);
}
// ── end-to-end execution coverage (unsigned semantics) ──
/// Compile + execute a top-level program and return the raw u64 bits of
/// the final expression.
fn run_top_level(code: &str) -> u64 {
use crate::VMConfig;
use crate::executor::VirtualMachine;
let program = shape_ast::parser::parse_program(code).expect("parse failed");
let compiler = super::super::super::BytecodeCompiler::new();
let bytecode = compiler.compile(&program).expect("compile failed");
let mut vm = VirtualMachine::new(VMConfig::default());
vm.load_program(bytecode);
vm.execute_raw(None).expect("execution failed")
}
#[test]
fn u64_max_div_literal_computes_unsigned() {
// u64::MAX / 2 == 9223372036854775807 (unsigned). A signed reinterpret
// computes (-1) / 2 == 0.
let bits = run_top_level("let a: u64 = 18446744073709551615\na / 2\n");
assert_eq!(bits, 9_223_372_036_854_775_807);
}
#[test]
fn u64_max_mod_literal_computes_unsigned() {
// u64::MAX % 10 == 5 (unsigned). Signed would give -1.
let bits = run_top_level("let a: u64 = 18446744073709551615\na % 10\n");
assert_eq!(bits, 5);
}
#[test]
fn u64_literal_left_div_var_computes_unsigned() {
// 100 / u64::MAX == 0 (unsigned). A signed reinterpret of u64::MAX as
// -1 would compute 100 / -1 == -100.
let bits = run_top_level("let a: u64 = 18446744073709551615\n100 / a\n");
assert_eq!(bits, 0);
}
#[test]
fn u64_add_sub_mul_literal_wrap_at_2_pow_64() {
// a + 1 wraps u64::MAX → 0.
assert_eq!(
run_top_level("let a: u64 = 18446744073709551615\na + 1\n"),
0
);
// a - 1 on u64::MAX → u64::MAX - 1.
assert_eq!(
run_top_level("let a: u64 = 18446744073709551615\na - 1\n"),
18_446_744_073_709_551_614
);
// (2^63) * 2 wraps mod 2^64 → 0.
assert_eq!(
run_top_level("let m: u64 = 9223372036854775808\nm * 2\n"),
0
);
}
}
#[cfg(test)]
mod ws3_f3_error_context_tests {
//! WS-3 F3: the `!!` error-context operator compiles.
//!
//! Before this fix `compile_expr_binary_op` had no
//! `BinaryOp::ErrorContext` arm, so `!!` fell into the generic
//! arithmetic arm whose strict-operand-type gate rejected the
//! `Result<…>` left operand — a core operator could not be compiled
//! at all. The opcode (`OpCode::ErrorContext`) and the runtime
//! handler (`op_error_context`) already existed; only the
//! compiler-dispatch arm was missing.
use crate::compiler::BytecodeCompiler;
use shape_ast::parser::parse_program;
#[test]
fn ws3_f3_error_context_operator_compiles() {
let code = r#"
fn boom() -> Result<int, string> { Err("bad") }
fn main() -> Result<int, string> {
let v = boom() !! "ctx"
print(v)
Ok(0)
}
"#;
let program = parse_program(code).expect("Failed to parse");
let result = BytecodeCompiler::new().compile(&program);
assert!(
result.is_ok(),
"`!!` error-context operator must compile: {:?}",
result.err()
);
}
#[test]
fn ws3_f3_error_context_unwrapped_type_propagates_to_binding() {
// `!!` yields the UNWRAPPED success value `T` (`Ok(v) => v`), so
// a downstream `v + 1` must type-check as `int + int`.
let code = r#"
fn good() -> Result<int, string> { Ok(99) }
fn main() -> Result<int, string> {
let v = good() !! "ctx"
let w = v + 1
print(w)
Ok(0)
}
"#;
let program = parse_program(code).expect("Failed to parse");
let result = BytecodeCompiler::new().compile(&program);
assert!(
result.is_ok(),
"`!!`-unwrapped value must keep its type for a downstream binop: {:?}",
result.err()
);
}
}
#[cfg(test)]
mod ws9c_anonymous_object_factory_tests {
//! WS-9c: an unannotated function returning an object literal built from
//! its parameters — `fn aabb(lo, hi) { {min: lo, max: hi} }` — is an
//! anonymous-object factory. Before this fix the object literal froze its
//! field types to `unknown` (no `TypeAnnotation` variable variant), so a
//! later `a.min + b.max` over the factory result was spuriously rejected
//! as `unknown + unknown`. The fix keeps the field-value parameters as
//! `tyvar` markers through inference, publishes `apply_callsite_unions`'
//! `resolved` fixpoint into the unifier, and registers an inline schema
//! for the inferred return so the compiler resolves `.field` access.
use crate::compiler::BytecodeCompiler;
use shape_ast::parser::parse_program;
fn compiles(code: &str) -> bool {
let program = parse_program(code).expect("Failed to parse");
BytecodeCompiler::new().compile(&program).is_ok()
}
#[test]
fn ws9c_factory_result_field_binop_compiles() {
// The headline repro: a binop over two factory results' fields.
assert!(compiles(
r#"
fn aabb(lo, hi) { {min: lo, max: hi} }
let a = aabb(1, 5)
let b = aabb(2, 6)
print(a.min + b.max)
"#
));
}
#[test]
fn ws9c_factory_result_through_unannotated_param_compiles() {
// The factory result threaded into a second unannotated function.
assert!(compiles(
r#"
fn aabb(lo, hi) { {min: lo, max: hi} }
fn area(box) { box.max - box.min }
print(area(aabb(1, 5)))
"#
));
}
#[test]
fn ws9c_factory_result_direct_field_access_compiles() {
// `f(...).field` directly, with no intervening `let` binding.
assert!(compiles(
r#"
fn aabb(lo, hi) { {min: lo, max: hi} }
print(aabb(1, 5).min + 1)
"#
));
}
#[test]
fn ws9c_factory_result_array_literal_compiles() {
// An array literal of factory results must compile — the element
// type resolves to the factory's anonymous-object return type rather
// than cascading an `unknown` element into `op_new_array`.
assert!(compiles(
r#"
fn aabb(lo, hi) { {min: lo, max: hi} }
let xs = [aabb(1, 5), aabb(2, 6)]
print(xs)
"#
));
}
}