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
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
//! The single Core checker.
//!
//! There is exactly one checker, here, and every front end goes through it
//! (`docs/design.md` Section 7). Every mutating operation gets back a
//! [`Report`] — the verification verdict (Section 6). An incomplete program
//! (one with holes) is not an error; it is a normal state.
//!
//! What is checked, and which Section 2 principle a failure maps to:
//!
//! - structural integrity — every referenced child hash is present (P4)
//! - locality — every name (binding or callee) resolves (P1)
//! - types — argument and result types honor declared signatures (P2)
//! - confidence — arguments meet each param's `min_confidence`, and a
//! function's result is no weaker than its declared `produces` (P7)
//! - effects — a function's `requires` covers every effect it performs,
//! effects propagating by union (P5)
//! - failures — every failure a callee declares is covered by the caller's
//! `on_failure` (P6)
//!
//! ## Why this is incremental
//!
//! The store is content-addressed, so a [`NodeHash`] denotes one immutable
//! subtree forever. Facts that depend only on a subtree's content
//! ([`SubtreeFacts`]: holes and structural integrity) are a pure function of
//! its hash and are memoized by hash; re-checking after an edit recomputes
//! only changed hashes. That is the Section 7 incrementality claim, falling
//! out of content-addressing rather than being engineered. The typed walk
//! (name/type/confidence/effect/failure) is context-dependent and is
//! recomputed; memoizing it on `(hash, scope)` is a later refinement.
use crate::node::{MatchArm, Node, NodeHash, Produces};
use crate::store::{Result, Store};
use crate::ty::{Confidence, Effect, Type};
use serde::Serialize;
use std::cell::Cell;
use std::collections::{BTreeSet, HashMap};
/// Whether a subtree has unfilled holes.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
pub enum Status {
/// No holes anywhere in the subtree.
Complete,
/// At least one hole remains. A normal state, not an error.
Incomplete,
}
/// Whether every callee-declared failure is covered by the caller.
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
pub enum Failures {
Exhaustive,
Uncovered(Vec<String>),
}
/// A broken design principle, with the offending node and a reason. The
/// `principle` is the Section 2 principle number.
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
pub struct Violation {
pub principle: u8,
pub node: NodeHash,
pub detail: String,
}
/// The verification verdict for a checked root (`docs/design.md` Section 6).
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
pub struct Report {
pub node: NodeHash,
pub status: Status,
pub holes: Vec<NodeHash>,
/// Effects actually performed (union of callee `requires`).
pub effects: BTreeSet<Effect>,
/// Confidence at the produces site, when inferable.
pub confidence: Option<Confidence>,
pub failures: Failures,
pub violations: Vec<Violation>,
}
impl Report {
/// True when nothing invalid was found. Holes are not violations, so an
/// `Incomplete` report can still be `ok`.
pub fn ok(&self) -> bool {
self.violations.is_empty()
}
}
/// A function's checkable contract, extracted from its node.
#[derive(Clone)]
struct Signature {
type_params: Vec<String>,
params: Vec<crate::node::Param>,
produces: Produces,
requires: BTreeSet<Effect>,
on_failure: Vec<String>,
}
/// Content-only facts about a subtree: holes it contains and referenced child
/// hashes absent from the store. A pure function of the subtree's hash.
#[derive(Clone, Default)]
struct SubtreeFacts {
holes: Vec<NodeHash>,
missing: Vec<NodeHash>,
}
/// What checking one function produced.
struct FnResult {
result_confidence: Option<Confidence>,
effects: BTreeSet<Effect>,
uncovered_failures: Vec<String>,
}
/// An ordered name → (type, confidence) scope. Later entries shadow earlier
/// ones; an entry is `None` when its value's type could not be inferred (so
/// dependent checks are skipped rather than cascading).
type Scope = Vec<(String, Option<(Type, Confidence)>)>;
/// Record type name → its fields.
type RecordTable = HashMap<String, Vec<(String, Type)>>;
/// Variant type name → its cases (case name → payload fields).
type VariantTable = HashMap<String, Vec<(String, Vec<(String, Type)>)>>;
/// The checker. Borrows a [`Store`]; owns a per-instance memo of
/// [`SubtreeFacts`] keyed by content hash.
pub struct Checker<'a> {
store: &'a Store,
facts: HashMap<NodeHash, SubtreeFacts>,
/// Populated from the root module at the start of `check`, read while
/// walking.
records: RecordTable,
variants: VariantTable,
computed: Cell<u64>,
}
impl<'a> Checker<'a> {
pub fn new(store: &'a Store) -> Self {
Self {
store,
facts: HashMap::new(),
records: HashMap::new(),
variants: HashMap::new(),
computed: Cell::new(0),
}
}
/// Nodes whose content-facts were computed rather than memoized. Used by
/// tests to demonstrate incrementality.
pub fn computed_count(&self) -> u64 {
self.computed.get()
}
/// Check the subtree rooted at `root` and produce its [`Report`].
pub fn check(&mut self, root: &NodeHash) -> Result<Report> {
let Some(root_node) = self.store.get(root)? else {
return Ok(Report {
node: root.clone(),
status: Status::Complete,
holes: Vec::new(),
effects: BTreeSet::new(),
confidence: None,
failures: Failures::Exhaustive,
violations: vec![Violation {
principle: 4,
node: root.clone(),
detail: "root node is not present in the store".into(),
}],
});
};
let facts = self.subtree_facts(root)?;
let mut violations: Vec<Violation> = facts
.missing
.iter()
.map(|h| Violation {
principle: 4,
node: h.clone(),
detail: "referenced child node is not present in the store".into(),
})
.collect();
let sigs = self.signatures(root, &root_node)?;
self.records = self.record_defs(&root_node)?;
self.variants = self.variant_defs(&root_node)?;
let mut effects = BTreeSet::new();
let mut confidence = None;
let mut uncovered: Vec<String> = Vec::new();
match &root_node {
Node::Function { .. } => {
let fr = self.check_function(root, &root_node, &sigs, &mut violations)?;
effects = fr.effects;
confidence = fr.result_confidence;
uncovered = fr.uncovered_failures;
}
Node::Module { functions, .. } => {
for fh in functions {
if let Some(fnode) = self.store.get(fh)? {
let fr = self.check_function(fh, &fnode, &sigs, &mut violations)?;
effects.extend(fr.effects);
for u in fr.uncovered_failures {
if !uncovered.contains(&u) {
uncovered.push(u);
}
}
}
}
}
_ => {
// A bare expression root: still report unresolved names.
let mut fl = BTreeSet::new();
confidence = self
.walk_expr(root, &[], &sigs, &mut violations, &mut effects, &mut fl)?
.map(|(_, c)| c);
}
}
Ok(Report {
node: root.clone(),
status: if facts.holes.is_empty() {
Status::Complete
} else {
Status::Incomplete
},
holes: facts.holes,
effects,
confidence,
failures: if uncovered.is_empty() {
Failures::Exhaustive
} else {
Failures::Uncovered(uncovered)
},
violations,
})
}
/// Content-only facts for a subtree, memoized by hash. The caller
/// guarantees `hash` is present in the store.
fn subtree_facts(&mut self, hash: &NodeHash) -> Result<SubtreeFacts> {
if let Some(cached) = self.facts.get(hash) {
return Ok(cached.clone());
}
self.computed.set(self.computed.get() + 1);
let node = self
.store
.get(hash)?
.expect("subtree_facts caller guarantees presence");
let mut facts = SubtreeFacts::default();
if let Node::Hole { .. } = node {
facts.holes.push(hash.clone());
}
for child in child_hashes(&node) {
match self.store.get(child)? {
None => facts.missing.push(child.clone()),
Some(_) => {
let sub = self.subtree_facts(child)?;
facts.holes.extend(sub.holes);
facts.missing.extend(sub.missing);
}
}
}
self.facts.insert(hash.clone(), facts.clone());
Ok(facts)
}
/// Build the name → [`Signature`] table the root resolves calls against:
/// every function in a module, or a lone function (so self-calls resolve).
fn signatures(&self, _root: &NodeHash, root_node: &Node) -> Result<HashMap<String, Signature>> {
let mut sigs = HashMap::new();
let mut add = |node: &Node| {
if let Node::Function {
name,
type_params,
params,
produces,
requires,
on_failure,
..
} = node
{
sigs.insert(
name.clone(),
Signature {
type_params: type_params.clone(),
params: params.clone(),
produces: produces.clone(),
requires: requires.clone(),
on_failure: on_failure.clone(),
},
);
}
};
match root_node {
Node::Function { .. } => add(root_node),
Node::Module { functions, .. } => {
for fh in functions {
if let Some(fnode) = self.store.get(fh)? {
add(&fnode);
}
}
}
_ => {}
}
Ok(sigs)
}
/// Build the record-type table the root resolves type names against:
/// every `RecordDef` in a module, or a lone `RecordDef`.
fn record_defs(&self, root_node: &Node) -> Result<RecordTable> {
let mut recs = HashMap::new();
let mut add = |node: &Node| {
if let Node::RecordDef { name, fields } = node {
recs.insert(name.clone(), fields.clone());
}
};
match root_node {
Node::RecordDef { .. } => add(root_node),
Node::Module { types, .. } => {
for th in types {
if let Some(tnode) = self.store.get(th)? {
add(&tnode);
}
}
}
_ => {}
}
Ok(recs)
}
/// Build the variant-type table: every `VariantDef` in a module, or a
/// lone `VariantDef`.
fn variant_defs(&self, root_node: &Node) -> Result<VariantTable> {
let mut vars = HashMap::new();
let mut add = |node: &Node| {
if let Node::VariantDef { name, cases } = node {
vars.insert(name.clone(), cases.clone());
}
};
match root_node {
Node::VariantDef { .. } => add(root_node),
Node::Module { types, .. } => {
for th in types {
if let Some(tnode) = self.store.get(th)? {
add(&tnode);
}
}
}
_ => {}
}
Ok(vars)
}
/// Check one function: scope, types, confidence, effects, failures.
fn check_function(
&self,
fn_hash: &NodeHash,
fn_node: &Node,
sigs: &HashMap<String, Signature>,
out: &mut Vec<Violation>,
) -> Result<FnResult> {
let Node::Function {
params,
produces,
requires,
on_failure,
body,
result,
..
} = fn_node
else {
return Ok(FnResult {
result_confidence: None,
effects: BTreeSet::new(),
uncovered_failures: Vec::new(),
});
};
let mut scope: Scope = params
.iter()
.map(|p| (p.name.clone(), Some((p.ty.clone(), p.min_confidence))))
.collect();
let mut effects = BTreeSet::new();
let mut failures = BTreeSet::new();
for step_hash in body {
let Some(step) = self.store.get(step_hash)? else {
continue;
};
if let Node::Step { binding, value } = &step {
let v = self
.walk_expr(value, &scope, sigs, out, &mut effects, &mut failures)?;
scope.push((binding.clone(), v));
}
}
let result_confidence = match self
.walk_expr(result, &scope, sigs, out, &mut effects, &mut failures)?
{
Some((rt, rc)) => {
if !compatible(&rt, &produces.ty) {
out.push(Violation {
principle: 2,
node: result.clone(),
detail: format!(
"result is {:?} but `produces` declares {:?}",
rt, produces.ty
),
});
}
if rc < produces.confidence {
out.push(Violation {
principle: 7,
node: result.clone(),
detail: format!(
"result confidence {:?} is weaker than declared {:?}",
rc, produces.confidence
),
});
}
Some(rc)
}
None => None,
};
// Effects propagate by union; `requires` must cover them (P5).
for e in &effects {
if !requires.contains(e) {
out.push(Violation {
principle: 5,
node: fn_hash.clone(),
detail: format!("performs effect {e:?} not declared in `requires`"),
});
}
}
// Every callee-declared failure must be in this function's
// `on_failure` (P6).
let mut uncovered_failures = Vec::new();
for f in &failures {
if !on_failure.contains(f) {
uncovered_failures.push(f.clone());
out.push(Violation {
principle: 6,
node: fn_hash.clone(),
detail: format!("failure `{f}` is not covered by `on_failure`"),
});
}
}
Ok(FnResult {
result_confidence,
effects,
uncovered_failures,
})
}
/// Infer an expression's `(type, confidence)`, reporting name, type, and
/// confidence violations and accumulating effects and failures. `None`
/// means "not inferable" (an unresolved name or a hole) — dependent checks
/// are then skipped rather than cascading.
#[allow(clippy::only_used_in_recursion)]
fn walk_expr(
&self,
hash: &NodeHash,
scope: &[(String, Option<(Type, Confidence)>)],
sigs: &HashMap<String, Signature>,
out: &mut Vec<Violation>,
effects: &mut BTreeSet<Effect>,
failures: &mut BTreeSet<String>,
) -> Result<Option<(Type, Confidence)>> {
let Some(node) = self.store.get(hash)? else {
// Absence is a structural violation, already reported via facts.
return Ok(None);
};
Ok(match node {
Node::Lit(_) => Some((Type::Number, Confidence::Structural)),
Node::FloatLit(_) => Some((Type::Float, Confidence::Structural)),
Node::FloatOp { op, lhs, rhs } => {
let l = self.walk_expr(&lhs, scope, sigs, out, effects, failures)?;
let r = self.walk_expr(&rhs, scope, sigs, out, effects, failures)?;
for (h, t) in [(&lhs, &l), (&rhs, &r)] {
if let Some((ty, _)) = t {
if *ty != Type::Float && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: h.clone(),
detail: format!(
"float operand is {ty:?}, expected Float"
),
});
}
}
}
let conf = match (&l, &r) {
(Some((_, a)), Some((_, b))) => (*a).min(*b),
_ => Confidence::Structural,
};
use crate::node::BinOp as B;
if op.is_logical() || op == B::Mod || op == B::Neq {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"operator `{}` is not defined on Float",
op.symbol()
),
});
None
} else if op.is_comparison() {
Some((Type::Bool, conf))
} else {
Some((Type::Float, conf))
}
}
Node::IntToFloat(a) => {
let t = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
if let Some((ty, c)) = t {
if ty != Type::Number && ty != Type::Never {
out.push(Violation {
principle: 2,
node: a.clone(),
detail: format!("to_float expects Number, got {ty:?}"),
});
}
Some((Type::Float, c))
} else {
None
}
}
Node::FloatToInt(a) => {
let t = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
if let Some((ty, c)) = t {
if ty != Type::Float && ty != Type::Never {
out.push(Violation {
principle: 2,
node: a.clone(),
detail: format!("to_int expects Float, got {ty:?}"),
});
}
Some((Type::Number, c))
} else {
None
}
}
Node::DecimalLit(_) => {
Some((Type::Decimal, Confidence::Structural))
}
Node::DecimalOp { op, lhs, rhs } => {
let l = self.walk_expr(&lhs, scope, sigs, out, effects, failures)?;
let r = self.walk_expr(&rhs, scope, sigs, out, effects, failures)?;
for (h, t) in [(&lhs, &l), (&rhs, &r)] {
if let Some((ty, _)) = t {
if *ty != Type::Decimal && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: h.clone(),
detail: format!(
"decimal operand is {ty:?}, expected Decimal"
),
});
}
}
}
let conf = match (&l, &r) {
(Some((_, a)), Some((_, b))) => (*a).min(*b),
_ => Confidence::Structural,
};
use crate::node::BinOp as B;
if op.is_logical() || op == B::Mod {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"operator `{}` is not defined on Decimal",
op.symbol()
),
});
None
} else if op.is_comparison() {
Some((Type::Bool, conf))
} else {
Some((Type::Decimal, conf))
}
}
Node::IntToDecimal(a) => {
let t = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
if let Some((ty, c)) = t {
if ty != Type::Number && ty != Type::Never {
out.push(Violation {
principle: 2,
node: a.clone(),
detail: format!(
"to_decimal expects Number, got {ty:?}"
),
});
}
Some((Type::Decimal, c))
} else {
None
}
}
Node::DecimalToInt(a) | Node::DecimalRaw(a) => {
let t = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
if let Some((ty, c)) = t {
if ty != Type::Decimal && ty != Type::Never {
out.push(Violation {
principle: 2,
node: a.clone(),
detail: format!(
"expects Decimal, got {ty:?}"
),
});
}
Some((Type::Number, c))
} else {
None
}
}
Node::Bool(_) => Some((Type::Bool, Confidence::Structural)),
Node::Not(arg) => {
let a = self.walk_expr(&arg, scope, sigs, out, effects, failures)?;
if let Some((at, ac)) = a {
if at != Type::Bool && at != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!("`!` operand is {at:?}, expected Bool"),
});
}
Some((Type::Bool, ac))
} else {
None
}
}
Node::Str(_) => Some((Type::String, Confidence::Structural)),
Node::Now => {
// Performs the Time effect (the existing P5 coverage check
// then requires the enclosing function to declare it) and
// yields an external-confidence Number.
effects.insert(Effect::Time);
Some((Type::Number, Confidence::External))
}
Node::List(elems) => {
if elems.is_empty() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: "empty list literal needs a type annotation (v0.3)"
.into(),
});
return Ok(None);
}
let mut elem_ty: Option<Type> = None;
let mut conf = Confidence::Persisted;
for e in &elems {
if let Some((t, c)) =
self.walk_expr(e, scope, sigs, out, effects, failures)?
{
match &elem_ty {
None => elem_ty = Some(t),
Some(et) => {
if !compatible(et, &t) {
out.push(Violation {
principle: 2,
node: e.clone(),
detail: format!(
"list element is {t:?}, expected {et:?}"
),
});
}
}
}
conf = conf.min(c);
}
}
elem_ty.map(|t| (Type::List(Box::new(t)), conf))
}
Node::ListEmpty { elem } => {
Some((Type::List(Box::new(elem)), Confidence::Structural))
}
Node::ListCons { head, tail } => {
let ht = self.walk_expr(&head, scope, sigs, out, effects, failures)?;
let tt = self.walk_expr(&tail, scope, sigs, out, effects, failures)?;
match tt {
Some((Type::List(et), tc)) => {
if let Some((h, _)) = &ht {
if !compatible(&et, h) {
out.push(Violation {
principle: 2,
node: head.clone(),
detail: format!(
"cons head is {h:?} but the list is List<{et:?}>"
),
});
}
}
let hc =
ht.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((Type::List(et), hc.min(tc)))
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: tail.clone(),
detail: format!(
"cons tail must be a List, got {other:?}"
),
});
None
}
None => None,
}
}
Node::OptionSome(v) => self
.walk_expr(&v, scope, sigs, out, effects, failures)?
.map(|(t, c)| (Type::Option(Box::new(t)), c)),
Node::OptionNone { elem } => {
Some((Type::Option(Box::new(elem)), Confidence::Structural))
}
Node::OptionElse { opt, default } => {
let ot = self.walk_expr(&opt, scope, sigs, out, effects, failures)?;
let dt =
self.walk_expr(&default, scope, sigs, out, effects, failures)?;
match ot {
Some((Type::Option(inner), oc)) => {
if let Some((d, _)) = &dt {
if !compatible(&inner, d) {
out.push(Violation {
principle: 2,
node: default.clone(),
detail: format!(
"option default is {d:?} but the Option holds {inner:?}"
),
});
}
}
let dc =
dt.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((*inner, oc.min(dc)))
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: opt.clone(),
detail: format!(
"option_else expects an Option, got {other:?}"
),
});
None
}
None => None,
}
}
Node::OptionMatch {
opt,
some_bind,
some_body,
none_body,
} => {
let ot = self.walk_expr(&opt, scope, sigs, out, effects, failures)?;
let (inner, oc) = match ot {
Some((Type::Option(inner), oc)) => (*inner, oc),
Some((Type::Never, oc)) => (Type::Never, oc),
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: opt.clone(),
detail: format!(
"OptionMatch scrutinee is {other:?}, expected Option"
),
});
return Ok(None);
}
None => return Ok(None),
};
let mut s2 = scope.to_vec();
s2.push((some_bind.clone(), Some((inner, oc))));
let st = self.walk_expr(
&some_body, &s2, sigs, out, effects, failures,
)?;
let nt = self.walk_expr(
&none_body, scope, sigs, out, effects, failures,
)?;
match (st, nt) {
(Some((s, sc)), Some((n, nc))) => {
if !compatible(&s, &n) {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"OptionMatch arms differ: {s:?} vs {n:?}"
),
});
}
let ty = if s == Type::Never { n } else { s };
Some((ty, oc.min(sc).min(nc)))
}
(Some(v), None) | (None, Some(v)) => Some(v),
(None, None) => None,
}
}
Node::ListTryGet { list, index } => {
let lt = self.walk_expr(&list, scope, sigs, out, effects, failures)?;
let it = self.walk_expr(&index, scope, sigs, out, effects, failures)?;
if let Some((t, _)) = &it {
if *t != Type::Number && *t != Type::Never {
out.push(Violation {
principle: 2,
node: index.clone(),
detail: format!("list index is {t:?}, expected Number"),
});
}
}
match lt {
Some((Type::List(elem), lc)) => {
let ic =
it.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((Type::Option(elem), lc.min(ic)))
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: list.clone(),
detail: format!(
"list_try_get on a non-List type {other:?}"
),
});
None
}
None => None,
}
}
Node::ListLen(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((Type::List(_), c)) => Some((Type::Number, c)),
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!("list_len expects a List, got {other:?}"),
});
None
}
None => None,
}
}
Node::ListGet { list, index } => {
let lt = self.walk_expr(&list, scope, sigs, out, effects, failures)?;
let it = self.walk_expr(&index, scope, sigs, out, effects, failures)?;
if let Some((t, _)) = &it {
if *t != Type::Number && *t != Type::Never {
out.push(Violation {
principle: 2,
node: index.clone(),
detail: format!("list index is {t:?}, expected Number"),
});
}
}
match lt {
Some((Type::List(elem), lc)) => {
let ic = it.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((*elem, lc.min(ic)))
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: list.clone(),
detail: format!("list_get on a non-List type {other:?}"),
});
None
}
None => None,
}
}
Node::Map(pairs) => {
if pairs.is_empty() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: "empty map literal needs a type annotation (v0.3)"
.into(),
});
return Ok(None);
}
let mut kt: Option<Type> = None;
let mut vt: Option<Type> = None;
let mut conf = Confidence::Persisted;
for (k, v) in &pairs {
if let Some((t, c)) =
self.walk_expr(k, scope, sigs, out, effects, failures)?
{
match &kt {
None => kt = Some(t),
Some(e) => {
if !compatible(e, &t) {
out.push(Violation {
principle: 2,
node: k.clone(),
detail: format!(
"map key is {t:?}, expected {e:?}"
),
});
}
}
}
conf = conf.min(c);
}
if let Some((t, c)) =
self.walk_expr(v, scope, sigs, out, effects, failures)?
{
match &vt {
None => vt = Some(t),
Some(e) => {
if !compatible(e, &t) {
out.push(Violation {
principle: 2,
node: v.clone(),
detail: format!(
"map value is {t:?}, expected {e:?}"
),
});
}
}
}
conf = conf.min(c);
}
}
match (kt, vt) {
(Some(k), Some(v)) => {
Some((Type::Map(Box::new(k), Box::new(v)), conf))
}
_ => None,
}
}
Node::MapGet { map, key } => {
let mt = self.walk_expr(&map, scope, sigs, out, effects, failures)?;
let kt = self.walk_expr(&key, scope, sigs, out, effects, failures)?;
match mt {
Some((Type::Map(k, v), mc)) => {
if let Some((t, _)) = &kt {
if !compatible(&k, t) {
out.push(Violation {
principle: 2,
node: key.clone(),
detail: format!(
"map key is {t:?}, expected {k:?}"
),
});
}
}
let kc = kt.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((*v, mc.min(kc)))
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: map.clone(),
detail: format!("map_get on a non-Map type {other:?}"),
});
None
}
None => None,
}
}
Node::MapTryGet { map, key } => {
let mt = self.walk_expr(&map, scope, sigs, out, effects, failures)?;
let kt = self.walk_expr(&key, scope, sigs, out, effects, failures)?;
match mt {
Some((Type::Map(k, v), mc)) => {
if let Some((t, _)) = &kt {
if !compatible(&k, t) {
out.push(Violation {
principle: 2,
node: key.clone(),
detail: format!(
"map key is {t:?}, expected {k:?}"
),
});
}
}
let kc = kt.map(|(_, c)| c).unwrap_or(Confidence::Persisted);
Some((Type::Option(v), mc.min(kc)))
}
Some((Type::Never, c)) => Some((Type::Never, c)),
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: map.clone(),
detail: format!("map_try_get on a non-Map type {other:?}"),
});
None
}
None => None,
}
}
Node::MapLen(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((Type::Map(_, _), c)) => Some((Type::Number, c)),
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!("map_len expects a Map, got {other:?}"),
});
None
}
None => None,
}
}
Node::Log(arg) => {
// Performs the Log effect; passes the value through
// unchanged (same type and confidence).
effects.insert(Effect::Log);
self.walk_expr(&arg, scope, sigs, out, effects, failures)?
}
Node::Publish(arg) => {
// Performs the Live effect. `topic` must be a String;
// yields Number (0). The checker forces `requires Live`
// on any function that can publish — liveness visible.
effects.insert(Effect::Live);
let t =
self.walk_expr(&arg, scope, sigs, out, effects, failures)?;
if let Some((ty, _)) = t {
if ty != Type::String && ty != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"publish topic is {ty:?}, expected String"
),
});
}
}
Some((Type::Number, Confidence::Structural))
}
Node::SetHeader { name, value } => {
// Performs the Resp effect. `name` and `value` must be
// String; yields Number (0) so it sequences like
// `publish`. The checker forces `requires Resp` on any
// function that can set a header — visible, not hidden.
effects.insert(Effect::Resp);
for (label, arg) in
[("name", &name), ("value", &value)]
{
let t = self.walk_expr(
arg, scope, sigs, out, effects, failures,
)?;
if let Some((ty, _)) = t {
if ty != Type::String && ty != Type::Never {
out.push(Violation {
principle: 2,
node: (*arg).clone(),
detail: format!(
"set_header {label} is {ty:?}, \
expected String"
),
});
}
}
}
Some((Type::Number, Confidence::Structural))
}
Node::Rand => {
effects.insert(Effect::Rand);
Some((Type::Number, Confidence::External))
}
Node::MutNew(v) => {
effects.insert(Effect::Mut);
self.walk_expr(&v, scope, sigs, out, effects, failures)?
.map(|(t, c)| (Type::Cell(Box::new(t)), c))
}
Node::MutGet(cell) => {
match self.walk_expr(&cell, scope, sigs, out, effects, failures)? {
Some((Type::Cell(t), c)) => Some((*t, c)),
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: cell.clone(),
detail: format!("cell_get on a non-Cell type {other:?}"),
});
None
}
None => None,
}
}
Node::MutSet { cell, value } => {
effects.insert(Effect::Mut);
let ct = self.walk_expr(&cell, scope, sigs, out, effects, failures)?;
let vt =
self.walk_expr(&value, scope, sigs, out, effects, failures)?;
if let (Some((Type::Cell(et), _)), Some((vty, _))) = (&ct, &vt) {
if !compatible(et, vty) {
out.push(Violation {
principle: 2,
node: value.clone(),
detail: format!(
"cell holds {et:?} but assigned {vty:?}"
),
});
}
} else if let Some((other, _)) = &ct {
if !matches!(other, Type::Cell(_)) {
out.push(Violation {
principle: 2,
node: cell.clone(),
detail: format!("cell_set on a non-Cell type {other:?}"),
});
}
}
vt // pass-through
}
Node::DiskWrite { path, content } => {
effects.insert(Effect::Disk);
let p = self.walk_expr(&path, scope, sigs, out, effects, failures)?;
let cn =
self.walk_expr(&content, scope, sigs, out, effects, failures)?;
for (n, t) in [(&path, &p), (&content, &cn)] {
if let Some((ty, _)) = t {
if *ty != Type::String && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: n.clone(),
detail: format!("disk_write expects String, got {ty:?}"),
});
}
}
}
Some((Type::Number, Confidence::External))
}
Node::DiskRead(path) => {
effects.insert(Effect::Disk);
if let Some((t, _)) =
self.walk_expr(&path, scope, sigs, out, effects, failures)?
{
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: path.clone(),
detail: format!("disk_read expects String, got {t:?}"),
});
}
}
// Returns the file's contents (host→wasm allocation), at
// external confidence (it comes from outside the program).
Some((Type::String, Confidence::External))
}
Node::NetGet(url) => {
effects.insert(Effect::Net);
if let Some((t, _)) =
self.walk_expr(&url, scope, sigs, out, effects, failures)?
{
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: url.clone(),
detail: format!("net_get expects String, got {t:?}"),
});
}
}
Some((Type::Number, Confidence::External))
}
Node::DbQuery { sql, params } => {
effects.insert(Effect::Db);
if let Some((t, _)) =
self.walk_expr(&sql, scope, sigs, out, effects, failures)?
{
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: sql.clone(),
detail: format!("db_query expects String, got {t:?}"),
});
}
}
if let Some((t, _)) =
self.walk_expr(¶ms, scope, sigs, out, effects, failures)?
{
let ok = matches!(&t, Type::List(e) if **e == Type::String)
|| t == Type::Never;
if !ok {
out.push(Violation {
principle: 2,
node: params.clone(),
detail: format!(
"db_query params must be List<String>, got {t:?}"
),
});
}
}
// Reading back from the system of record yields a `String`
// result at `persisted` confidence — the decided definition.
Some((Type::String, Confidence::Persisted))
}
Node::StrConcat(a, b) => {
let at = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
let bt = self.walk_expr(&b, scope, sigs, out, effects, failures)?;
for (n, t) in [(&a, &at), (&b, &bt)] {
if let Some((ty, _)) = t {
if *ty != Type::String && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: n.clone(),
detail: format!("str_concat expects String, got {ty:?}"),
});
}
}
}
let c = at
.map(|(_, c)| c)
.unwrap_or(Confidence::Persisted)
.min(bt.map(|(_, c)| c).unwrap_or(Confidence::Persisted));
Some((Type::String, c))
}
Node::StrSlice { s, start, len } => {
let st = self.walk_expr(&s, scope, sigs, out, effects, failures)?;
let stt =
self.walk_expr(&start, scope, sigs, out, effects, failures)?;
let lnt = self.walk_expr(&len, scope, sigs, out, effects, failures)?;
if let Some((t, _)) = &st {
if *t != Type::String && *t != Type::Never {
out.push(Violation {
principle: 2,
node: s.clone(),
detail: format!("str_slice expects String, got {t:?}"),
});
}
}
for (n, t) in [(&start, &stt), (&len, &lnt)] {
if let Some((ty, _)) = t {
if *ty != Type::Number && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: n.clone(),
detail: format!("str_slice index is {ty:?}, expected Number"),
});
}
}
}
let c = [st, stt, lnt]
.into_iter()
.flatten()
.map(|(_, c)| c)
.min()
.unwrap_or(Confidence::Structural);
Some((Type::String, c))
}
Node::StrEq(a, b)
| Node::StrContains { haystack: a, needle: b }
| Node::StrStartsWith { s: a, prefix: b } => {
let at = self.walk_expr(&a, scope, sigs, out, effects, failures)?;
let bt = self.walk_expr(&b, scope, sigs, out, effects, failures)?;
for (n, t) in [(&a, &at), (&b, &bt)] {
if let Some((ty, _)) = t {
if *ty != Type::String && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: n.clone(),
detail: format!("string op expects String, got {ty:?}"),
});
}
}
}
let c = at
.map(|(_, c)| c)
.unwrap_or(Confidence::Persisted)
.min(bt.map(|(_, c)| c).unwrap_or(Confidence::Persisted));
Some((Type::Bool, c))
}
Node::StrIndexOf { haystack, needle } => {
let ht =
self.walk_expr(&haystack, scope, sigs, out, effects, failures)?;
let nt =
self.walk_expr(&needle, scope, sigs, out, effects, failures)?;
for (node, t) in [(&haystack, &ht), (&needle, &nt)] {
if let Some((ty, _)) = t {
if *ty != Type::String && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: node.clone(),
detail: format!(
"string op expects String, got {ty:?}"
),
});
}
}
}
let c = ht
.map(|(_, c)| c)
.unwrap_or(Confidence::Persisted)
.min(nt.map(|(_, c)| c).unwrap_or(Confidence::Persisted));
Some((Type::Number, c))
}
Node::StrLen(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!("str_len expects String, got {t:?}"),
});
}
Some((Type::Number, c))
}
None => None,
}
}
Node::StrLower(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"str_lower expects String, got {t:?}"
),
});
}
Some((Type::String, c))
}
None => None,
}
}
Node::StrFromCode(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::Number && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"str_from_code expects Number, got {t:?}"
),
});
}
Some((Type::String, c))
}
None => None,
}
}
Node::NumberToStr(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::Number && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"number_to_str expects Number, got {t:?}"
),
});
}
Some((Type::String, c))
}
None => None,
}
}
Node::StrToNumber(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"str_to_number expects String, got {t:?}"
),
});
}
Some((Type::Number, c))
}
None => None,
}
}
Node::StrToNumberOpt(arg) => {
match self.walk_expr(&arg, scope, sigs, out, effects, failures)? {
Some((t, c)) => {
if t != Type::String && t != Type::Never {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"str_to_number_opt expects String, got {t:?}"
),
});
}
Some((Type::Option(Box::new(Type::Number)), c))
}
None => None,
}
}
Node::Hole { .. } => None,
Node::Ref(name) => {
match scope.iter().rev().find(|(n, _)| n == &name) {
Some((_, v)) => v.clone(),
None => {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unresolved reference: `{name}`"),
});
None
}
}
}
Node::Step { value, .. } => {
self.walk_expr(&value, scope, sigs, out, effects, failures)?
}
Node::Fail(f) => {
// Diverges: contributes the variant to the propagated failure
// set (the existing P6 coverage check enforces `on_failure`),
// has type Never, and carries top confidence so it never
// drags a weakest-input minimum.
failures.insert(f);
Some((Type::Never, Confidence::Persisted))
}
Node::Handle { body, handlers } => {
// Body failures are scoped here: handled variants are caught
// and do not propagate; everything else does.
let mut body_f = BTreeSet::new();
let b = self.walk_expr(&body, scope, sigs, out, effects, &mut body_f)?;
for f in &body_f {
if !handlers.iter().any(|(v, _)| v == f) {
failures.insert(f.clone());
}
}
match b {
None => None,
Some((bt, bc)) => {
let mut conf = bc;
for (_, recover) in &handlers {
if let Some((rt, rc)) = self
.walk_expr(recover, scope, sigs, out, effects, failures)?
{
if !compatible(&rt, &bt) {
out.push(Violation {
principle: 2,
node: recover.clone(),
detail: format!(
"handler recovers as {rt:?} but the value is {bt:?}"
),
});
}
conf = conf.min(rc);
}
}
Some((bt, conf))
}
}
}
Node::If {
cond,
then_branch,
else_branch,
} => {
let c = self.walk_expr(&cond, scope, sigs, out, effects, failures)?;
let t = self.walk_expr(&then_branch, scope, sigs, out, effects, failures)?;
let e = self.walk_expr(&else_branch, scope, sigs, out, effects, failures)?;
if let Some((ct, _)) = &c {
if *ct != Type::Bool && *ct != Type::Never {
out.push(Violation {
principle: 2,
node: cond.clone(),
detail: format!("condition is {ct:?}, expected Bool"),
});
}
}
match (t, e) {
(Some((tt, tc)), Some((et, ec))) => {
if !compatible(&tt, &et) {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"branch types differ: {tt:?} vs {et:?}"
),
});
}
// A `fail` branch is Never; the if's type is the other
// branch's. Weakest input over condition and branches.
let rty = if tt == Type::Never { et } else { tt };
let mut conf = tc.min(ec);
if let Some((_, cc)) = c {
conf = conf.min(cc);
}
Some((rty, conf))
}
_ => None,
}
}
Node::BinOp { op, lhs, rhs } => {
let l = self.walk_expr(&lhs, scope, sigs, out, effects, failures)?;
let r = self.walk_expr(&rhs, scope, sigs, out, effects, failures)?;
match (l, r) {
(Some((lt, lc)), Some((rt, rc))) => {
// Weakest-input propagation (the decided rule, now with
// a real site): a derived value's confidence is the
// minimum of its inputs'.
let conf = lc.min(rc);
if op.is_logical() {
for (operand, ty) in [(&lhs, <), (&rhs, &rt)] {
if *ty != Type::Bool && *ty != Type::Never {
out.push(Violation {
principle: 2,
node: operand.clone(),
detail: format!(
"logical operand is {ty:?}, expected Bool"
),
});
}
}
Some((Type::Bool, conf))
} else if op.is_comparison() {
if !compatible(<, &rt) {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"comparison operands differ: {lt:?} vs {rt:?}"
),
});
}
Some((Type::Bool, conf))
} else {
if lt != Type::Number && lt != Type::Never {
out.push(Violation {
principle: 2,
node: lhs.clone(),
detail: format!(
"arithmetic operand is {lt:?}, expected Number"
),
});
}
if rt != Type::Number && rt != Type::Never {
out.push(Violation {
principle: 2,
node: rhs.clone(),
detail: format!(
"arithmetic operand is {rt:?}, expected Number"
),
});
}
Some((Type::Number, conf))
}
}
_ => None,
}
}
Node::Call { func, args } => {
let Some(sig) = sigs.get(&func) else {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unresolved function: `{func}`"),
});
for arg in &args {
self.walk_expr(arg, scope, sigs, out, effects, failures)?;
}
return Ok(None);
};
if args.len() != sig.params.len() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"`{func}` takes {} argument(s), {} given",
sig.params.len(),
args.len()
),
});
}
// Unify each parameter type (which may mention a type
// variable) against the actual argument type, building a
// substitution. For a monomorphic function this is just
// structural equality.
let mut subst: HashMap<String, Type> = HashMap::new();
for (i, arg) in args.iter().enumerate() {
let inferred =
self.walk_expr(arg, scope, sigs, out, effects, failures)?;
if let (Some((at, ac)), Some(p)) = (inferred, sig.params.get(i)) {
if !unify(&p.ty, &at, &mut subst) {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"argument `{}` is {:?} but `{func}` expects {:?}",
p.name, at, p.ty
),
});
}
if ac < p.min_confidence {
out.push(Violation {
principle: 7,
node: arg.clone(),
detail: format!(
"argument `{}` is {:?} but `{func}` requires at least {:?}",
p.name, ac, p.min_confidence
),
});
}
}
}
effects.extend(sig.requires.iter().copied());
failures.extend(sig.on_failure.iter().cloned());
let result_ty = substitute(&sig.produces.ty, &subst);
// A type parameter occurring in the result must also occur
// in some parameter, else no argument can pin it (e.g.
// `make<T>() -> T`). A still-`Var` result *after*
// unification is fine — it may be bound to the caller's
// own opaque type variable, as in generic recursion
// (`fold` calling `fold_at`).
for tp in &sig.type_params {
if ty_mentions(&sig.produces.ty, tp)
&& !sig.params.iter().any(|p| ty_mentions(&p.ty, tp))
{
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"type parameter `{tp}` of `{func}` appears only \
in the result and cannot be inferred"
),
});
}
}
Some((result_ty, sig.produces.confidence))
}
Node::FuncRef(name) => {
let Some(sig) = sigs.get(&name) else {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unresolved function: `{name}`"),
});
return Ok(None);
};
// K1 boundary (documented): a function *value* lowers to one
// `call_indirect` of a fixed type, so it cannot be generic
// (no instantiation site) nor fallible (its `[tag,val]`
// return would leak as the value). Both are honest
// restrictions, not fakes — closures/lambdas come next.
if !sig.type_params.is_empty() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"cannot take a function value of generic `{name}` (v0.4)"
),
});
}
if !sig.on_failure.is_empty() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"cannot take a function value of fallible `{name}` (v0.4)"
),
});
}
let fn_ty = Type::Fn {
params: sig.params.iter().map(|p| p.ty.clone()).collect(),
ret: Box::new(sig.produces.ty.clone()),
effects: sig.requires.clone(),
};
Some((fn_ty, Confidence::Structural))
}
Node::CallValue { callee, args } => {
let c =
self.walk_expr(&callee, scope, sigs, out, effects, failures)?;
let (cty, cconf) = match c {
Some(v) => v,
None => {
for arg in &args {
self.walk_expr(
arg, scope, sigs, out, effects, failures,
)?;
}
return Ok(None);
}
};
let Type::Fn {
params,
ret,
effects: fx,
} = cty
else {
if cty != Type::Never {
out.push(Violation {
principle: 2,
node: callee.clone(),
detail: format!(
"callee is {cty:?}, not a function value"
),
});
}
for arg in &args {
self.walk_expr(
arg, scope, sigs, out, effects, failures,
)?;
}
return Ok(None);
};
if args.len() != params.len() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"function value takes {} argument(s), {} given",
params.len(),
args.len()
),
});
}
// Weakest-input propagation across callee and arguments.
let mut conf = cconf;
for (i, arg) in args.iter().enumerate() {
let inferred =
self.walk_expr(arg, scope, sigs, out, effects, failures)?;
if let (Some((at, ac)), Some(pt)) = (inferred, params.get(i)) {
if !compatible(pt, &at) {
out.push(Violation {
principle: 2,
node: arg.clone(),
detail: format!(
"argument {i} is {at:?} but the function \
value expects {pt:?}"
),
});
}
conf = conf.min(ac);
}
}
effects.extend(fx.iter().copied());
Some((*ret, conf))
}
Node::Lambda { params, body } => {
// The body sees the enclosing scope plus the lambda's own
// params. Effects and failures are isolated: making a
// closure performs nothing — its effects belong to the
// `Fn` and fire at the call site (`CallValue` unions them).
let mut s2 = scope.to_vec();
for p in ¶ms {
s2.push((
p.name.clone(),
Some((p.ty.clone(), p.min_confidence)),
));
}
let mut lam_fx = BTreeSet::new();
let mut lam_fail = BTreeSet::new();
let bt = self.walk_expr(
&body, &s2, sigs, out, &mut lam_fx, &mut lam_fail,
)?;
if !lam_fail.is_empty() {
out.push(Violation {
principle: 6,
node: hash.clone(),
detail: format!(
"a lambda may not raise an uncaught failure: {} (v0.4)",
lam_fail.iter().cloned().collect::<Vec<_>>().join(", ")
),
});
}
let ret = bt.map(|(t, _)| t).unwrap_or(Type::Never);
let fn_ty = Type::Fn {
params: params.iter().map(|p| p.ty.clone()).collect(),
ret: Box::new(ret),
effects: lam_fx,
};
Some((fn_ty, Confidence::Structural))
}
Node::Record { type_name, fields } => {
match self.records.get(&type_name).cloned() {
None => {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unknown record type: `{type_name}`"),
});
for (_, fh) in &fields {
self.walk_expr(fh, scope, sigs, out, effects, failures)?;
}
None
}
Some(def_fields) => {
let mut conf = Confidence::Persisted;
for (fname, fty) in &def_fields {
match fields.iter().find(|(n, _)| n == fname) {
None => out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"missing field `{fname}` for `{type_name}`"
),
}),
Some((_, fh)) => {
if let Some((vt, vc)) = self.walk_expr(
fh, scope, sigs, out, effects, failures,
)? {
if !compatible(&vt, fty) {
out.push(Violation {
principle: 2,
node: fh.clone(),
detail: format!(
"field `{fname}` is {vt:?}, expected {fty:?}"
),
});
}
conf = conf.min(vc);
}
}
}
}
for (n, fh) in &fields {
if !def_fields.iter().any(|(dn, _)| dn == n) {
out.push(Violation {
principle: 2,
node: fh.clone(),
detail: format!("`{type_name}` has no field `{n}`"),
});
self.walk_expr(fh, scope, sigs, out, effects, failures)?;
}
}
if def_fields.is_empty() {
conf = Confidence::Structural;
}
Some((Type::Named(type_name.clone()), conf))
}
}
}
Node::Field {
base,
type_name,
field,
} => {
match self.walk_expr(&base, scope, sigs, out, effects, failures)? {
Some((Type::Named(rec), bc)) => {
if rec != type_name {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"field access typed as `{type_name}` but base is `{rec}`"
),
});
}
match self.records.get(&rec) {
Some(fs) => match fs.iter().find(|(n, _)| n == &field) {
Some((_, fty)) => Some((fty.clone(), bc)),
None => {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!("`{rec}` has no field `{field}`"),
});
None
}
},
None => {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unknown record type: `{rec}`"),
});
None
}
}
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: base.clone(),
detail: format!(
"field access on non-record type {other:?}"
),
});
None
}
None => None,
}
}
Node::Variant {
type_name,
case,
fields,
} => match self.variants.get(&type_name).cloned() {
None => {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unknown variant type: `{type_name}`"),
});
for (_, fh) in &fields {
self.walk_expr(fh, scope, sigs, out, effects, failures)?;
}
None
}
Some(cases) => match cases.iter().find(|(c, _)| c == &case) {
None => {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!("`{type_name}` has no case `{case}`"),
});
for (_, fh) in &fields {
self.walk_expr(fh, scope, sigs, out, effects, failures)?;
}
None
}
Some((_, payload)) => {
let payload = payload.clone();
let mut conf = Confidence::Persisted;
for (fname, fty) in &payload {
match fields.iter().find(|(n, _)| n == fname) {
None => out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"missing field `{fname}` for `{type_name}.{case}`"
),
}),
Some((_, fh)) => {
if let Some((vt, vc)) = self.walk_expr(
fh, scope, sigs, out, effects, failures,
)? {
if !compatible(&vt, fty) {
out.push(Violation {
principle: 2,
node: fh.clone(),
detail: format!(
"field `{fname}` is {vt:?}, expected {fty:?}"
),
});
}
conf = conf.min(vc);
}
}
}
}
for (n, fh) in &fields {
if !payload.iter().any(|(dn, _)| dn == n) {
out.push(Violation {
principle: 2,
node: fh.clone(),
detail: format!(
"`{type_name}.{case}` has no field `{n}`"
),
});
self.walk_expr(fh, scope, sigs, out, effects, failures)?;
}
}
if payload.is_empty() {
conf = Confidence::Structural;
}
Some((Type::Named(type_name.clone()), conf))
}
},
},
Node::Match {
scrutinee,
type_name,
arms,
} => {
match self.walk_expr(&scrutinee, scope, sigs, out, effects, failures)? {
Some((Type::Named(vname), sconf)) => {
if vname != type_name {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"match typed as `{type_name}` but scrutinee is `{vname}`"
),
});
}
match self.variants.get(&vname).cloned() {
None => {
out.push(Violation {
principle: 1,
node: hash.clone(),
detail: format!("unknown variant type: `{vname}`"),
});
None
}
Some(cases) => {
for (cname, _) in &cases {
if !arms.iter().any(|a| &a.case == cname) {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"non-exhaustive match: case `{cname}` not covered"
),
});
}
}
let mut result_ty: Option<Type> = None;
let mut conf = sconf;
for arm in &arms {
let Some((_, payload)) =
cases.iter().find(|(c, _)| c == &arm.case)
else {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"`{vname}` has no case `{}`",
arm.case
),
});
continue;
};
if arm.bindings.len() != payload.len() {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"case `{}` has {} field(s), {} bound",
arm.case,
payload.len(),
arm.bindings.len()
),
});
}
let mut s2 = scope.to_vec();
for (i, b) in arm.bindings.iter().enumerate() {
let entry = payload
.get(i)
.map(|(_, ft)| (ft.clone(), sconf));
s2.push((b.clone(), entry));
}
if let Some((bt, bc)) = self.walk_expr(
&arm.body, &s2, sigs, out, effects, failures,
)? {
match &result_ty {
None => result_ty = Some(bt),
Some(rt) => {
if !compatible(rt, &bt) {
out.push(Violation {
principle: 2,
node: hash.clone(),
detail: format!(
"match arms differ: {rt:?} vs {bt:?}"
),
});
}
}
}
conf = conf.min(bc);
}
}
result_ty.map(|t| (t, conf))
}
}
}
Some((other, _)) => {
out.push(Violation {
principle: 2,
node: scrutinee.clone(),
detail: format!("match on non-variant type {other:?}"),
});
None
}
None => None,
}
}
Node::Function { .. }
| Node::Module { .. }
| Node::RecordDef { .. }
| Node::VariantDef { .. } => None,
})
}
}
/// Two types are compatible if equal, or if either is `Never` — an
/// expression that diverges can stand wherever a value is expected.
fn compatible(a: &Type, b: &Type) -> bool {
a == b || *a == Type::Never || *b == Type::Never
}
/// Unify a (possibly type-variable-bearing) parameter type against an actual
/// type, recording type-variable bindings. Monomorphic types unify only by
/// structural equality; `Never` unifies with anything.
fn unify(pat: &Type, actual: &Type, subst: &mut HashMap<String, Type>) -> bool {
if *actual == Type::Never {
return true;
}
match pat {
Type::Var(v) => match subst.get(v) {
Some(bound) => compatible(&bound.clone(), actual),
None => {
subst.insert(v.clone(), actual.clone());
true
}
},
Type::List(a) => {
if let Type::List(b) = actual {
unify(a, b, subst)
} else {
false
}
}
Type::Option(a) => {
if let Type::Option(b) = actual {
unify(a, b, subst)
} else {
false
}
}
Type::Cell(a) => {
if let Type::Cell(b) = actual {
unify(a, b, subst)
} else {
false
}
}
Type::Map(ka, va) => {
if let Type::Map(kb, vb) = actual {
unify(ka, kb, subst) && unify(va, vb, subst)
} else {
false
}
}
Type::Result(oa, ea) => {
if let Type::Result(ob, eb) = actual {
unify(oa, ob, subst) && unify(ea, eb, subst)
} else {
false
}
}
Type::Fn {
params: pa,
ret: ra,
..
} => {
if let Type::Fn {
params: pb,
ret: rb,
..
} = actual
{
pa.len() == pb.len()
&& pa.iter().zip(pb).all(|(x, y)| unify(x, y, subst))
&& unify(ra, rb, subst)
} else {
false
}
}
_ => pat == actual,
}
}
/// Apply a type-variable substitution.
fn substitute(t: &Type, subst: &HashMap<String, Type>) -> Type {
match t {
Type::Var(v) => subst.get(v).cloned().unwrap_or_else(|| t.clone()),
Type::List(a) => Type::List(Box::new(substitute(a, subst))),
Type::Option(a) => Type::Option(Box::new(substitute(a, subst))),
Type::Cell(a) => Type::Cell(Box::new(substitute(a, subst))),
Type::Map(k, v) => Type::Map(
Box::new(substitute(k, subst)),
Box::new(substitute(v, subst)),
),
Type::Result(o, e) => Type::Result(
Box::new(substitute(o, subst)),
Box::new(substitute(e, subst)),
),
Type::Fn {
params,
ret,
effects,
} => Type::Fn {
params: params.iter().map(|p| substitute(p, subst)).collect(),
ret: Box::new(substitute(ret, subst)),
effects: effects.clone(),
},
_ => t.clone(),
}
}
/// Whether type `t` mentions the named type variable.
fn ty_mentions(t: &Type, name: &str) -> bool {
match t {
Type::Var(v) => v == name,
Type::List(a) | Type::Option(a) | Type::Cell(a) => ty_mentions(a, name),
Type::Map(k, v) | Type::Result(k, v) => {
ty_mentions(k, name) || ty_mentions(v, name)
}
Type::Fn { params, ret, .. } => {
params.iter().any(|p| ty_mentions(p, name)) || ty_mentions(ret, name)
}
_ => false,
}
}
/// The child hashes a node references, in order.
pub(crate) fn child_hashes(node: &Node) -> Vec<&NodeHash> {
match node {
Node::Lit(_)
| Node::FloatLit(_)
| Node::DecimalLit(_)
| Node::Bool(_)
| Node::Str(_)
| Node::Now
| Node::Rand
| Node::Ref(_)
| Node::FuncRef(_)
| Node::Hole { .. }
| Node::Fail(_)
| Node::RecordDef { .. }
| Node::VariantDef { .. } => Vec::new(),
Node::StrLen(arg)
| Node::StrLower(arg)
| Node::StrFromCode(arg)
| Node::IntToFloat(arg)
| Node::FloatToInt(arg)
| Node::IntToDecimal(arg)
| Node::DecimalToInt(arg)
| Node::DecimalRaw(arg)
| Node::Not(arg)
| Node::NumberToStr(arg)
| Node::StrToNumber(arg)
| Node::StrToNumberOpt(arg) => vec![arg],
Node::StrConcat(a, b) | Node::StrEq(a, b) => vec![a, b],
Node::StrSlice { s, start, len } => vec![s, start, len],
Node::StrContains { haystack, needle } => vec![haystack, needle],
Node::StrStartsWith { s, prefix } => vec![s, prefix],
Node::StrIndexOf { haystack, needle } => vec![haystack, needle],
Node::List(elems) => elems.iter().collect(),
Node::ListEmpty { .. } => Vec::new(),
Node::ListCons { head, tail } => vec![head, tail],
Node::OptionSome(v) => vec![v],
Node::OptionNone { .. } => Vec::new(),
Node::OptionElse { opt, default } => vec![opt, default],
Node::OptionMatch {
opt,
some_body,
none_body,
..
} => vec![opt, some_body, none_body],
Node::ListTryGet { list, index } => vec![list, index],
Node::ListLen(arg) => vec![arg],
Node::ListGet { list, index } => vec![list, index],
Node::Map(pairs) => {
let mut v = Vec::with_capacity(pairs.len() * 2);
for (k, val) in pairs {
v.push(k);
v.push(val);
}
v
}
Node::MapGet { map, key } => vec![map, key],
Node::MapTryGet { map, key } => vec![map, key],
Node::MapLen(arg) => vec![arg],
Node::Log(arg) | Node::Publish(arg) => vec![arg],
Node::SetHeader { name, value } => vec![name, value],
Node::MutNew(v) => vec![v],
Node::MutGet(cell) => vec![cell],
Node::MutSet { cell, value } => vec![cell, value],
Node::DiskWrite { path, content } => vec![path, content],
Node::DiskRead(path) => vec![path],
Node::NetGet(url) => vec![url],
Node::DbQuery { sql, params } => vec![sql, params],
Node::Record { fields, .. } => fields.iter().map(|(_, h)| h).collect(),
Node::Variant { fields, .. } => fields.iter().map(|(_, h)| h).collect(),
Node::Field { base, .. } => vec![base],
Node::Match {
scrutinee, arms, ..
} => {
let mut v = vec![scrutinee];
v.extend(arms.iter().map(|a| &a.body));
v
}
Node::Handle { body, handlers } => {
let mut v = vec![body];
v.extend(handlers.iter().map(|(_, h)| h));
v
}
Node::Call { args, .. } => args.iter().collect(),
Node::CallValue { callee, args } => {
let mut v = vec![callee];
v.extend(args.iter());
v
}
Node::Lambda { body, .. } => vec![body],
Node::Step { value, .. } => vec![value],
Node::BinOp { lhs, rhs, .. }
| Node::FloatOp { lhs, rhs, .. }
| Node::DecimalOp { lhs, rhs, .. } => vec![lhs, rhs],
Node::If {
cond,
then_branch,
else_branch,
} => vec![cond, then_branch, else_branch],
Node::Function { body, result, .. } => {
let mut v: Vec<&NodeHash> = body.iter().collect();
v.push(result);
v
}
Node::Module {
types, functions, ..
} => {
let mut v: Vec<&NodeHash> = types.iter().collect();
v.extend(functions.iter());
v
}
}
}
/// The structural inverse of [`child_hashes`]: rebuild `node` with its
/// child hashes replaced by `kids`, in the **exact order**
/// `child_hashes` yields them, preserving every non-hash field (ops,
/// names, types, case labels, bindings). `kids.len()` must equal
/// `child_hashes(node).len()` — this is the substitution primitive
/// `replace_node`/`fill_hole` build on; the invariant
/// `child_hashes(&with_child_hashes(n, child_hashes(n))) == child_hashes(n)`
/// is asserted by `with_child_hashes_round_trips`.
pub(crate) fn with_child_hashes(node: &Node, kids: &[NodeHash]) -> Node {
let k = |i: usize| kids[i].clone();
match node {
// Leaves — no children; identity.
Node::Lit(_)
| Node::FloatLit(_)
| Node::DecimalLit(_)
| Node::Bool(_)
| Node::Str(_)
| Node::Now
| Node::Rand
| Node::Ref(_)
| Node::FuncRef(_)
| Node::Hole { .. }
| Node::Fail(_)
| Node::RecordDef { .. }
| Node::VariantDef { .. }
| Node::ListEmpty { .. }
| Node::OptionNone { .. } => node.clone(),
Node::StrLen(_) => Node::StrLen(k(0)),
Node::StrLower(_) => Node::StrLower(k(0)),
Node::StrFromCode(_) => Node::StrFromCode(k(0)),
Node::IntToFloat(_) => Node::IntToFloat(k(0)),
Node::FloatToInt(_) => Node::FloatToInt(k(0)),
Node::IntToDecimal(_) => Node::IntToDecimal(k(0)),
Node::DecimalToInt(_) => Node::DecimalToInt(k(0)),
Node::DecimalRaw(_) => Node::DecimalRaw(k(0)),
Node::Not(_) => Node::Not(k(0)),
Node::NumberToStr(_) => Node::NumberToStr(k(0)),
Node::StrToNumber(_) => Node::StrToNumber(k(0)),
Node::StrToNumberOpt(_) => Node::StrToNumberOpt(k(0)),
Node::ListLen(_) => Node::ListLen(k(0)),
Node::MapLen(_) => Node::MapLen(k(0)),
Node::OptionSome(_) => Node::OptionSome(k(0)),
Node::Log(_) => Node::Log(k(0)),
Node::Publish(_) => Node::Publish(k(0)),
Node::SetHeader { .. } => Node::SetHeader {
name: k(0),
value: k(1),
},
Node::MutNew(_) => Node::MutNew(k(0)),
Node::MutGet(_) => Node::MutGet(k(0)),
Node::DiskRead(_) => Node::DiskRead(k(0)),
Node::NetGet(_) => Node::NetGet(k(0)),
Node::StrConcat(_, _) => Node::StrConcat(k(0), k(1)),
Node::StrEq(_, _) => Node::StrEq(k(0), k(1)),
Node::StrContains { .. } => Node::StrContains {
haystack: k(0),
needle: k(1),
},
Node::StrStartsWith { .. } => Node::StrStartsWith {
s: k(0),
prefix: k(1),
},
Node::StrIndexOf { .. } => Node::StrIndexOf {
haystack: k(0),
needle: k(1),
},
Node::StrSlice { .. } => Node::StrSlice {
s: k(0),
start: k(1),
len: k(2),
},
Node::ListCons { .. } => Node::ListCons {
head: k(0),
tail: k(1),
},
Node::OptionElse { .. } => Node::OptionElse {
opt: k(0),
default: k(1),
},
Node::OptionMatch {
some_bind,
..
} => Node::OptionMatch {
opt: k(0),
some_bind: some_bind.clone(),
some_body: k(1),
none_body: k(2),
},
Node::ListTryGet { .. } => Node::ListTryGet {
list: k(0),
index: k(1),
},
Node::ListGet { .. } => Node::ListGet {
list: k(0),
index: k(1),
},
Node::MapGet { .. } => Node::MapGet {
map: k(0),
key: k(1),
},
Node::MapTryGet { .. } => Node::MapTryGet {
map: k(0),
key: k(1),
},
Node::MutSet { .. } => Node::MutSet {
cell: k(0),
value: k(1),
},
Node::DiskWrite { .. } => Node::DiskWrite {
path: k(0),
content: k(1),
},
Node::DbQuery { .. } => Node::DbQuery {
sql: k(0),
params: k(1),
},
Node::BinOp { op, .. } => Node::BinOp {
op: *op,
lhs: k(0),
rhs: k(1),
},
Node::FloatOp { op, .. } => Node::FloatOp {
op: *op,
lhs: k(0),
rhs: k(1),
},
Node::DecimalOp { op, .. } => Node::DecimalOp {
op: *op,
lhs: k(0),
rhs: k(1),
},
Node::If { .. } => Node::If {
cond: k(0),
then_branch: k(1),
else_branch: k(2),
},
Node::List(elems) => {
Node::List((0..elems.len()).map(k).collect())
}
Node::Map(pairs) => Node::Map(
(0..pairs.len()).map(|i| (k(2 * i), k(2 * i + 1))).collect(),
),
Node::Record {
type_name, fields, ..
} => Node::Record {
type_name: type_name.clone(),
fields: fields
.iter()
.enumerate()
.map(|(i, (n, _))| (n.clone(), k(i)))
.collect(),
},
Node::Variant {
type_name,
case,
fields,
} => Node::Variant {
type_name: type_name.clone(),
case: case.clone(),
fields: fields
.iter()
.enumerate()
.map(|(i, (n, _))| (n.clone(), k(i)))
.collect(),
},
Node::Field {
type_name, field, ..
} => Node::Field {
base: k(0),
type_name: type_name.clone(),
field: field.clone(),
},
Node::Match {
type_name, arms, ..
} => Node::Match {
scrutinee: k(0),
type_name: type_name.clone(),
arms: arms
.iter()
.enumerate()
.map(|(i, a)| MatchArm {
body: k(i + 1),
..a.clone()
})
.collect(),
},
Node::Handle { handlers, .. } => Node::Handle {
body: k(0),
handlers: handlers
.iter()
.enumerate()
.map(|(i, (n, _))| (n.clone(), k(i + 1)))
.collect(),
},
Node::Call { func, args } => Node::Call {
func: func.clone(),
args: (0..args.len()).map(k).collect(),
},
Node::CallValue { args, .. } => Node::CallValue {
callee: k(0),
args: (0..args.len()).map(|i| k(i + 1)).collect(),
},
Node::Lambda { params, .. } => Node::Lambda {
params: params.clone(),
body: k(0),
},
Node::Step { binding, .. } => Node::Step {
binding: binding.clone(),
value: k(0),
},
Node::Function {
name,
type_params,
params,
produces,
requires,
on_failure,
body,
..
} => Node::Function {
name: name.clone(),
type_params: type_params.clone(),
params: params.clone(),
produces: produces.clone(),
requires: requires.clone(),
on_failure: on_failure.clone(),
body: (0..body.len()).map(k).collect(),
result: k(body.len()),
},
Node::Module {
name,
types,
functions,
} => Node::Module {
name: name.clone(),
types: (0..types.len()).map(k).collect(),
functions: (0..functions.len())
.map(|i| k(types.len() + i))
.collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::node::{BinOp, MatchArm, Param};
fn p(name: &str, ty: Type, c: Confidence) -> Param {
Param {
name: name.into(),
ty,
min_confidence: c,
}
}
fn produces(ty: Type, confidence: Confidence) -> Produces {
Produces { ty, confidence }
}
#[allow(clippy::too_many_arguments)]
fn function(
store: &Store,
name: &str,
params: Vec<Param>,
prod: Produces,
requires: BTreeSet<Effect>,
on_failure: Vec<&str>,
body: Vec<NodeHash>,
result: NodeHash,
) -> NodeHash {
store
.put(&Node::Function {
name: name.into(),
type_params: vec![],
params,
produces: prod,
requires,
on_failure: on_failure.into_iter().map(String::from).collect(),
body,
result,
})
.unwrap()
}
/// `add(a: Number@External, b: Number@External) -> Number@Structural`,
/// pure, no failures — a callee used by other tests. Its result is a
/// structural literal, so it honors its own `produces`.
fn add_fn(s: &Store) -> NodeHash {
let sum = s.put(&Node::Lit(0)).unwrap();
function(
s,
"add",
vec![
p("a", Type::Number, Confidence::External),
p("b", Type::Number, Confidence::External),
],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
sum,
)
}
#[test]
fn a_well_typed_module_is_clean_and_complete() {
let s = Store::open_in_memory().unwrap();
let add = add_fn(&s);
let n = s.put(&Node::Ref("n".into())).unwrap();
let call = s
.put(&Node::Call {
func: "add".into(),
args: vec![n.clone(), n],
})
.unwrap();
let step = s
.put(&Node::Step {
binding: "d".into(),
value: call,
})
.unwrap();
let res = s.put(&Node::Ref("d".into())).unwrap();
let double = function(
&s,
"double",
vec![p("n", Type::Number, Confidence::External)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![step],
res,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![add, double],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
assert_eq!(r.status, Status::Complete);
assert_eq!(r.failures, Failures::Exhaustive);
}
#[test]
fn the_boolean_layer_type_checks() {
let s = Store::open_in_memory().unwrap();
// `!(true) || (1 < 2)` : Bool — the literal, the unary, and a
// logical operator over a comparison.
let t = s.put(&Node::Bool(true)).unwrap();
let nott = s.put(&Node::Not(t.clone())).unwrap();
let one = s.put(&Node::Lit(1)).unwrap();
let two = s.put(&Node::Lit(2)).unwrap();
let lt = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: one.clone(),
rhs: two,
})
.unwrap();
let or = s
.put(&Node::BinOp {
op: BinOp::Or,
lhs: nott,
rhs: lt,
})
.unwrap();
let ok = function(
&s,
"ok",
vec![],
produces(Type::Bool, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
or,
);
let r = Checker::new(&s).check(&ok).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
// `!5` — a Number operand to `!` is a Principle 2 violation.
let five = s.put(&Node::Lit(5)).unwrap();
let badnot = s.put(&Node::Not(five)).unwrap();
let bf = function(
&s,
"bf",
vec![],
produces(Type::Bool, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
badnot,
);
let r2 = Checker::new(&s).check(&bf).unwrap();
assert!(!r2.ok());
assert!(r2
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("expected Bool")));
// `1 && true` — a Number operand to `&&` is a Principle 2 violation.
let andbad = s
.put(&Node::BinOp {
op: BinOp::And,
lhs: one,
rhs: t,
})
.unwrap();
let ab = function(
&s,
"ab",
vec![],
produces(Type::Bool, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
andbad,
);
let r3 = Checker::new(&s).check(&ab).unwrap();
assert!(!r3.ok());
assert!(r3
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("logical operand")));
}
#[test]
fn function_values_type_check() {
let s = Store::open_in_memory().unwrap();
let fn_num_num = Type::Fn {
params: vec![Type::Number],
ret: Box::new(Type::Number),
effects: BTreeSet::new(),
};
// double(n) -> Number ; apply(f: Fn(Number)->Number, x) -> Number
// is `f(x)` ; main = apply(&double, 21).
let dbl = function(
&s,
"double",
vec![p("n", Type::Number, Confidence::Structural)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Ref("n".into())).unwrap(),
);
let call_f = s
.put(&Node::CallValue {
callee: s.put(&Node::Ref("f".into())).unwrap(),
args: vec![s.put(&Node::Ref("x".into())).unwrap()],
})
.unwrap();
let apply = function(
&s,
"apply",
vec![
p("f", fn_num_num.clone(), Confidence::Structural),
p("x", Type::Number, Confidence::Structural),
],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
call_f,
);
let main = function(
&s,
"main",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "apply".into(),
args: vec![
s.put(&Node::FuncRef("double".into())).unwrap(),
s.put(&Node::Lit(21)).unwrap(),
],
})
.unwrap(),
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![dbl, apply, main],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
// `&identity` — a function value of a generic function is rejected.
let id = identity_fn(&s);
let badgen = function(
&s,
"bg",
vec![],
produces(fn_num_num.clone(), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FuncRef("identity".into())).unwrap(),
);
let mg = s
.put(&Node::Module {
name: "mg".into(),
types: vec![],
functions: vec![id, badgen],
})
.unwrap();
let rg = Checker::new(&s).check(&mg).unwrap();
assert!(rg
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("generic")));
// `&boom` — a function value of a fallible function is rejected.
let boom = function(
&s,
"boom",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec!["Boom"],
vec![],
s.put(&Node::Fail("Boom".into())).unwrap(),
);
let badfal = function(
&s,
"bf2",
vec![],
produces(fn_num_num, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FuncRef("boom".into())).unwrap(),
);
let mf = s
.put(&Node::Module {
name: "mf".into(),
types: vec![],
functions: vec![boom, badfal],
})
.unwrap();
let rf = Checker::new(&s).check(&mf).unwrap();
assert!(rf
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("fallible")));
// Calling a non-function value is a Principle 2 violation.
let badcall = function(
&s,
"bc",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::CallValue {
callee: s.put(&Node::Lit(5)).unwrap(),
args: vec![],
})
.unwrap(),
);
let rc = Checker::new(&s).check(&badcall).unwrap();
assert!(rc
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("not a function value")));
}
#[test]
fn closures_type_check_and_isolate_effects() {
let s = Store::open_in_memory().unwrap();
let lam_param = |name: &str| Param {
name: name.into(),
ty: Type::Number,
min_confidence: Confidence::External,
};
// mk(k) -> Fn(Number)->Number is `|x| x + k` (captures k).
let body = s
.put(&Node::BinOp {
op: BinOp::Add,
lhs: s.put(&Node::Ref("x".into())).unwrap(),
rhs: s.put(&Node::Ref("k".into())).unwrap(),
})
.unwrap();
let lam = s
.put(&Node::Lambda {
params: vec![lam_param("x")],
body,
})
.unwrap();
let fn_num_num = Type::Fn {
params: vec![Type::Number],
ret: Box::new(Type::Number),
effects: BTreeSet::new(),
};
let mk = function(
&s,
"mk",
vec![p("k", Type::Number, Confidence::Structural)],
produces(fn_num_num.clone(), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
lam,
);
let r = Checker::new(&s)
.check(
&s.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![mk],
})
.unwrap(),
)
.unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
// Effect isolation: `mklog = |x| log(x)` returns a closure whose
// Fn type carries Log. *Creating* it performs nothing — mklog
// needs no `requires` — but the returned type honestly declares
// the effect. A function that *calls* it must declare Log (P5).
let fn_log = Type::Fn {
params: vec![Type::Number],
ret: Box::new(Type::Number),
effects: [Effect::Log].into_iter().collect(),
};
let log_body = s
.put(&Node::Log(s.put(&Node::Ref("x".into())).unwrap()))
.unwrap();
let log_lam = s
.put(&Node::Lambda {
params: vec![lam_param("x")],
body: log_body,
})
.unwrap();
let mklog = function(
&s,
"mklog",
vec![],
produces(fn_log.clone(), Confidence::Structural),
BTreeSet::new(), // no requires — creating a closure is pure
vec![],
vec![],
log_lam,
);
let r2 = Checker::new(&s)
.check(
&s.put(&Node::Module {
name: "m2".into(),
types: vec![],
functions: vec![mklog],
})
.unwrap(),
)
.unwrap();
assert!(
r2.ok(),
"creating an effectful closure must be pure: {:?}",
r2.violations
);
// Calling a Log-effecting function value without declaring Log
// is a Principle 5 violation.
let call_f = s
.put(&Node::CallValue {
callee: s.put(&Node::Ref("f".into())).unwrap(),
args: vec![s.put(&Node::Lit(0)).unwrap()],
})
.unwrap();
let runner = function(
&s,
"runner",
vec![p("f", fn_log, Confidence::Structural)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(), // missing Log
vec![],
vec![],
call_f,
);
let r3 = Checker::new(&s)
.check(
&s.put(&Node::Module {
name: "m3".into(),
types: vec![],
functions: vec![runner],
})
.unwrap(),
)
.unwrap();
assert!(r3
.violations
.iter()
.any(|v| v.principle == 5 && v.detail.contains("Log")));
// A lambda may not raise an uncaught failure (v0.4 boundary).
let fail_lam = s
.put(&Node::Lambda {
params: vec![lam_param("x")],
body: s.put(&Node::Fail("Boom".into())).unwrap(),
})
.unwrap();
let mkfail = function(
&s,
"mkfail",
vec![],
produces(fn_num_num, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
fail_lam,
);
let r4 = Checker::new(&s)
.check(
&s.put(&Node::Module {
name: "m4".into(),
types: vec![],
functions: vec![mkfail],
})
.unwrap(),
)
.unwrap();
assert!(r4
.violations
.iter()
.any(|v| v.principle == 6 && v.detail.contains("uncaught failure")));
}
#[test]
fn option_match_type_checks() {
let s = Store::open_in_memory().unwrap();
// f(o: Option<Number>) -> Number = match o { Some(v) -> v+1, None -> 0 }
let good = s
.put(&Node::OptionMatch {
opt: s.put(&Node::Ref("o".into())).unwrap(),
some_bind: "v".into(),
some_body: s
.put(&Node::BinOp {
op: BinOp::Add,
lhs: s.put(&Node::Ref("v".into())).unwrap(),
rhs: s.put(&Node::Lit(1)).unwrap(),
})
.unwrap(),
none_body: s.put(&Node::Lit(0)).unwrap(),
})
.unwrap();
let f = function(
&s,
"f",
vec![p(
"o",
Type::Option(Box::new(Type::Number)),
Confidence::Structural,
)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
good,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
// Scrutinee not an Option -> Principle 2.
let bad_scrut = s
.put(&Node::OptionMatch {
opt: s.put(&Node::Lit(5)).unwrap(),
some_bind: "v".into(),
some_body: s.put(&Node::Ref("v".into())).unwrap(),
none_body: s.put(&Node::Lit(0)).unwrap(),
})
.unwrap();
let bf = function(
&s,
"bf",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
bad_scrut,
);
let r2 = Checker::new(&s).check(&bf).unwrap();
assert!(r2
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("expected Option")));
// Arms of different types -> Principle 2.
let bad_arms = s
.put(&Node::OptionMatch {
opt: s.put(&Node::Ref("o".into())).unwrap(),
some_bind: "v".into(),
some_body: s.put(&Node::Str("x".into())).unwrap(),
none_body: s.put(&Node::Lit(0)).unwrap(),
})
.unwrap();
let ba = function(
&s,
"ba",
vec![p(
"o",
Type::Option(Box::new(Type::Number)),
Confidence::Structural,
)],
produces(Type::String, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
bad_arms,
);
let r3 = Checker::new(&s).check(&ba).unwrap();
assert!(r3
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("arms differ")));
}
#[test]
fn float_type_checks() {
let s = Store::open_in_memory().unwrap();
let f = |v: f64| s.put(&Node::FloatLit(v.to_bits())).unwrap();
// f() -> Float = 1.5 * 2.0
let good = function(
&s,
"g",
vec![],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FloatOp {
op: BinOp::Mul,
lhs: f(1.5),
rhs: f(2.0),
})
.unwrap(),
);
let r = Checker::new(&s).check(&good).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
// Float op with a Number operand -> Principle 2.
let mixed = function(
&s,
"mx",
vec![],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FloatOp {
op: BinOp::Add,
lhs: f(1.0),
rhs: s.put(&Node::Lit(2)).unwrap(),
})
.unwrap(),
);
let r2 = Checker::new(&s).check(&mixed).unwrap();
assert!(r2
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("expected Float")));
// `%` is not defined on Float -> Principle 2.
let modf = function(
&s,
"mf",
vec![],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FloatOp {
op: BinOp::Mod,
lhs: f(5.0),
rhs: f(2.0),
})
.unwrap(),
);
let r3 = Checker::new(&s).check(&modf).unwrap();
assert!(r3
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("not defined on Float")));
}
#[test]
fn decimal_type_checks() {
let s = Store::open_in_memory().unwrap();
let d = |v: i64| s.put(&Node::DecimalLit(v)).unwrap();
let good = function(
&s,
"g",
vec![],
produces(Type::Decimal, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::DecimalOp {
op: BinOp::Mul,
lhs: d(12500),
rhs: d(40000),
})
.unwrap(),
);
assert!(Checker::new(&s).check(&good).unwrap().ok());
// Number operand to a Decimal op -> Principle 2.
let mixed = function(
&s,
"mx",
vec![],
produces(Type::Decimal, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::DecimalOp {
op: BinOp::Add,
lhs: d(10000),
rhs: s.put(&Node::Lit(2)).unwrap(),
})
.unwrap(),
);
let r2 = Checker::new(&s).check(&mixed).unwrap();
assert!(r2
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("expected Decimal")));
// `%` is not defined on Decimal -> Principle 2.
let modd = function(
&s,
"md",
vec![],
produces(Type::Decimal, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::DecimalOp {
op: BinOp::Mod,
lhs: d(50000),
rhs: d(20000),
})
.unwrap(),
);
let r3 = Checker::new(&s).check(&modd).unwrap();
assert!(r3
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("not defined on Decimal")));
}
#[test]
fn publish_requires_the_live_effect() {
let s = Store::open_in_memory().unwrap();
let body = || s.put(&Node::Publish(
s.put(&Node::Str("items".into())).unwrap(),
)).unwrap();
// requires Live → clean.
let ok = function(
&s,
"notify",
vec![],
produces(Type::Number, Confidence::Structural),
[Effect::Live].into_iter().collect(),
vec![],
vec![],
body(),
);
assert!(Checker::new(&s).check(&ok).unwrap().ok());
// missing requires Live → Principle 5.
let bad = function(
&s,
"notify2",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
body(),
);
let r = Checker::new(&s).check(&bad).unwrap();
assert!(
r.violations
.iter()
.any(|v| v.principle == 5 && v.detail.contains("Live")),
"publish without `requires Live` must be P5: {:?}",
r.violations
);
}
#[test]
fn numeric_and_closure_soundness() {
// Adversarial: every program here MUST be rejected. Number,
// Decimal, and Float-bits are all i64 at runtime, so a missed
// rejection is silent corruption, not a trap — the worst failure
// for a trust-the-checker language. A failing assertion here is a
// real soundness hole, not a test bug.
let s = Store::open_in_memory().unwrap();
let flt = |v: f64| s.put(&Node::FloatLit(v.to_bits())).unwrap();
let dec = |v: i64| s.put(&Node::DecimalLit(v)).unwrap();
let lit = |v: i64| s.put(&Node::Lit(v)).unwrap();
let rf = |n: &str| s.put(&Node::Ref(n.into())).unwrap();
let rejects = |f: &NodeHash, why: &str| {
let r = Checker::new(&s).check(f).unwrap();
assert!(
!r.ok() && r.violations.iter().any(|v| v.principle == 2),
"UNSOUND: checker accepted `{why}` — {:?}",
r.violations
);
};
let module = |fns: Vec<NodeHash>| {
s.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: fns,
})
.unwrap()
};
let pnum = |n: &str| p(n, Type::Number, Confidence::Structural);
// 1. Float returned where Number is declared.
rejects(
&function(
&s,
"r1",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
flt(1.0),
),
"Float as Number result",
);
// 2. Number arithmetic with a Float operand.
rejects(
&function(
&s,
"r2",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::BinOp {
op: BinOp::Add,
lhs: lit(1),
rhs: flt(2.0),
})
.unwrap(),
),
"Number + Float",
);
// 3. Float op with a Decimal operand (both i64 — the silent one).
rejects(
&function(
&s,
"r3",
vec![],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::FloatOp {
op: BinOp::Add,
lhs: flt(1.0),
rhs: dec(20000),
})
.unwrap(),
),
"Float + Decimal",
);
// 4. Float passed to a Number parameter across a call.
let idn = function(
&s,
"idn",
vec![pnum("n")],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rf("n"),
);
let c4 = function(
&s,
"c4",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "idn".into(),
args: vec![flt(3.0)],
})
.unwrap(),
);
rejects(&module(vec![idn, c4]), "Float arg to Number param");
// 5. CallValue arity mismatch (closure of 1 param, 2 args).
rejects(
&function(
&s,
"r5",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::CallValue {
callee: s
.put(&Node::Lambda {
params: vec![pnum("x")],
body: rf("x"),
})
.unwrap(),
args: vec![lit(1), lit(2)],
})
.unwrap(),
),
"closure arity mismatch",
);
// 6. CallValue arg-type mismatch (Float into Fn(Number)).
rejects(
&function(
&s,
"r6",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::CallValue {
callee: s
.put(&Node::Lambda {
params: vec![pnum("x")],
body: rf("x"),
})
.unwrap(),
args: vec![flt(1.0)],
})
.unwrap(),
),
"Float into Fn(Number)",
);
// 7. Lambda return type vs. expected Fn return (unify Fn ret).
let apply = function(
&s,
"apply",
vec![p(
"f",
Type::Fn {
params: vec![Type::Number],
ret: Box::new(Type::Number),
effects: BTreeSet::new(),
},
Confidence::Structural,
)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::CallValue {
callee: rf("f"),
args: vec![lit(1)],
})
.unwrap(),
);
let c7 = function(
&s,
"c7",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "apply".into(),
args: vec![s
.put(&Node::Lambda {
params: vec![pnum("x")],
body: s.put(&Node::Str("nope".into())).unwrap(),
})
.unwrap()],
})
.unwrap(),
);
rejects(
&module(vec![apply, c7]),
"Fn(Number)->String where Fn(Number)->Number expected",
);
// 8. Type parameter that occurs only in the result (uninferable).
let phantom = s
.put(&Node::Function {
name: "phantom".into(),
type_params: vec!["T".into()],
params: vec![pnum("x")],
produces: produces(
Type::Option(Box::new(Type::Var("T".into()))),
Confidence::Structural,
),
requires: BTreeSet::new(),
on_failure: vec![],
body: vec![],
result: s
.put(&Node::OptionNone {
elem: Type::Var("T".into()),
})
.unwrap(),
})
.unwrap();
let usep = function(
&s,
"usep",
vec![],
produces(
Type::Option(Box::new(Type::Number)),
Confidence::Structural,
),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "phantom".into(),
args: vec![lit(0)],
})
.unwrap(),
);
rejects(
&module(vec![phantom, usep]),
"type param only in result (uninferable)",
);
// 9. OptionMatch arms of different numeric types.
rejects(
&function(
&s,
"r9",
vec![p(
"o",
Type::Option(Box::new(Type::Number)),
Confidence::Structural,
)],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::OptionMatch {
opt: rf("o"),
some_bind: "v".into(),
some_body: flt(1.0),
none_body: lit(0),
})
.unwrap(),
),
"OptionMatch Float/Number arms",
);
// 10. IntToFloat applied to a String.
rejects(
&function(
&s,
"r10",
vec![],
produces(Type::Float, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::IntToFloat(
s.put(&Node::Str("x".into())).unwrap(),
))
.unwrap(),
),
"to_float(String)",
);
}
#[test]
fn effect_failure_confidence_soundness() {
// The other three core guarantees, adversarially. A hole here is
// a "pure" function that does I/O, an uncaught failure that
// escapes typing, or unvalidated data reaching a validated sink —
// each a direct thesis violation, and each silent.
let s = Store::open_in_memory().unwrap();
let lit = |v: i64| s.put(&Node::Lit(v)).unwrap();
let rf = |n: &str| s.put(&Node::Ref(n.into())).unwrap();
let module = |fns: Vec<NodeHash>| {
s.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: fns,
})
.unwrap()
};
let rej = |f: &NodeHash, principle: u8, why: &str| {
let r = Checker::new(&s).check(f).unwrap();
assert!(
!r.ok() && r.violations.iter().any(|v| v.principle == principle),
"UNSOUND: accepted `{why}` (expected P{principle}) — {:?}",
r.violations
);
};
let truth = || {
s.put(&Node::BinOp {
op: BinOp::Eq,
lhs: lit(0),
rhs: lit(0),
})
.unwrap()
};
// P5 — a Log effect, undeclared.
rej(
&function(
&s,
"e1",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Log(lit(1))).unwrap(),
),
5,
"Log with requires {}",
);
// P5 — effect performed inside an If branch must still surface.
rej(
&function(
&s,
"e2",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::If {
cond: truth(),
then_branch: s.put(&Node::Log(lit(1))).unwrap(),
else_branch: lit(0),
})
.unwrap(),
),
5,
"Log inside an If branch with requires {}",
);
// P5 — effect propagates across a call (callee Time, caller {}).
let timed = function(
&s,
"timed",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::from([Effect::Time]),
vec![],
vec![],
s.put(&Node::Now).unwrap(),
);
let caller5 = function(
&s,
"caller5",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "timed".into(),
args: vec![],
})
.unwrap(),
);
rej(
&module(vec![timed, caller5]),
5,
"calling a Time fn without declaring Time",
);
// P6 — Fail inside an If branch, uncovered.
rej(
&function(
&s,
"f1",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::If {
cond: truth(),
then_branch: s.put(&Node::Fail("Boom".into())).unwrap(),
else_branch: lit(0),
})
.unwrap(),
),
6,
"Fail in a branch, on_failure []",
);
// P6 — a partial Handle leaves a different failure uncaught.
rej(
&function(
&s,
"f2",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Handle {
body: s.put(&Node::Fail("Y".into())).unwrap(),
handlers: vec![("X".into(), lit(0))],
})
.unwrap(),
),
6,
"Handle X but body fails Y",
);
// P6 — failure propagates across a call.
let raiser = function(
&s,
"raiser",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec!["Boom"],
vec![],
s.put(&Node::Fail("Boom".into())).unwrap(),
);
let caller6 = function(
&s,
"caller6",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "raiser".into(),
args: vec![],
})
.unwrap(),
);
rej(
&module(vec![raiser, caller6]),
6,
"calling a fallible fn without covering its failure",
);
// P7 — External value into a Validated-min parameter.
let sink = function(
&s,
"sink",
vec![p("x", Type::Number, Confidence::Validated)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rf("x"),
);
let weak = function(
&s,
"weak",
vec![p("e", Type::Number, Confidence::External)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "sink".into(),
args: vec![rf("e")],
})
.unwrap(),
);
rej(
&module(vec![sink, weak]),
7,
"External arg into a Validated param",
);
// P7 — weakest-input propagation: External + 1 is still External.
let sink2 = function(
&s,
"sink2",
vec![p("x", Type::Number, Confidence::Validated)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rf("x"),
);
let derived = function(
&s,
"derived",
vec![p("e", Type::Number, Confidence::External)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Call {
func: "sink2".into(),
args: vec![s
.put(&Node::BinOp {
op: BinOp::Add,
lhs: rf("e"),
rhs: lit(1),
})
.unwrap()],
})
.unwrap(),
);
rej(
&module(vec![sink2, derived]),
7,
"weakest-input: (External + 1) into Validated param",
);
}
#[test]
fn a_type_mismatch_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
// f() -> String but result is a Number literal.
let lit = s.put(&Node::Lit(1)).unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::String, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
lit.clone(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(!r.ok());
let v = &r.violations[0];
assert_eq!(v.principle, 2);
assert_eq!(v.node, lit);
assert!(v.detail.contains("String"));
}
#[test]
fn passing_weaker_confidence_than_required_is_a_principle_7_violation() {
let s = Store::open_in_memory().unwrap();
// need(x: Number@Validated) and a caller passing an External param.
let xref = s.put(&Node::Ref("x".into())).unwrap();
let need = function(
&s,
"need",
vec![p("x", Type::Number, Confidence::Validated)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
xref,
);
let raw = s.put(&Node::Ref("raw".into())).unwrap();
let call = s
.put(&Node::Call {
func: "need".into(),
args: vec![raw.clone()],
})
.unwrap();
let caller = function(
&s,
"caller",
vec![p("raw", Type::Number, Confidence::External)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
call,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![need, caller],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 7 && v.node == raw));
}
#[test]
fn an_undeclared_effect_is_a_principle_5_violation() {
let s = Store::open_in_memory().unwrap();
// writer requires Db; caller calls it but declares no effects.
let unit = s.put(&Node::Lit(0)).unwrap();
let mut db = BTreeSet::new();
db.insert(Effect::Db);
let writer = function(
&s,
"writer",
vec![],
produces(Type::Number, Confidence::Structural),
db,
vec![],
vec![],
unit,
);
let call = s
.put(&Node::Call {
func: "writer".into(),
args: vec![],
})
.unwrap();
let caller = function(
&s,
"caller",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(), // declares no effects, but calls writer (Db)
vec![],
vec![],
call,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![writer, caller],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 5));
assert!(r.effects.contains(&Effect::Db));
}
#[test]
fn an_uncovered_failure_is_a_principle_6_violation() {
let s = Store::open_in_memory().unwrap();
let unit = s.put(&Node::Lit(0)).unwrap();
let risky = function(
&s,
"risky",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec!["Boom"],
vec![],
unit.clone(),
);
let call = s
.put(&Node::Call {
func: "risky".into(),
args: vec![],
})
.unwrap();
let caller = function(
&s,
"caller",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![], // does not cover `Boom`
vec![],
call,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![risky, caller],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 6));
assert_eq!(r.failures, Failures::Uncovered(vec!["Boom".into()]));
}
#[test]
fn an_unresolved_reference_is_a_principle_1_violation() {
let s = Store::open_in_memory().unwrap();
let ghost = s.put(&Node::Ref("ghost".into())).unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
ghost.clone(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 1 && v.node == ghost));
}
#[test]
fn a_hole_makes_it_incomplete_but_not_invalid() {
let s = Store::open_in_memory().unwrap();
let hole = s
.put(&Node::Hole {
expects: "Number".into(),
})
.unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![hole.clone()],
s.put(&Node::Lit(0)).unwrap(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert_eq!(r.status, Status::Incomplete);
assert_eq!(r.holes, vec![hole]);
assert!(r.ok());
}
#[test]
fn a_missing_child_is_a_principle_4_violation() {
let s = Store::open_in_memory().unwrap();
let dangling = Node::Ref("never".into()).hash();
let step = s
.put(&Node::Step {
binding: "x".into(),
value: dangling.clone(),
})
.unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![step],
s.put(&Node::Lit(0)).unwrap(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 4 && v.node == dangling));
}
#[test]
fn a_step_binding_is_not_in_scope_for_its_own_value() {
let s = Store::open_in_memory().unwrap();
let aref = s.put(&Node::Ref("a".into())).unwrap();
let step = s
.put(&Node::Step {
binding: "a".into(),
value: aref.clone(),
})
.unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![step],
s.put(&Node::Lit(0)).unwrap(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 1 && v.node == aref));
}
#[test]
fn unchanged_subtrees_are_not_recomputed() {
let s = Store::open_in_memory().unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
s.put(&Node::Lit(1)).unwrap(),
);
let mut c = Checker::new(&s);
c.check(&f).unwrap();
let after_first = c.computed_count();
assert!(after_first > 0);
c.check(&f).unwrap();
assert_eq!(c.computed_count(), after_first);
}
/// `a + b` with `a@Validated, b@External` yields `Number@External`
/// (weakest input). Declaring `produces … @ Validated` is then a P7
/// violation — the decided weakest-input rule, now with a real site.
#[test]
fn arithmetic_confidence_is_the_weakest_input() {
let s = Store::open_in_memory().unwrap();
let a = s.put(&Node::Ref("a".into())).unwrap();
let b = s.put(&Node::Ref("b".into())).unwrap();
let sum = s
.put(&Node::BinOp {
op: BinOp::Add,
lhs: a,
rhs: b,
})
.unwrap();
let f = function(
&s,
"combine",
vec![
p("a", Type::Number, Confidence::Validated),
p("b", Type::Number, Confidence::External),
],
produces(Type::Number, Confidence::Validated),
BTreeSet::new(),
vec![],
vec![],
sum.clone(),
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(
r.violations
.iter()
.any(|v| v.principle == 7 && v.node == sum),
"expected weakest-input P7, got {:?}",
r.violations
);
assert_eq!(r.confidence, Some(Confidence::External));
}
#[test]
fn a_comparison_yields_bool() {
let s = Store::open_in_memory().unwrap();
let a = s.put(&Node::Ref("a".into())).unwrap();
let b = s.put(&Node::Ref("b".into())).unwrap();
let cmp = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: a,
rhs: b,
})
.unwrap();
let f = function(
&s,
"less",
vec![
p("a", Type::Number, Confidence::Structural),
p("b", Type::Number, Confidence::Structural),
],
produces(Type::Bool, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
cmp,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
}
#[test]
fn arithmetic_on_a_bool_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let a = s.put(&Node::Ref("a".into())).unwrap();
let b = s.put(&Node::Ref("b".into())).unwrap();
let cmp = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: a.clone(),
rhs: b,
})
.unwrap();
// (a < b) + a — Bool operand in arithmetic.
let bad = s
.put(&Node::BinOp {
op: BinOp::Add,
lhs: cmp,
rhs: a,
})
.unwrap();
let f = function(
&s,
"bad",
vec![
p("a", Type::Number, Confidence::Structural),
p("b", Type::Number, Confidence::Structural),
],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
bad,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 2));
}
#[test]
fn a_non_bool_condition_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let one = s.put(&Node::Lit(1)).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let iff = s
.put(&Node::If {
cond: one.clone(), // Number, not Bool
then_branch: one.clone(),
else_branch: zero,
})
.unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
iff,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 2 && v.node == one));
}
/// `abs(n) = if n < 0 then 0 - n else n end` — a real conditional that
/// type-checks clean.
#[test]
fn a_well_typed_conditional_is_clean() {
let s = Store::open_in_memory().unwrap();
let n = s.put(&Node::Ref("n".into())).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let cond = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: n.clone(),
rhs: zero.clone(),
})
.unwrap();
let neg = s
.put(&Node::BinOp {
op: BinOp::Sub,
lhs: zero,
rhs: n.clone(),
})
.unwrap();
let iff = s
.put(&Node::If {
cond,
then_branch: neg,
else_branch: n,
})
.unwrap();
let f = function(
&s,
"abs",
vec![p("n", Type::Number, Confidence::External)],
produces(Type::Number, Confidence::External),
BTreeSet::new(),
vec![],
vec![],
iff,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
assert_eq!(r.confidence, Some(Confidence::External));
}
#[test]
fn an_uncovered_fail_is_a_principle_6_violation() {
let s = Store::open_in_memory().unwrap();
let boom = s.put(&Node::Fail("Boom".into())).unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![], // does NOT declare Boom
vec![],
boom,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 6));
assert_eq!(r.failures, Failures::Uncovered(vec!["Boom".into()]));
}
/// `safe_div(a, b) on_failure DivByZero =
/// if b == 0 then fail DivByZero else a / b end`
/// — a real fallible function that type-checks clean. The `fail` branch
/// is `Never` and unifies with the `Number` branch; the failure is
/// covered by `on_failure`.
#[test]
fn a_fallible_function_with_a_covered_failure_is_clean() {
let s = Store::open_in_memory().unwrap();
let a = s.put(&Node::Ref("a".into())).unwrap();
let b = s.put(&Node::Ref("b".into())).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let is_zero = s
.put(&Node::BinOp {
op: BinOp::Eq,
lhs: b.clone(),
rhs: zero,
})
.unwrap();
let boom = s.put(&Node::Fail("DivByZero".into())).unwrap();
let div = s
.put(&Node::BinOp {
op: BinOp::Div,
lhs: a,
rhs: b,
})
.unwrap();
let iff = s
.put(&Node::If {
cond: is_zero,
then_branch: boom,
else_branch: div,
})
.unwrap();
let f = function(
&s,
"safe_div",
vec![
p("a", Type::Number, Confidence::Structural),
p("b", Type::Number, Confidence::Structural),
],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec!["DivByZero"],
vec![],
iff,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
assert_eq!(r.failures, Failures::Exhaustive);
}
#[test]
fn handle_catches_a_failure_so_it_need_not_propagate() {
let s = Store::open_in_memory().unwrap();
// risky() on_failure [Boom]
let unit = s.put(&Node::Lit(0)).unwrap();
let risky = function(
&s,
"risky",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec!["Boom"],
vec![],
unit,
);
// caller: step x = risky() on Boom -> 0 ; result x
let call = s
.put(&Node::Call {
func: "risky".into(),
args: vec![],
})
.unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let handle = s
.put(&Node::Handle {
body: call,
handlers: vec![("Boom".into(), zero)],
})
.unwrap();
let step = s
.put(&Node::Step {
binding: "x".into(),
value: handle,
})
.unwrap();
let xref = s.put(&Node::Ref("x".into())).unwrap();
let caller = function(
&s,
"caller",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![], // declares NO failures — Boom is handled, so this is fine
vec![step],
xref,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![risky, caller],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
assert_eq!(r.failures, Failures::Exhaustive);
}
fn point_def(s: &Store) -> NodeHash {
s.put(&Node::RecordDef {
name: "Point".into(),
fields: vec![
("x".into(), Type::Number),
("y".into(), Type::Number),
],
})
.unwrap()
}
#[test]
fn a_record_module_typechecks_clean() {
let s = Store::open_in_memory().unwrap();
let pd = point_def(&s);
// mk(a) -> Point { x: a, y: 0 }
let a = s.put(&Node::Ref("a".into())).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let rec = s
.put(&Node::Record {
type_name: "Point".into(),
fields: vec![("x".into(), a), ("y".into(), zero)],
})
.unwrap();
let mk = function(
&s,
"mk",
vec![p("a", Type::Number, Confidence::Structural)],
produces(Type::Named("Point".into()), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rec,
);
// getx(pt) -> pt.x
let pref = s.put(&Node::Ref("pt".into())).unwrap();
let fx = s
.put(&Node::Field {
base: pref,
type_name: "Point".into(),
field: "x".into(),
})
.unwrap();
let getx = function(
&s,
"getx",
vec![p(
"pt",
Type::Named("Point".into()),
Confidence::Structural,
)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
fx,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![pd],
functions: vec![mk, getx],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
}
#[test]
fn a_wrong_field_type_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let pd = point_def(&s);
// x given a Bool (a < b) instead of Number.
let a = s.put(&Node::Ref("a".into())).unwrap();
let b = s.put(&Node::Ref("b".into())).unwrap();
let cmp = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: a,
rhs: b,
})
.unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let rec = s
.put(&Node::Record {
type_name: "Point".into(),
fields: vec![("x".into(), cmp), ("y".into(), zero)],
})
.unwrap();
let mk = function(
&s,
"mk",
vec![
p("a", Type::Number, Confidence::Structural),
p("b", Type::Number, Confidence::Structural),
],
produces(Type::Named("Point".into()), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rec,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![pd],
functions: vec![mk],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 2));
}
#[test]
fn an_unknown_record_type_is_a_principle_1_violation() {
let s = Store::open_in_memory().unwrap();
let z = s.put(&Node::Lit(0)).unwrap();
let rec = s
.put(&Node::Record {
type_name: "Nope".into(),
fields: vec![("a".into(), z)],
})
.unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Named("Nope".into()), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
rec,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 1));
}
/// `type Status = variant { Active, Closed(reason: Number) }` and a
/// function that constructs and exhaustively matches it.
fn status_def(s: &Store) -> NodeHash {
s.put(&Node::VariantDef {
name: "Status".into(),
cases: vec![
("Active".into(), vec![]),
("Closed".into(), vec![("reason".into(), Type::Number)]),
],
})
.unwrap()
}
#[test]
fn a_variant_module_with_exhaustive_match_is_clean() {
let s = Store::open_in_memory().unwrap();
let sd = status_def(&s);
// describe(st) -> match st { Active -> 0, Closed(reason) -> reason }
let st = s.put(&Node::Ref("st".into())).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
let rref = s.put(&Node::Ref("reason".into())).unwrap();
let m = s
.put(&Node::Match {
scrutinee: st,
type_name: "Status".into(),
arms: vec![
MatchArm {
case: "Active".into(),
bindings: vec![],
body: zero,
},
MatchArm {
case: "Closed".into(),
bindings: vec!["reason".into()],
body: rref,
},
],
})
.unwrap();
let describe = function(
&s,
"describe",
vec![p(
"st",
Type::Named("Status".into()),
Confidence::Structural,
)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
m,
);
let module = s
.put(&Node::Module {
name: "m".into(),
types: vec![sd],
functions: vec![describe],
})
.unwrap();
let r = Checker::new(&s).check(&module).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
}
#[test]
fn a_non_exhaustive_match_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let sd = status_def(&s);
let st = s.put(&Node::Ref("st".into())).unwrap();
let zero = s.put(&Node::Lit(0)).unwrap();
// Only covers Active; Closed missing.
let m = s
.put(&Node::Match {
scrutinee: st,
type_name: "Status".into(),
arms: vec![MatchArm {
case: "Active".into(),
bindings: vec![],
body: zero,
}],
})
.unwrap();
let f = function(
&s,
"f",
vec![p(
"st",
Type::Named("Status".into()),
Confidence::Structural,
)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
m,
);
let module = s
.put(&Node::Module {
name: "m".into(),
types: vec![sd],
functions: vec![f],
})
.unwrap();
let r = Checker::new(&s).check(&module).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("Closed")));
}
#[test]
fn constructing_an_unknown_case_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let sd = status_def(&s);
let bad = s
.put(&Node::Variant {
type_name: "Status".into(),
case: "Nope".into(),
fields: vec![],
})
.unwrap();
let f = function(
&s,
"mk",
vec![],
produces(Type::Named("Status".into()), Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
bad,
);
let module = s
.put(&Node::Module {
name: "m".into(),
types: vec![sd],
functions: vec![f],
})
.unwrap();
let r = Checker::new(&s).check(&module).unwrap();
assert!(r
.violations
.iter()
.any(|v| v.principle == 2 && v.detail.contains("Nope")));
}
/// `identity<T>(x: T) -> T` used at `Number` — the type parameter is
/// inferred from the argument and substituted into the result.
fn identity_fn(s: &Store) -> NodeHash {
let x = s.put(&Node::Ref("x".into())).unwrap();
s.put(&Node::Function {
name: "identity".into(),
type_params: vec!["T".into()],
params: vec![p("x", Type::Var("T".into()), Confidence::Structural)],
produces: Produces {
ty: Type::Var("T".into()),
confidence: Confidence::Structural,
},
requires: BTreeSet::new(),
on_failure: vec![],
body: vec![],
result: x,
})
.unwrap()
}
#[test]
fn a_generic_function_resolves_at_the_call_site() {
let s = Store::open_in_memory().unwrap();
let id = identity_fn(&s);
let n = s.put(&Node::Ref("n".into())).unwrap();
let call = s
.put(&Node::Call {
func: "identity".into(),
args: vec![n],
})
.unwrap();
let f = function(
&s,
"use_id",
vec![p("n", Type::Number, Confidence::Structural)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
call,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![id, f],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
}
#[test]
fn a_generic_argument_conflict_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
// pair<T>(a: T, b: T) -> T
let aref = s.put(&Node::Ref("a".into())).unwrap();
let pair = s
.put(&Node::Function {
name: "pair".into(),
type_params: vec!["T".into()],
params: vec![
p("a", Type::Var("T".into()), Confidence::Structural),
p("b", Type::Var("T".into()), Confidence::Structural),
],
produces: Produces {
ty: Type::Var("T".into()),
confidence: Confidence::Structural,
},
requires: BTreeSet::new(),
on_failure: vec![],
body: vec![],
result: aref,
})
.unwrap();
// g(n) = pair(n, n < n) — T bound to Number then to Bool.
let n1 = s.put(&Node::Ref("n".into())).unwrap();
let n2 = s.put(&Node::Ref("n".into())).unwrap();
let n3 = s.put(&Node::Ref("n".into())).unwrap();
let cmp = s
.put(&Node::BinOp {
op: BinOp::Lt,
lhs: n2,
rhs: n3,
})
.unwrap();
let call = s
.put(&Node::Call {
func: "pair".into(),
args: vec![n1, cmp],
})
.unwrap();
let g = function(
&s,
"g",
vec![p("n", Type::Number, Confidence::Structural)],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
call,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![pair, g],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 2));
}
#[test]
fn string_literal_and_str_len_typecheck() {
let s = Store::open_in_memory().unwrap();
// greet() -> String { yield "hello" }
let hello = s.put(&Node::Str("hello".into())).unwrap();
let greet = function(
&s,
"greet",
vec![],
produces(Type::String, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
hello,
);
// size() -> Number { yield str_len("hello") }
let h2 = s.put(&Node::Str("hello".into())).unwrap();
let sl = s.put(&Node::StrLen(h2)).unwrap();
let size = function(
&s,
"size",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
sl,
);
let m = s
.put(&Node::Module {
name: "m".into(),
types: vec![],
functions: vec![greet, size],
})
.unwrap();
let r = Checker::new(&s).check(&m).unwrap();
assert!(r.ok(), "unexpected: {:?}", r.violations);
}
#[test]
fn str_len_on_a_number_is_a_principle_2_violation() {
let s = Store::open_in_memory().unwrap();
let n = s.put(&Node::Lit(3)).unwrap();
let sl = s.put(&Node::StrLen(n)).unwrap();
let f = function(
&s,
"f",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
sl,
);
let r = Checker::new(&s).check(&f).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 2));
}
#[test]
fn a_homogeneous_list_typechecks_and_a_mixed_one_does_not() {
let s = Store::open_in_memory().unwrap();
// ok: [1,2,3] -> List<Number>; list_get(...,0) -> Number
let e0 = s.put(&Node::Lit(1)).unwrap();
let e1 = s.put(&Node::Lit(2)).unwrap();
let lst = s.put(&Node::List(vec![e0, e1])).unwrap();
let idx = s.put(&Node::Lit(0)).unwrap();
let g = s
.put(&Node::ListGet {
list: lst,
index: idx,
})
.unwrap();
let ok = function(
&s,
"ok",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
g,
);
assert!(Checker::new(&s).check(&ok).unwrap().ok());
// bad: [1, "x"] -> P2 (mixed element types)
let n = s.put(&Node::Lit(1)).unwrap();
let t = s.put(&Node::Str("x".into())).unwrap();
let mixed = s.put(&Node::List(vec![n, t])).unwrap();
let len = s.put(&Node::ListLen(mixed)).unwrap();
let bad = function(
&s,
"bad",
vec![],
produces(Type::Number, Confidence::Structural),
BTreeSet::new(),
vec![],
vec![],
len,
);
let r = Checker::new(&s).check(&bad).unwrap();
assert!(r.violations.iter().any(|v| v.principle == 2));
}
}