aver-lang 0.27.0

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
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
use super::{
    VerifyEmitMode, generate_prelude, proof_mode_issues, recurrence, transpile,
    transpile_for_proof_mode, transpile_with_verify_mode,
};
use crate::ast::{
    BinOp, Expr, FnBody, FnDef, Literal, MatchArm, Pattern, Spanned, Stmt, TailCallData, TopLevel,
    TypeDef, TypeVariant, VerifyBlock, VerifyGiven, VerifyGivenDomain, VerifyKind, VerifyLaw,
};

/// Shorthand: wrap an Expr in Spanned with line=0.
fn sb(e: Expr) -> Spanned<Expr> {
    Spanned::bare(e)
}
/// Shorthand: wrap an Expr in Box<Spanned> with line=0.
fn sbb(e: Expr) -> Box<Spanned<Expr>> {
    Box::new(Spanned::bare(e))
}
use crate::codegen::{CodegenContext, build_context};
use crate::source::parse_source;

use std::collections::{HashMap, HashSet};
use std::sync::Arc as Rc;

/// Populate `ctx.proof_ir` from the current items. Synthetic-AST
/// tests bypass the pipeline (where ProofLower runs automatically);
/// IR-pinned law strategies rely on this being populated so the
/// backend's IR-pin lookups can fire.
fn populate_proof_ir(ctx: &mut CodegenContext) {
    // Mirror the production order: BuildSymbols → proof_lower. The
    // populate side asserts the symbol table is present (it's a
    // hard prerequisite for FnId-keyed fn_contracts), so synthetic-
    // ctx tests have to build it the same way `refresh_facts` does.
    ctx.symbol_table = crate::ir::SymbolTable::build(&ctx.items, &ctx.modules);
    let inputs = crate::codegen::proof_lower::ProofLowerInputs::from_ctx(ctx);
    ctx.proof_ir = crate::codegen::proof_lower::lower(&inputs);
}

fn empty_ctx() -> CodegenContext {
    CodegenContext {
        items: vec![],
        type_defs: vec![],
        fn_defs: vec![],
        project_name: "verify_mode".to_string(),
        modules: vec![],
        module_prefixes: HashSet::new(),
        policy: None,
        emit_replay_runtime: false,
        runtime_policy_from_env: false,
        guest_entry: None,
        emit_self_host_support: false,
        extra_fn_defs: Vec::new(),
        mutual_tco_members: HashSet::<crate::ir::FnId>::new(),
        recursive_fns: HashSet::<crate::ir::FnId>::new(),
        buffer_build_sinks: HashMap::new(),
        buffer_fusion_sites: Vec::new(),
        synthesized_buffered_fns: Vec::new(),
        proof_ir: crate::ir::ProofIR::default(),
        symbol_table: crate::ir::SymbolTable::default(),
        resolved_fn_defs: Vec::new(),
        resolved_module_fn_defs: Vec::new(),
        current_module_scope: std::cell::RefCell::new(None),
        resolved_program: crate::codegen::program_view::ResolvedProgramView::default(),
        program_shape: None,
        mir_program: None,
        bare_i64: Default::default(),
        discovered_lemmas: Vec::new(),
        sample_expected: std::collections::HashMap::new(),
        allow_mathlib: false,
        hand_proofs: Default::default(),
    }
}

fn ctx_from_source(source: &str, project_name: &str) -> CodegenContext {
    let mut items = parse_source(source).expect("source should parse");
    // Proof-mode minimal pipeline: only the stages a proof
    // exporter actually consumes. Resolve / last_use / escape /
    // interp_lower / buffer_build all rewrite item shapes in
    // ways that break the recursion classifier's source-level
    // pattern matching (e.g. escape inlines a record into the
    // caller, dropping the recursive call's structural shape).
    // Analyze stays on — `recursive_fns` is what `proof_lower`
    // reads to decide which fns to classify.
    let pipeline_result = crate::ir::pipeline::run(
        &mut items,
        crate::ir::PipelineConfig {
            run_tco: true,
            typecheck: Some(crate::ir::TypecheckMode::Full { base_dir: None }),
            run_interp_lower: false,
            run_buffer_build: false,
            run_resolve: false,
            run_last_use: false,
            run_analyze: true,
            run_escape: false,
            run_refinement_lower: true,
            run_interval_analyze: false,
            run_contract_lower: true,
            run_law_lower: true,
            // BuildSymbols is needed for fn_contracts lookup
            // (keyed by opaque FnId resolved through the symbol
            // table since the FnKey → FnId migration).
            run_build_symbols: true,
            dep_modules: &[],
            alloc_policy: None,
            call_ctx: None,
            on_after_pass: None,
        },
    );
    let tc = pipeline_result.typecheck.expect("typecheck requested");
    assert!(
        tc.errors.is_empty(),
        "source should typecheck without errors: {:?}",
        tc.errors
    );
    let proof_ir = pipeline_result.proof_ir;
    let mut ctx = build_context(
        items,
        &tc,
        pipeline_result.analysis.as_ref(),
        project_name.to_string(),
        vec![],
        pipeline_result.symbol_table,
        pipeline_result.resolved_items,
    );
    if let Some(ir) = proof_ir {
        ctx.proof_ir = ir;
    }
    ctx
}

/// Concatenate every emitted `.lean` source (entry + per-module +
/// `AverCommon`) into a single string for content assertions. The
/// unified emitter splits prelude (`AverCommon.lean`) and body
/// (`<Project>.lean`) into separate files; tests originally checked
/// for substrings against the legacy single-file output, so the
/// helper now returns the concatenation so those substring assertions
/// keep working regardless of which file the content lands in.
fn generated_lean_file(out: &crate::codegen::ProjectOutput) -> String {
    out.files
        .iter()
        .filter_map(|(name, content)| {
            (name.ends_with(".lean") && name != "lakefile.lean").then_some(content.as_str())
        })
        .collect::<Vec<&str>>()
        .join("\n")
}

fn empty_ctx_with_verify_case() -> CodegenContext {
    let mut ctx = empty_ctx();
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "f".to_string(),
        line: 1,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(1))),
            sb(Expr::Literal(Literal::Int(1))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Cases,
        trace: false,
        cases_givens: vec![],
    }));
    ctx
}

fn empty_ctx_with_two_verify_blocks_same_fn() -> CodegenContext {
    let mut ctx = empty_ctx();
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "f".to_string(),
        line: 1,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(1))),
            sb(Expr::Literal(Literal::Int(1))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Cases,
        trace: false,
        cases_givens: vec![],
    }));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "f".to_string(),
        line: 2,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(2))),
            sb(Expr::Literal(Literal::Int(2))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Cases,
        trace: false,
        cases_givens: vec![],
    }));
    ctx
}

fn empty_ctx_with_verify_law() -> CodegenContext {
    let mut ctx = empty_ctx();
    let add = FnDef {
        name: "add".to_string(),
        line: 1,
        params: vec![
            ("a".to_string(), "Int".to_string()),
            ("b".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Add,
            sbb(Expr::Ident("a".to_string())),
            sbb(Expr::Ident("b".to_string())),
        )))),
        resolution: None,
    };
    ctx.fn_defs.push(add.clone());
    ctx.items.push(TopLevel::FnDef(add));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "add".to_string(),
        line: 1,
        cases: vec![
            (
                sb(Expr::FnCall(
                    sbb(Expr::Ident("add".to_string())),
                    vec![
                        sb(Expr::Literal(Literal::Int(1))),
                        sb(Expr::Literal(Literal::Int(2))),
                    ],
                )),
                sb(Expr::FnCall(
                    sbb(Expr::Ident("add".to_string())),
                    vec![
                        sb(Expr::Literal(Literal::Int(2))),
                        sb(Expr::Literal(Literal::Int(1))),
                    ],
                )),
            ),
            (
                sb(Expr::FnCall(
                    sbb(Expr::Ident("add".to_string())),
                    vec![
                        sb(Expr::Literal(Literal::Int(2))),
                        sb(Expr::Literal(Literal::Int(3))),
                    ],
                )),
                sb(Expr::FnCall(
                    sbb(Expr::Ident("add".to_string())),
                    vec![
                        sb(Expr::Literal(Literal::Int(3))),
                        sb(Expr::Literal(Literal::Int(2))),
                    ],
                )),
            ),
        ],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "commutative".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "a".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
                },
                VerifyGiven {
                    name: "b".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![
                        sb(Expr::Literal(Literal::Int(2))),
                        sb(Expr::Literal(Literal::Int(3))),
                    ]),
                },
            ],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::Ident("b".to_string())),
                ],
            )),
            rhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("b".to_string())),
                    sb(Expr::Ident("a".to_string())),
                ],
            )),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    ctx
}

#[test]
fn prelude_normalizes_float_string_format() {
    let prelude = generate_prelude();
    assert!(
        prelude.contains("private def normalizeFloatString (s : String) : String :="),
        "missing normalizeFloatString helper in prelude"
    );
    assert!(
        prelude.contains(
            "def String.fromFloat (f : Float) : String := normalizeFloatString (toString f)"
        ),
        "String.fromFloat should normalize Lean float formatting"
    );
}

#[test]
fn prelude_validates_char_from_code_unicode_bounds() {
    let prelude = generate_prelude();
    assert!(
        prelude.contains("if n < 0 || n > 1114111 then none"),
        "Char.fromCode should reject code points above Unicode max"
    );
    assert!(
        prelude.contains("else if n >= 55296 && n <= 57343 then none"),
        "Char.fromCode should reject surrogate code points"
    );
}

#[test]
fn prelude_includes_map_set_helper_lemmas() {
    let prelude = generate_prelude();
    assert!(
        prelude.contains("theorem has_set_self [DecidableEq α]"),
        "missing AverMap.has_set_self helper theorem"
    );
    assert!(
        prelude.contains("theorem get_set_self [DecidableEq α]"),
        "missing AverMap.get_set_self helper theorem"
    );
}

#[test]
fn lean_output_without_map_usage_omits_map_prelude() {
    let mut ctx = ctx_from_source(
        r#"
module NoMap
    intent = "Simple pure program without maps."

fn addOne(n: Int) -> Int
    n + 1

verify addOne
    addOne(1) => 2
"#,
        "nomap",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(
        !lean.contains("namespace AverMap"),
        "did not expect AverMap prelude in program without map usage:\n{}",
        lean
    );
}

#[test]
fn transpile_emits_native_decide_for_verify_by_default() {
    let mut ctx = empty_ctx_with_verify_case();
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("example : 1 = 1 := by native_decide"));
}

#[test]
fn transpile_can_emit_sorry_for_verify_when_requested() {
    let mut ctx = empty_ctx_with_verify_case();
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::Sorry);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("example : 1 = 1 := by sorry"));
}

#[test]
fn transpile_can_emit_theorem_skeletons_for_verify() {
    let mut ctx = empty_ctx_with_verify_case();
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
    assert!(lean.contains("  sorry"));
}

#[test]
fn theorem_skeleton_numbering_is_global_per_function_across_verify_blocks() {
    let mut ctx = empty_ctx_with_two_verify_blocks_same_fn();
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
    assert!(lean.contains("theorem f_verify_2 : 2 = 2 := by"));
}

#[test]
fn transpile_emits_named_theorems_for_verify_law() {
    let mut ctx = empty_ctx_with_verify_law();
    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("-- verify law add.commutative (2 cases)"));
    assert!(lean.contains("-- given a: Int = 1..2"));
    assert!(lean.contains("-- given b: Int = [2, 3]"));
    assert!(
        lean.contains(
            "theorem add_law_commutative : ∀ (a : Int) (b : Int), add a b = add b a := by"
        )
    );
    assert!(lean.contains("  intro a b"));
    assert!(lean.contains("  simp [add, Int.add_comm]"));
    assert!(
        lean.contains(
            "theorem add_law_commutative_sample_1 : add 1 2 = add 2 1 := by native_decide"
        )
    );
    assert!(
        lean.contains(
            "theorem add_law_commutative_sample_2 : add 2 3 = add 3 2 := by native_decide"
        )
    );
}

#[test]
fn generate_prelude_emits_int_roundtrip_theorem() {
    let lean = generate_prelude();
    assert!(lean.contains(
        "theorem Int.fromString_fromInt : ∀ n : Int, Int.fromString (String.fromInt n) = .ok n"
    ));
    assert!(lean.contains("theorem String.intercalate_empty_chars (s : String) :"));
    assert!(lean.contains("def splitOnCharGo"));
    assert!(lean.contains("theorem split_single_char_append"));
    assert!(lean.contains("theorem split_intercalate_trailing_single_char"));
    assert!(lean.contains("namespace AverDigits"));
    assert!(lean.contains("theorem String.charAt_length_none (s : String)"));
    assert!(lean.contains("theorem digitChar_not_ws : ∀ d : Nat, d < 10 ->"));
}

#[test]
fn transpile_emits_guarded_theorems_for_verify_law_when_clause() {
    let mut ctx = ctx_from_source(
        r#"
module GuardedLaw
    intent =
        "verify law with precondition"

fn pickGreater(a: Int, b: Int) -> Int
    match a > b
        true -> a
        false -> b

verify pickGreater law ordered
    given a: Int = [1, 2]
    given b: Int = [1, 2]
    when a > b
    pickGreater(a, b) => a
"#,
        "guarded_law",
    );
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- when (a > b)"));
    assert!(lean.contains(
            "theorem pickGreater_law_ordered : ∀ (a : Int) (b : Int), a = 1 ∨ a = 2 -> b = 1 ∨ b = 2 -> (a > b) = true -> pickGreater a b = a := by"
        ));
    // Sample guards Int-ascribe their substituted numerals: a bare
    // `(1 - 2 > 0)` premise would elaborate over Nat, where truncated
    // subtraction can make the theorem FALSE AS STATED.
    assert!(lean.contains(
            "theorem pickGreater_law_ordered_sample_1 : ((1 : Int) > (1 : Int)) = true -> pickGreater 1 1 = 1 := by"
        ));
    assert!(lean.contains(
            "theorem pickGreater_law_ordered_sample_4 : ((2 : Int) > (2 : Int)) = true -> pickGreater 2 2 = 2 := by"
        ));
}

#[test]
fn transpile_uses_spec_theorem_names_for_declared_spec_laws() {
    let mut ctx = ctx_from_source(
        r#"
module SpecDemo
    intent =
        "spec demo"

fn absVal(x: Int) -> Int
    match x < 0
        true -> 0 - x
        false -> x

fn absValSpec(x: Int) -> Int
    match x < 0
        true -> 0 - x
        false -> x

verify absVal law absValSpec
    given x: Int = [-2, -1, 0, 1, 2]
    absVal(x) => absValSpec(x)
"#,
        "spec_demo",
    );
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- verify law absVal.spec absValSpec (5 cases)"));
    assert!(
        lean.contains("theorem absVal_eq_absValSpec : ∀ (x : Int), absVal x = absValSpec x := by")
    );
    assert!(lean.contains("theorem absVal_eq_absValSpec_checked_domain :"));
    assert!(lean.contains("theorem absVal_eq_absValSpec_sample_1 :"));
    assert!(!lean.contains("theorem absVal_law_absValSpec :"));
}

#[test]
fn transpile_keeps_noncanonical_spec_laws_as_regular_law_names() {
    let mut ctx = ctx_from_source(
        r#"
module SpecLawShape
    intent =
        "shape probe"

fn foo(x: Int) -> Int
    x + 1

fn fooSpec(seed: Int, x: Int) -> Int
    x + seed

verify foo law fooSpec
    given x: Int = [1, 2]
    foo(x) => fooSpec(1, x)
"#,
        "spec_law_shape",
    );
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- verify law foo.fooSpec (2 cases)"));
    assert!(lean.contains("theorem foo_law_fooSpec : ∀ (x : Int), foo x = fooSpec 1 x := by"));
    assert!(!lean.contains("theorem foo_eq_fooSpec :"));
}

#[test]
fn transpile_auto_proves_linear_int_canonical_spec_law_in_auto_mode() {
    let mut ctx = ctx_from_source(
        r#"
module SpecGap
    intent =
        "nontrivial canonical spec law"

fn inc(x: Int) -> Int
    x + 1

fn incSpec(x: Int) -> Int
    x + 2 - 1

verify inc law incSpec
    given x: Int = [0, 1, 2]
    inc(x) => incSpec(x)
"#,
        "spec_gap",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- verify law inc.spec incSpec (3 cases)"));
    assert!(lean.contains("theorem inc_eq_incSpec : ∀ (x : Int), inc x = incSpec x := by"));
    assert!(lean.contains("change (x + 1) = ((x + 2) - 1)"));
    assert!(lean.contains("omega"));
    assert!(!lean.contains(
        "-- universal theorem inc_eq_incSpec omitted: sampled law shape is not auto-proved yet"
    ));
    assert!(lean.contains("theorem inc_eq_incSpec_checked_domain :"));
}

#[test]
fn transpile_auto_proves_guarded_canonical_spec_law_in_auto_mode() {
    let mut ctx = ctx_from_source(
        r#"
module GuardedSpecGap
    intent =
        "guarded canonical spec law"

fn clampNonNegative(x: Int) -> Int
    match x < 0
        true -> 0
        false -> x

fn clampNonNegativeSpec(x: Int) -> Int
    match x < 0
        true -> 0
        false -> x

verify clampNonNegative law clampNonNegativeSpec
    given x: Int = [-2, -1, 0, 1, 2]
    when x >= 0
    clampNonNegative(x) => clampNonNegativeSpec(x)
"#,
        "guarded_spec_gap",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- when (x >= 0)"));
    assert!(lean.contains(
            "theorem clampNonNegative_eq_clampNonNegativeSpec : ∀ (x : Int), x = (-2) ∨ x = (-1) ∨ x = 0 ∨ x = 1 ∨ x = 2 -> (x >= 0) = true -> clampNonNegative x = clampNonNegativeSpec x := by"
        ));
    assert!(lean.contains("intro x h_x h_when"));
    assert!(lean.contains("simpa [clampNonNegative, clampNonNegativeSpec]"));
    assert!(!lean.contains(
            "-- universal theorem clampNonNegative_eq_clampNonNegativeSpec omitted: sampled law shape is not auto-proved yet"
        ));
    assert!(!lean.contains("cases h_x"));
}

#[test]
fn transpile_proves_conditional_comparison_bridge_law_as_universal() {
    // `prop_70 leSucc`: `when le(m, n) -> le(m, S n) => true`. The conditional
    // comparison-bridge emit closes it as the TRUE-universal
    // `∀ m n, le m n = true -> le m (n + 1) = true` — the sampled-domain
    // disjunctions are dropped (`omit_domain`) so the law is classed `universal`,
    // and the premise + goal are bridged to `≤` and discharged by `omega`.
    let mut ctx = ctx_from_source(
        r#"
module CondCmpBridge
    intent = "conditional comparison bridge: le(m,n) implies le(m, S n)"

type Nat
    Z
    S(Nat)

fn le(x: Nat, y: Nat) -> Bool
    match x
        Nat.Z -> true
        Nat.S(z) -> match y
            Nat.Z -> false
            Nat.S(x2) -> le(z, x2)

verify le law leSucc
    given m: Nat = [Nat.Z, Nat.S(Nat.Z)]
    given n: Nat = [Nat.Z, Nat.S(Nat.Z)]
    when le(m, n)
    le(m, Nat.S(n)) => true
"#,
        "cond_cmp_bridge",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    // Classed `universal`, NOT `bounded-domain`.
    assert!(lean.contains("-- aver:law-class le_law_leSucc universal le.leSucc"));
    // The TRUE-universal conditional statement: no `m = 0 ∨ …` sampled-domain
    // premise, the `when` survives as the `= true ->` implication.
    assert!(lean.contains(
        "theorem le_law_leSucc : ∀ (m : Nat) (n : Nat), le m n = true -> le m (n + 1) = true := by"
    ));
    // Law-scoped `≤` bridge support theorem (uid `le_leSucc`, no `_law_` so the
    // audit never mistakes it for a creditable main theorem).
    assert!(lean.contains("theorem le_leSucc_le_isNatLe : ∀ a b, (le a b = true) = (a ≤ b) := by"));
    // Premise introduced as `h_when`; bridged at hypothesis and goal, `omega` closes.
    assert!(lean.contains("intro m n h_when"));
    assert!(lean.contains("simp only [le_leSucc_le_isNatLe] at h_when ⊢ <;> omega"));
}

#[test]
fn transpile_proves_conditional_inductive_membership_law_as_universal() {
    // `prop_36 elemConcat`: `when elem(x,y) -> elem(x, y ++ z) => true` (append
    // monotonicity). The GENERIC conditional-inductive driver (no bespoke
    // membership emitter) closes it as the TRUE-universal `∀ x y z, elem x y =
    // true -> elem x (y ++ z) = true` by induction on the first list given,
    // threading the premise into the cons arm. Admitted with no helper-pool gate;
    // the partner list `z` is intro'd before the premise (`intro z h_when`).
    let mut ctx = ctx_from_source(
        r#"
module CondIndMembership
    intent = "conditional inductive membership: elem x y implies elem x (y ++ z)"

type Nat
    Z
    S(Nat)

fn eqNat(x: Nat, y: Nat) -> Bool
    match x
        Nat.Z -> match y
            Nat.Z -> true
            Nat.S(z) -> false
        Nat.S(x2) -> match y
            Nat.Z -> false
            Nat.S(y2) -> eqNat(x2, y2)

fn barbar(x: Bool, y: Bool) -> Bool
    match x
        true -> true
        false -> y

fn elem(x: Nat, y: List<Nat>) -> Bool
    match y
        [] -> false
        [z, ..xs] -> barbar(eqNat(x, z), elem(x, xs))

verify elem law elemConcat
    given x: Nat = [Nat.Z, Nat.S(Nat.Z)]
    given y: List<Nat> = [[Nat.Z], [Nat.S(Nat.Z)]]
    given z: List<Nat> = [[], [Nat.Z]]
    when elem(x, y)
    elem(x, List.concat(y, z)) => true
"#,
        "cond_ind_membership",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    // Classed `universal`, NOT `bounded-domain` (the sampled-domain disjunctions
    // are dropped via `omit_domain`).
    assert!(lean.contains("-- aver:law-class elem_law_elemConcat universal elem.elemConcat"));
    // The TRUE-universal conditional statement (no `y = [..] ∨ …` domain premise).
    assert!(lean.contains(
        "theorem elem_law_elemConcat : ∀ (x : Nat) (y : List Nat) (z : List Nat), elem x y = true -> elem x (y ++ z) = true := by"
    ));
    // Induction on the first list given `y`, with the partner list + premise
    // threaded INSIDE the cons arm (`intro z h_when` after `induction`, so the IH
    // carries the antecedent and generalizes over the partner).
    assert!(lean.contains("induction y with"));
    assert!(lean.contains("| cons hd tl ih =>"));
    assert!(lean.contains("intro z h_when"));
}

#[test]
fn transpile_proves_zip_rev_via_generic_decomposition() {
    // `prop_85 zipRev` closes through the DECOMPOSITION path, NOT a hardcoded
    // Lean template: a `zipSnocDistribution` helper `verify ... law` supplies the
    // algebraic content, and the GENERIC conditional-inductive driver proves
    // zipRev by list induction + `simp_all` over the fn defs AND that earlier
    // helper (the laws-as-lemmas pool). The premise `when` law is cited as the
    // conditional rewrite `… = true -> …`.
    let mut ctx = ctx_from_source(
        r#"
module ZipRev
    intent = "if len xs = len ys then zip (rev xs) (rev ys) = revPair (zip xs ys)"

type Nat
    Z
    S(Nat)

fn natEq(a: Nat, b: Nat) -> Bool
    match a
        Nat.Z -> match b
            Nat.Z -> true
            Nat.S(y) -> false
        Nat.S(x) -> match b
            Nat.Z -> false
            Nat.S(y) -> natEq(x, y)

fn len(xs: List<Int>) -> Nat
    match xs
        [] -> Nat.Z
        [y, ..ys] -> Nat.S(len(ys))

fn appendInt(xs: List<Int>, ys: List<Int>) -> List<Int>
    match xs
        [] -> ys
        [z, ..zs] -> List.concat([z], appendInt(zs, ys))

fn appendPair(xs: List<Tuple<Int, Int>>, ys: List<Tuple<Int, Int>>) -> List<Tuple<Int, Int>>
    match xs
        [] -> ys
        [z, ..zs] -> List.concat([z], appendPair(zs, ys))

fn rev(xs: List<Int>) -> List<Int>
    match xs
        [] -> []
        [y, ..ys] -> appendInt(rev(ys), [y])

fn revPair(xs: List<Tuple<Int, Int>>) -> List<Tuple<Int, Int>>
    match xs
        [] -> []
        [y, ..ys] -> appendPair(revPair(ys), [y])

fn zip(xs: List<Int>, ys: List<Int>) -> List<Tuple<Int, Int>>
    match xs
        [] -> []
        [z, ..x2] -> match ys
            [] -> []
            [x3, ..x4] -> List.concat([(z, x3)], zip(x2, x4))

verify len law lenSnocSucc
    given a: List<Int> = [[], [1], [1, 2]]
    given x: Int = [9]
    len(appendInt(a, [x])) => Nat.S(len(a))

verify zip law zipSnocDistribution
    given as: List<Int> = [[], [1]]
    given bs: List<Int> = [[], [4]]
    given x: Int = [7]
    given y: Int = [9]
    when natEq(len(as), len(bs))
    zip(appendInt(as, [x]), appendInt(bs, [y])) => appendPair(zip(as, bs), [(x, y)])

verify zip law zipRev
    given xs: List<Int> = [[], [1], [1, 2]]
    given ys: List<Int> = [[], [4], [4, 5]]
    when natEq(len(xs), len(ys))
    zip(rev(xs), rev(ys)) => revPair(zip(xs, ys))
"#,
        "zip_rev",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    // zipRev is classed `universal` and proved by the GENERIC driver: list
    // induction threading the premise, with the snoc-distribution HELPER LAW
    // cited from the pool inside the proof's `simp_all` set.
    assert!(lean.contains("-- aver:law-class zip_law_zipRev universal zip.zipRev"));
    assert!(lean.contains(
        "theorem zip_law_zipRev : ∀ (xs : List Int) (ys : List Int), natEq (len xs) (len ys) = true -> zip (rev xs) (rev ys) = revPair (zip xs ys) := by"
    ));
    assert!(lean.contains("induction xs with"));
    assert!(lean.contains("zip_law_zipSnocDistribution"));
    // No hardcoded per-figure template (the old `zip_rev_supports_body` path).
    assert!(!lean.contains("zip_zipRev_snoc"));
}

#[test]
fn transpile_auto_proves_simp_normalized_canonical_spec_law_in_auto_mode() {
    let mut ctx = ctx_from_source(
        r#"
module SpecGapNonlinear
    intent =
        "nonlinear canonical spec law"

fn square(x: Int) -> Int
    x * x

fn squareSpec(x: Int) -> Int
    x * x + 0

verify square law squareSpec
    given x: Int = [0, 1, 2]
    square(x) => squareSpec(x)
"#,
        "spec_gap_nonlinear",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("-- verify law square.spec squareSpec (3 cases)"));
    assert!(
        lean.contains("theorem square_eq_squareSpec : ∀ (x : Int), square x = squareSpec x := by")
    );
    assert!(lean.contains("simp [square, squareSpec]"));
    assert!(!lean.contains(
            "-- universal theorem square_eq_squareSpec omitted: sampled law shape is not auto-proved yet"
        ));
    assert!(lean.contains("theorem square_eq_squareSpec_checked_domain :"));
    assert!(lean.contains("theorem square_eq_squareSpec_sample_1 :"));
}

#[test]
fn transpile_auto_proves_reflexive_law_with_rfl() {
    let mut ctx = empty_ctx();
    // After the phase-E3 migration LawTheorem.fn_id is resolved
    // through the symbol table at populate time, so the law's
    // target fn must exist as a FnDef in `ctx.items`. Pre-fix
    // the verify block alone was enough (FnKey was constructed
    // from the bare name without checking).
    let id_law = FnDef {
        name: "idLaw".to_string(),
        line: 1,
        params: vec![("x".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Ident("x".to_string())))),
        resolution: None,
    };
    ctx.fn_defs.push(id_law.clone());
    ctx.items.push(TopLevel::FnDef(id_law));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "idLaw".to_string(),
        line: 1,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(1))),
            sb(Expr::Literal(Literal::Int(1))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "reflexive".to_string(),
            givens: vec![VerifyGiven {
                name: "x".to_string(),
                type_name: "Int".to_string(),
                domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
            }],
            when: None,
            lhs: sb(Expr::Ident("x".to_string())),
            rhs: sb(Expr::Ident("x".to_string())),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    // Synthetic-AST test bypasses the parser + pipeline, so the
    // LawLower stage hasn't run. refresh_facts populates
    // ProofIR.law_theorems with Reflexive on `x => x` — backend's
    // Step-24 reader checks the IR to emit rfl.
    ctx.refresh_facts();
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem idLaw_law_reflexive : ∀ (x : Int), x = x := by"));
    assert!(lean.contains("  intro x"));
    assert!(lean.contains("  rfl"));
}

#[test]
fn transpile_auto_proves_identity_law_for_int_add_wrapper() {
    let mut ctx = empty_ctx_with_verify_law();
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "add".to_string(),
        line: 10,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(1))),
                    sb(Expr::Literal(Literal::Int(0))),
                ],
            )),
            sb(Expr::Literal(Literal::Int(1))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "identityZero".to_string(),
            givens: vec![VerifyGiven {
                name: "a".to_string(),
                type_name: "Int".to_string(),
                domain: VerifyGivenDomain::Explicit(vec![
                    sb(Expr::Literal(Literal::Int(0))),
                    sb(Expr::Literal(Literal::Int(1))),
                ]),
            }],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::Literal(Literal::Int(0))),
                ],
            )),
            rhs: sb(Expr::Ident("a".to_string())),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem add_law_identityZero : ∀ (a : Int), add a 0 = a := by"));
    assert!(lean.contains("  intro a"));
    assert!(lean.contains("  simp [add]"));
}

#[test]
fn transpile_auto_proves_associative_law_for_int_add_wrapper() {
    let mut ctx = empty_ctx_with_verify_law();
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "add".to_string(),
        line: 20,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::FnCall(
                        sbb(Expr::Ident("add".to_string())),
                        vec![
                            sb(Expr::Literal(Literal::Int(1))),
                            sb(Expr::Literal(Literal::Int(2))),
                        ],
                    )),
                    sb(Expr::Literal(Literal::Int(3))),
                ],
            )),
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(1))),
                    sb(Expr::FnCall(
                        sbb(Expr::Ident("add".to_string())),
                        vec![
                            sb(Expr::Literal(Literal::Int(2))),
                            sb(Expr::Literal(Literal::Int(3))),
                        ],
                    )),
                ],
            )),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "associative".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "a".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(1)))]),
                },
                VerifyGiven {
                    name: "b".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
                },
                VerifyGiven {
                    name: "c".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(3)))]),
                },
            ],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::FnCall(
                        sbb(Expr::Ident("add".to_string())),
                        vec![
                            sb(Expr::Ident("a".to_string())),
                            sb(Expr::Ident("b".to_string())),
                        ],
                    )),
                    sb(Expr::Ident("c".to_string())),
                ],
            )),
            rhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::FnCall(
                        sbb(Expr::Ident("add".to_string())),
                        vec![
                            sb(Expr::Ident("b".to_string())),
                            sb(Expr::Ident("c".to_string())),
                        ],
                    )),
                ],
            )),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains(
            "theorem add_law_associative : ∀ (a : Int) (b : Int) (c : Int), add (add a b) c = add a (add b c) := by"
        ));
    assert!(lean.contains("  intro a b c"));
    assert!(lean.contains("  simp [add, Int.add_assoc]"));
}

#[test]
fn transpile_auto_proves_sub_laws() {
    let mut ctx = empty_ctx();
    let sub = FnDef {
        name: "sub".to_string(),
        line: 1,
        params: vec![
            ("a".to_string(), "Int".to_string()),
            ("b".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Sub,
            sbb(Expr::Ident("a".to_string())),
            sbb(Expr::Ident("b".to_string())),
        )))),
        resolution: None,
    };
    ctx.fn_defs.push(sub.clone());
    ctx.items.push(TopLevel::FnDef(sub));

    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "sub".to_string(),
        line: 10,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(2))),
                    sb(Expr::Literal(Literal::Int(0))),
                ],
            )),
            sb(Expr::Literal(Literal::Int(2))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "rightIdentity".to_string(),
            givens: vec![VerifyGiven {
                name: "a".to_string(),
                type_name: "Int".to_string(),
                domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
            }],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::Literal(Literal::Int(0))),
                ],
            )),
            rhs: sb(Expr::Ident("a".to_string())),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "sub".to_string(),
        line: 20,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(2))),
                    sb(Expr::Literal(Literal::Int(1))),
                ],
            )),
            sb(Expr::Neg(sbb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(1))),
                    sb(Expr::Literal(Literal::Int(2))),
                ],
            )))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "antiCommutative".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "a".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
                },
                VerifyGiven {
                    name: "b".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(1)))]),
                },
            ],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::Ident("b".to_string())),
                ],
            )),
            rhs: sb(Expr::Neg(sbb(Expr::FnCall(
                sbb(Expr::Ident("sub".to_string())),
                vec![
                    sb(Expr::Ident("b".to_string())),
                    sb(Expr::Ident("a".to_string())),
                ],
            )))),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem sub_law_rightIdentity : ∀ (a : Int), sub a 0 = a := by"));
    assert!(lean.contains("  simp [sub]"));
    assert!(lean.contains(
        "theorem sub_law_antiCommutative : ∀ (a : Int) (b : Int), sub a b = (-sub b a) := by"
    ));
    assert!(lean.contains("  simpa [sub] using (Int.neg_sub b a).symm"));
}

#[test]
fn transpile_auto_proves_unary_wrapper_equivalence_law() {
    let mut ctx = empty_ctx();
    let add = FnDef {
        name: "add".to_string(),
        line: 1,
        params: vec![
            ("a".to_string(), "Int".to_string()),
            ("b".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Add,
            sbb(Expr::Ident("a".to_string())),
            sbb(Expr::Ident("b".to_string())),
        )))),
        resolution: None,
    };
    let add_one = FnDef {
        name: "addOne".to_string(),
        line: 2,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Add,
            sbb(Expr::Ident("n".to_string())),
            sbb(Expr::Literal(Literal::Int(1))),
        )))),
        resolution: None,
    };
    ctx.fn_defs.push(add.clone());
    ctx.fn_defs.push(add_one.clone());
    ctx.items.push(TopLevel::FnDef(add));
    ctx.items.push(TopLevel::FnDef(add_one));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "addOne".to_string(),
        line: 3,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("addOne".to_string())),
                vec![sb(Expr::Literal(Literal::Int(2)))],
            )),
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(2))),
                    sb(Expr::Literal(Literal::Int(1))),
                ],
            )),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "identityViaAdd".to_string(),
            givens: vec![VerifyGiven {
                name: "n".to_string(),
                type_name: "Int".to_string(),
                domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
            }],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("addOne".to_string())),
                vec![sb(Expr::Ident("n".to_string()))],
            )),
            rhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("n".to_string())),
                    sb(Expr::Literal(Literal::Int(1))),
                ],
            )),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(
        lean.contains("theorem addOne_law_identityViaAdd : ∀ (n : Int), addOne n = add n 1 := by")
    );
    assert!(lean.contains("  simp [addOne, add]"));
}

#[test]
fn transpile_auto_proves_direct_map_set_laws() {
    let mut ctx = empty_ctx();

    // Stub FnDef for the verify target — see analogous note in
    // `transpile_auto_proves_reflexive_law_with_rfl`.
    let map_fn = FnDef {
        name: "map".to_string(),
        line: 1,
        params: vec![],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Literal(Literal::Int(0))))),
        resolution: None,
    };
    ctx.fn_defs.push(map_fn.clone());
    ctx.items.push(TopLevel::FnDef(map_fn));

    let map_set = |m: Spanned<Expr>, k: Spanned<Expr>, v: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "set".to_string(),
            )),
            vec![m, k, v],
        ))
    };
    let map_has = |m: Spanned<Expr>, k: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "has".to_string(),
            )),
            vec![m, k],
        ))
    };
    let map_get = |m: Spanned<Expr>, k: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "get".to_string(),
            )),
            vec![m, k],
        ))
    };
    let some = |v: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Option".to_string())),
                "Some".to_string(),
            )),
            vec![v],
        ))
    };
    let map_empty = || {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "empty".to_string(),
            )),
            vec![],
        ))
    };

    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "map".to_string(),
        line: 1,
        cases: vec![(
            map_has(
                map_set(
                    sb(Expr::Ident("m".to_string())),
                    sb(Expr::Ident("k".to_string())),
                    sb(Expr::Ident("v".to_string())),
                ),
                sb(Expr::Ident("k".to_string())),
            ),
            sb(Expr::Literal(Literal::Bool(true))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "setHasKey".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "m".to_string(),
                    type_name: "Map<String, Int>".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
                },
                VerifyGiven {
                    name: "k".to_string(),
                    type_name: "String".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
                        "a".to_string(),
                    )))]),
                },
                VerifyGiven {
                    name: "v".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(1)))]),
                },
            ],
            when: None,
            lhs: map_has(
                map_set(
                    sb(Expr::Ident("m".to_string())),
                    sb(Expr::Ident("k".to_string())),
                    sb(Expr::Ident("v".to_string())),
                ),
                sb(Expr::Ident("k".to_string())),
            ),
            rhs: sb(Expr::Literal(Literal::Bool(true))),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "map".to_string(),
        line: 2,
        cases: vec![(
            map_get(
                map_set(
                    sb(Expr::Ident("m".to_string())),
                    sb(Expr::Ident("k".to_string())),
                    sb(Expr::Ident("v".to_string())),
                ),
                sb(Expr::Ident("k".to_string())),
            ),
            some(sb(Expr::Ident("v".to_string()))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "setGetKey".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "m".to_string(),
                    type_name: "Map<String, Int>".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
                },
                VerifyGiven {
                    name: "k".to_string(),
                    type_name: "String".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
                        "a".to_string(),
                    )))]),
                },
                VerifyGiven {
                    name: "v".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(1)))]),
                },
            ],
            when: None,
            lhs: map_get(
                map_set(
                    sb(Expr::Ident("m".to_string())),
                    sb(Expr::Ident("k".to_string())),
                    sb(Expr::Ident("v".to_string())),
                ),
                sb(Expr::Ident("k".to_string())),
            ),
            rhs: some(sb(Expr::Ident("v".to_string()))),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("simpa using AverMap.has_set_self m k v"));
    assert!(lean.contains("simpa using AverMap.get_set_self m k v"));
}

#[test]
fn transpile_auto_proves_direct_recursive_sum_law_by_structural_induction() {
    let mut ctx = ctx_from_source(
        r#"
module Mirror
    intent =
        "direct recursive sum induction probe"

type Tree
    Leaf(Int)
    Node(Tree, Tree)

fn mirror(t: Tree) -> Tree
    match t
        Tree.Leaf(v) -> Tree.Leaf(v)
        Tree.Node(left, right) -> Tree.Node(mirror(right), mirror(left))

verify mirror law involutive
    given t: Tree = [Tree.Leaf(1), Tree.Node(Tree.Leaf(1), Tree.Leaf(2))]
    mirror(mirror(t)) => t
"#,
        "mirror",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(
        lean.contains("theorem mirror_law_involutive : ∀ (t : Tree), mirror (mirror t) = t := by")
    );
    assert!(lean.contains("  induction t with"));
    assert!(
        lean.contains(
            "  | leaf f0 => first | (simp [_root_.mirror]; done) | (simp [_root_.mirror]; omega) | sorry"
        )
    );
    assert!(lean.contains(
            "  | node f0 f1 ih0 ih1 => first | (simp_all [_root_.mirror]; done) | (simp_all [_root_.mirror]; omega) | sorry"
        ));
    assert!(!lean.contains(
            "-- universal theorem mirror_law_involutive omitted: sampled law shape is not auto-proved yet"
        ));
}

#[test]
fn transpile_auto_proves_map_update_laws() {
    let mut ctx = empty_ctx();

    let map_get = |m: Spanned<Expr>, k: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "get".to_string(),
            )),
            vec![m, k],
        ))
    };
    let map_set = |m: Spanned<Expr>, k: Spanned<Expr>, v: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "set".to_string(),
            )),
            vec![m, k, v],
        ))
    };
    let map_has = |m: Spanned<Expr>, k: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "has".to_string(),
            )),
            vec![m, k],
        ))
    };
    let option_some = |v: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Option".to_string())),
                "Some".to_string(),
            )),
            vec![v],
        ))
    };
    let option_with_default = |opt: Spanned<Expr>, def: Spanned<Expr>| {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Option".to_string())),
                "withDefault".to_string(),
            )),
            vec![opt, def],
        ))
    };
    let map_empty = || {
        sb(Expr::FnCall(
            sbb(Expr::Attr(
                sbb(Expr::Ident("Map".to_string())),
                "empty".to_string(),
            )),
            vec![],
        ))
    };

    let add_one = FnDef {
        name: "addOne".to_string(),
        line: 1,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Add,
            sbb(Expr::Ident("n".to_string())),
            sbb(Expr::Literal(Literal::Int(1))),
        )))),
        resolution: None,
    };
    ctx.fn_defs.push(add_one.clone());
    ctx.items.push(TopLevel::FnDef(add_one));

    let inc_count = FnDef {
        name: "incCount".to_string(),
        line: 2,
        params: vec![
            ("counts".to_string(), "Map<String, Int>".to_string()),
            ("word".to_string(), "String".to_string()),
        ],
        return_type: "Map<String, Int>".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::Block(vec![
            Stmt::Binding(
                "current".to_string(),
                None,
                map_get(
                    sb(Expr::Ident("counts".to_string())),
                    sb(Expr::Ident("word".to_string())),
                ),
            ),
            Stmt::Expr(sb(Expr::Match {
                subject: sbb(Expr::Ident("current".to_string())),
                arms: vec![
                    MatchArm {
                        pattern: Pattern::Constructor(
                            "Option.Some".to_string(),
                            vec!["n".to_string()],
                        ),
                        body: Box::new(map_set(
                            sb(Expr::Ident("counts".to_string())),
                            sb(Expr::Ident("word".to_string())),
                            sb(Expr::BinOp(
                                BinOp::Add,
                                sbb(Expr::Ident("n".to_string())),
                                sbb(Expr::Literal(Literal::Int(1))),
                            )),
                        )),
                        binding_slots: std::sync::OnceLock::new(),
                    },
                    MatchArm {
                        pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
                        body: Box::new(map_set(
                            sb(Expr::Ident("counts".to_string())),
                            sb(Expr::Ident("word".to_string())),
                            sb(Expr::Literal(Literal::Int(1))),
                        )),
                        binding_slots: std::sync::OnceLock::new(),
                    },
                ],
            })),
        ])),
        resolution: None,
    };
    ctx.fn_defs.push(inc_count.clone());
    ctx.items.push(TopLevel::FnDef(inc_count));

    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "incCount".to_string(),
        line: 10,
        cases: vec![(
            map_has(
                sb(Expr::FnCall(
                    sbb(Expr::Ident("incCount".to_string())),
                    vec![
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Ident("word".to_string())),
                    ],
                )),
                sb(Expr::Ident("word".to_string())),
            ),
            sb(Expr::Literal(Literal::Bool(true))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "keyPresent".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "counts".to_string(),
                    type_name: "Map<String, Int>".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
                },
                VerifyGiven {
                    name: "word".to_string(),
                    type_name: "String".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
                        "a".to_string(),
                    )))]),
                },
            ],
            when: None,
            lhs: map_has(
                sb(Expr::FnCall(
                    sbb(Expr::Ident("incCount".to_string())),
                    vec![
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Ident("word".to_string())),
                    ],
                )),
                sb(Expr::Ident("word".to_string())),
            ),
            rhs: sb(Expr::Literal(Literal::Bool(true))),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "incCount".to_string(),
        line: 20,
        cases: vec![(
            map_get(
                sb(Expr::FnCall(
                    sbb(Expr::Ident("incCount".to_string())),
                    vec![
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Literal(Literal::Str("a".to_string()))),
                    ],
                )),
                sb(Expr::Literal(Literal::Str("a".to_string()))),
            ),
            option_some(sb(Expr::FnCall(
                sbb(Expr::Ident("addOne".to_string())),
                vec![option_with_default(
                    map_get(
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Literal(Literal::Str("a".to_string()))),
                    ),
                    sb(Expr::Literal(Literal::Int(0))),
                )],
            ))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "existingKeyIncrements".to_string(),
            givens: vec![VerifyGiven {
                name: "counts".to_string(),
                type_name: "Map<String, Int>".to_string(),
                domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
            }],
            when: None,
            lhs: map_get(
                sb(Expr::FnCall(
                    sbb(Expr::Ident("incCount".to_string())),
                    vec![
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Literal(Literal::Str("a".to_string()))),
                    ],
                )),
                sb(Expr::Literal(Literal::Str("a".to_string()))),
            ),
            rhs: option_some(sb(Expr::FnCall(
                sbb(Expr::Ident("addOne".to_string())),
                vec![option_with_default(
                    map_get(
                        sb(Expr::Ident("counts".to_string())),
                        sb(Expr::Literal(Literal::Str("a".to_string()))),
                    ),
                    sb(Expr::Literal(Literal::Int(0))),
                )],
            ))),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(
        lean.contains("cases h : AverMap.get counts word <;> simp [AverMap.has_set_self]"),
        "expected keyPresent auto-proof with has_set_self"
    );
    assert!(
        lean.contains(
            "cases h : AverMap.get counts \"a\" <;> simp [AverMap.get_set_self, incCount, addOne]"
        ),
        "expected existingKeyIncrements auto-proof with get_set_self"
    );
}

#[test]
fn transpile_parenthesizes_negative_int_call_args_in_law_samples() {
    let mut ctx = empty_ctx();
    let add = FnDef {
        name: "add".to_string(),
        line: 1,
        params: vec![
            ("a".to_string(), "Int".to_string()),
            ("b".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
            BinOp::Add,
            sbb(Expr::Ident("a".to_string())),
            sbb(Expr::Ident("b".to_string())),
        )))),
        resolution: None,
    };
    ctx.fn_defs.push(add.clone());
    ctx.items.push(TopLevel::FnDef(add));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "add".to_string(),
        line: 1,
        cases: vec![(
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(-2))),
                    sb(Expr::Literal(Literal::Int(-1))),
                ],
            )),
            sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Literal(Literal::Int(-1))),
                    sb(Expr::Literal(Literal::Int(-2))),
                ],
            )),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "commutative".to_string(),
            givens: vec![
                VerifyGiven {
                    name: "a".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(-2)))]),
                },
                VerifyGiven {
                    name: "b".to_string(),
                    type_name: "Int".to_string(),
                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(-1)))]),
                },
            ],
            when: None,
            lhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("a".to_string())),
                    sb(Expr::Ident("b".to_string())),
                ],
            )),
            rhs: sb(Expr::FnCall(
                sbb(Expr::Ident("add".to_string())),
                vec![
                    sb(Expr::Ident("b".to_string())),
                    sb(Expr::Ident("a".to_string())),
                ],
            )),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));

    populate_proof_ir(&mut ctx);
    let out = transpile(&mut ctx);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains(
        "theorem add_law_commutative_sample_1 : add (-2) (-1) = add (-1) (-2) := by native_decide"
    ));
}

#[test]
fn verify_law_numbering_is_scoped_per_law_name() {
    let mut ctx = empty_ctx();
    let f = FnDef {
        name: "f".to_string(),
        line: 1,
        params: vec![("x".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Ident("x".to_string())))),
        resolution: None,
    };
    ctx.fn_defs.push(f.clone());
    ctx.items.push(TopLevel::FnDef(f));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "f".to_string(),
        line: 1,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(1))),
            sb(Expr::Literal(Literal::Int(1))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Cases,
        trace: false,
        cases_givens: vec![],
    }));
    ctx.items.push(TopLevel::Verify(VerifyBlock {
        fn_name: "f".to_string(),
        line: 2,
        cases: vec![(
            sb(Expr::Literal(Literal::Int(2))),
            sb(Expr::Literal(Literal::Int(2))),
        )],
        case_spans: vec![],
        case_givens: vec![],
        case_hostile_origins: vec![],
        case_hostile_profiles: vec![],
        case_reverse_order: vec![],
        kind: VerifyKind::Law(Box::new(VerifyLaw {
            name: "identity".to_string(),
            givens: vec![VerifyGiven {
                name: "x".to_string(),
                type_name: "Int".to_string(),
                domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
            }],
            when: None,
            lhs: sb(Expr::Ident("x".to_string())),
            rhs: sb(Expr::Ident("x".to_string())),
            sample_guards: vec![],
        })),
        trace: false,
        cases_givens: vec![],
    }));
    let out = transpile_with_verify_mode(&mut ctx, VerifyEmitMode::TheoremSkeleton);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
    assert!(lean.contains("theorem f_law_identity : ∀ (x : Int), x = x := by"));
    assert!(lean.contains("theorem f_law_identity_sample_1 : 2 = 2 := by"));
    assert!(!lean.contains("theorem f_law_identity_sample_2 : 2 = 2 := by"));
}

#[test]
fn proof_mode_accepts_single_int_countdown_recursion() {
    let mut ctx = empty_ctx();
    let down = FnDef {
        name: "down".to_string(),
        line: 1,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("n".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Int(0)),
                    body: sbb(Expr::Literal(Literal::Int(0))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "down".to_string(),
                        vec![sb(Expr::BinOp(
                            BinOp::Sub,
                            sbb(Expr::Ident("n".to_string())),
                            sbb(Expr::Literal(Literal::Int(1))),
                        ))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(down.clone()));
    ctx.fn_defs.push(down);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected Int countdown recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    // No `Module` declaration in `ctx.items` ⇒ closed-world by the
    // entry-script rule in `is_closed_world_pure_fn`. No external
    // caller for `down` in this synthetic ctx, so the
    // single-caller-predicate extractor returns empty and the Lean
    // emitter defaults to `(h_dom : n ≥ 0)` — same fallback the
    // legacy fibTR path used. Body has the canonical `match n { 0 ->
    // 0; _ -> down(n-1) }` shape, so we land on the native guarded
    // emit instead of fuel.
    assert!(
        lean.contains("def down__aux (n : Int) (h_dom : n ≥ 0) : Int :="),
        "expected native aux def with default precondition, got:\n{}",
        lean
    );
    assert!(
        lean.contains("else down__aux (n - 1) (by omega)"),
        "expected aux recursive call with omega proof, got:\n{}",
        lean
    );
    assert!(lean.contains("termination_by Int.natAbs n"));
    assert!(lean.contains("def down (n : Int) : Int :="));
    assert!(lean.contains("if h_dom : n ≥ 0 then down__aux n h_dom"));
    assert!(!lean.contains("def down__fuel"));
}

/// Shared module body for the scan-lemma gate probes: `isDigit` is
/// the canonical single-String-param Bool predicate.
const SCAN_GATE_PRELUDE: &str = r#"module ScanGate
    intent = "scan-lemma synthesis gate probes"
    effects []

fn isDigit(c: String) -> Bool
    code = Char.toCode(c)
    match code >= 48
        true -> code <= 57
        false -> false
"#;

fn lean_for_scan_gate(scanner: &str) -> String {
    let source = format!("{SCAN_GATE_PRELUDE}\n{scanner}");
    let mut ctx = ctx_from_source(&source, "scan_gate");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    out.files
        .iter()
        .map(|(_, content)| content.as_str())
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn scan_lemma_emitted_for_canonical_pos_returning_scanner() {
    // Positive control for the gates below: EXIT mentions `pos`, so
    // the `<fn>__fuel_scan` companion is synthesized.
    let lean = lean_for_scan_gate(
        r#"fn scanEnd(s: String, pos: Int) -> Int
    match String.charAt(s, pos)
        Option.None -> pos
        Option.Some(c) -> match isDigit(c)
            true -> scanEnd(s, pos + 1)
            false -> 0 - 1
"#,
    );
    assert!(
        lean.contains("scanEnd__fuel_scan"),
        "expected the scan companion lemma for the canonical shape, got:\n{lean}"
    );
}

#[test]
fn scan_lemma_not_emitted_for_pos_free_exit_scanner() {
    // EXIT without any `pos` occurrence (a constant-exit validator):
    // the lemma template's `rw [hpos]` would have no work to do and
    // FAIL — a build error in the export. The recognizer must
    // decline so nothing is synthesized.
    let lean = lean_for_scan_gate(
        r#"fn scanAll(s: String, pos: Int) -> Bool
    match String.charAt(s, pos)
        Option.None -> true
        Option.Some(c) -> match isDigit(c)
            true -> scanAll(s, pos + 1)
            false -> false
"#,
    );
    assert!(
        !lean.contains("__fuel_scan"),
        "pos-free EXIT must not get a scan lemma, got:\n{lean}"
    );
    assert!(
        lean.contains("def scanAll__fuel"),
        "the scanner itself still gets its fuel emission, got:\n{lean}"
    );
}

#[test]
fn proof_mode_when_stronger_than_refinement_invariant_stays_in_theorem() {
    // Before fix: `when` was dropped unconditionally whenever a
    // given was refinement-lifted, on the assumption that `when`
    // restated the type's invariant. A user-written stronger
    // predicate (`when a >= 10` over `Natural` whose invariant is
    // `a.val >= 0`) would silently disappear from the emitted
    // theorem — the proof artifact would universally quantify
    // over ALL Naturals while the user's source claim was
    // restricted to `a >= 10`. After fix: `when_is_redundant_
    // with_refinement_lifts` compares user's predicate to the
    // type's invariant (via commutator-relaxed compare). Drop
    // only fires when they match.
    let src = "module Stronger\n\
             \x20   intent = \"t\"\n\
             \n\
             record Natural\n\
             \x20   value: Int\n\
             \n\
             fn fromInt(n: Int) -> Result<Natural, String>\n\
             \x20   match n >= 0\n\
             \x20       true  -> Result.Ok(Natural(value = n))\n\
             \x20       false -> Result.Err(\"must be >= 0\")\n\
             \n\
             fn identity(a: Natural) -> Natural\n\
             \x20   a\n\
             \n\
             verify identity law selfEq\n\
             \x20   given a: Int = [10, 20, 30]\n\
             \x20   when a >= 10\n\
             \x20   identity(Natural(value = a)) => identity(Natural(value = a))\n";
    let mut ctx = ctx_from_source(src, "stronger");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    // `when a >= 10` is STRONGER than Natural's `n >= 0` invariant
    // so the universal theorem must keep it as a premise — AND
    // project `a` to `a.val` because the quantifier is now over
    // the Subtype carrier, not the underlying Int. The bare-`a`
    // shape would fail `lake build` with `failed to synthesize LE
    // Natural / OfNat Natural 10`.
    let universal_theorem = lean
        .lines()
        .find(|l| l.contains("theorem identity_law_selfEq"))
        .unwrap_or_else(|| panic!("expected universal theorem line, got:\n{}", lean));
    assert!(
        universal_theorem.contains("a.val >= 10"),
        "expected `when a.val >= 10` (projected) in universal theorem premise, got:\n{}",
        universal_theorem
    );
    assert!(
        !universal_theorem.contains(" a >= 10"),
        "must NOT emit bare `a >= 10` — Subtype carrier has no `LE Natural` instance, got:\n{}",
        universal_theorem
    );
}

#[test]
fn proof_mode_when_compound_equivalent_to_compound_invariant_drops_cleanly() {
    // Regression guard for `examples/refinement/int_range/int_range.av`:
    // the refinement predicate itself is `Bool.and(n >= 0, n <=
    // 100)`. A naive bijective match (lift `[Bool.and(a >= 0, a <=
    // 100), Bool.and(b >= 0, b <= 100)]` against flattened `when`
    // `[a >= 0, a <= 100, b >= 0, b <= 100]`) would length-
    // mismatch and keep the redundant premise — re-introducing
    // the type-mismatch shape that pre-fix already worked around.
    // The fix flattens BOTH sides; this test pins that.
    let src = "module IR\n\
             \x20   intent = \"t\"\n\
             \n\
             record IntRange\n\
             \x20   value: Int\n\
             \n\
             fn fromInt(n: Int) -> Result<IntRange, String>\n\
             \x20   match Bool.and(n >= 0, n <= 100)\n\
             \x20       true  -> Result.Ok(IntRange(value = n))\n\
             \x20       false -> Result.Err(\"oob\")\n\
             \n\
             fn identity(a: IntRange) -> IntRange\n\
             \x20   a\n\
             \n\
             verify identity law selfEq\n\
             \x20   given a: Int = [0, 50, 100]\n\
             \x20   when Bool.and(a >= 0, a <= 100)\n\
             \x20   identity(IntRange(value = a)) => identity(IntRange(value = a))\n";
    let mut ctx = ctx_from_source(src, "ir");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    let universal_theorem = lean
        .lines()
        .find(|l| l.contains("theorem identity_law_selfEq"))
        .unwrap_or_else(|| panic!("expected universal theorem line, got:\n{}", lean));
    assert!(
        !universal_theorem.contains("a >= 0"),
        "expected compound `when` to be dropped when it matches compound invariant, got:\n{}",
        universal_theorem
    );
    assert!(
        !universal_theorem.contains("a <= 100"),
        "expected compound `when` to be dropped when it matches compound invariant, got:\n{}",
        universal_theorem
    );
    assert!(
        universal_theorem.contains("∀ (a : IntRange)"),
        "expected universal to quantify over IntRange, got:\n{}",
        universal_theorem
    );
}

#[test]
fn proof_mode_when_equivalent_to_refinement_invariant_drops_cleanly() {
    // Regression: the typical natural.av-style case — `when a >=
    // 0` over `Natural` (invariant `n >= 0`) — must continue to
    // drop the redundant `when` so the universal theorem is `∀ (a
    // : Natural), ...` not `∀ (a : Natural), a.val >= 0 -> ...`
    // (which Lean type-mismatches against the Subtype carrier).
    let src = "module Equiv\n\
             \x20   intent = \"t\"\n\
             \n\
             record Natural\n\
             \x20   value: Int\n\
             \n\
             fn fromInt(n: Int) -> Result<Natural, String>\n\
             \x20   match n >= 0\n\
             \x20       true  -> Result.Ok(Natural(value = n))\n\
             \x20       false -> Result.Err(\"must be >= 0\")\n\
             \n\
             fn identity(a: Natural) -> Natural\n\
             \x20   a\n\
             \n\
             verify identity law selfEq\n\
             \x20   given a: Int = [0, 1, 2]\n\
             \x20   when a >= 0\n\
             \x20   identity(Natural(value = a)) => identity(Natural(value = a))\n";
    let mut ctx = ctx_from_source(src, "equiv");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    let universal_theorem = lean
        .lines()
        .find(|l| l.contains("theorem identity_law_selfEq"))
        .unwrap_or_else(|| panic!("expected universal theorem line, got:\n{}", lean));
    // Predicate equivalent to invariant → drop.
    assert!(
        !universal_theorem.contains("a >= 0"),
        "expected redundant `when a >= 0` to be dropped from universal theorem, got:\n{}",
        universal_theorem
    );
    assert!(
        universal_theorem.contains("∀ (a : Natural)"),
        "expected universal to quantify over Natural, got:\n{}",
        universal_theorem
    );
}

#[test]
fn proof_mode_non_zero_base_literal_falls_back_to_fuel() {
    // Conservative guard: native IntCountdownGuarded emit assumes
    // the aux's default `(h_dom : p ≥ 0)` precondition, under
    // which only `match p { 0 -> ... }` proves preservation
    // (wildcard arm gives `p ≠ 0`, with `p ≥ 0` that's `p ≥ 1`,
    // so `p - 1 ≥ 0`). A non-zero base literal like `match p { 5
    // -> ... }` would let `p = 0` reach the wildcard arm and
    // recurse with `p - 1 = -1`, breaking the precondition.
    // `omega` would rightly reject it at lake build. Compiler
    // must reject the shape upfront — generalising to arbitrary
    // literals needs a real preservation check that doesn't
    // exist yet (follow-up). Falls back to fuel encoding.
    let src = "module Worker\n\
             \x20   intent = \"t\"\n\
             \n\
             fn worker(n: Int) -> Int\n\
             \x20   match n\n\
             \x20       3 -> n\n\
             \x20       _ -> worker(n - 1)\n\
             \n\
             fn caller(n: Int) -> Int\n\
             \x20   match n > 2\n\
             \x20       true -> match n < 500\n\
             \x20           true -> worker(n)\n\
             \x20           false -> 0\n\
             \x20       false -> 0\n";
    let mut ctx = ctx_from_source(src, "worker");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(
        !lean.contains("worker__aux"),
        "must NOT emit native aux when base literal != 0 — preservation isn't provable without a real linear-int check; got:\n{}",
        lean
    );
    assert!(
        lean.contains("def worker__fuel"),
        "expected fuel fallback for non-zero base literal, got:\n{}",
        lean
    );
}

#[test]
fn proof_mode_exposed_int_countdown_falls_back_to_fuel() {
    // Closed-world check: a fn that lives in a module with an
    // explicit `exposes [...]` listing the fn is open-world, so the
    // native-guarded path is unsafe (callers outside this artifact
    // could pass negative ints). The classifier must keep the fuel
    // encoding for these.
    let src = "module Down\n\
             \x20   intent = \"t\"\n\
             \x20   exposes [down]\n\
             \n\
             fn down(n: Int) -> Int\n\
             \x20   match n\n\
             \x20       0 -> 0\n\
             \x20       _ -> down(n - 1)\n";
    let mut ctx = ctx_from_source(src, "downmod");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(
        lean.contains("def down__fuel"),
        "expected fuel emission for exposed fn, got:\n{}",
        lean
    );
    assert!(
        !lean.contains("down__aux"),
        "should not emit native aux for exposed fn, got:\n{}",
        lean
    );
}

#[test]
fn proof_mode_accepts_single_int_countdown_on_nonfirst_param() {
    let mut ctx = empty_ctx();
    let repeat_like = FnDef {
        name: "repeatLike".to_string(),
        line: 1,
        params: vec![
            ("char".to_string(), "String".to_string()),
            ("n".to_string(), "Int".to_string()),
        ],
        return_type: "List<String>".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::BinOp(
                BinOp::Lte,
                sbb(Expr::Ident("n".to_string())),
                sbb(Expr::Literal(Literal::Int(0))),
            )),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(true)),
                    body: sbb(Expr::List(vec![])),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(false)),
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "repeatLike".to_string(),
                        vec![
                            sb(Expr::Ident("char".to_string())),
                            sb(Expr::BinOp(
                                BinOp::Sub,
                                sbb(Expr::Ident("n".to_string())),
                                sbb(Expr::Literal(Literal::Int(1))),
                            )),
                        ],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(repeat_like.clone()));
    ctx.fn_defs.push(repeat_like);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected non-first Int countdown recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("def repeatLike__fuel"));
    assert!(lean.contains("def repeatLike (char : String) (n : Int) : List String :="));
    assert!(lean.contains("repeatLike__fuel ((Int.natAbs n) + 1) char n"));
}

#[test]
fn proof_mode_accepts_negative_guarded_int_ascent() {
    let mut ctx = empty_ctx();
    let normalize = FnDef {
        name: "normalize".to_string(),
        line: 1,
        params: vec![("angle".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::BinOp(
                BinOp::Lt,
                sbb(Expr::Ident("angle".to_string())),
                sbb(Expr::Literal(Literal::Int(0))),
            )),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(true)),
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "normalize".to_string(),
                        vec![sb(Expr::BinOp(
                            BinOp::Add,
                            sbb(Expr::Ident("angle".to_string())),
                            sbb(Expr::Literal(Literal::Int(360))),
                        ))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(false)),
                    body: sbb(Expr::Ident("angle".to_string())),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(normalize.clone()));
    ctx.fn_defs.push(normalize);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected negative-guarded Int ascent recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = out
        .files
        .iter()
        .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
        .expect("expected generated Lean file");
    assert!(lean.contains("def normalize__fuel"));
    assert!(lean.contains("normalize__fuel ((Int.natAbs angle) + 1) angle"));
}

#[test]
fn proof_mode_accepts_single_list_structural_recursion() {
    let mut ctx = empty_ctx();
    let len = FnDef {
        name: "len".to_string(),
        line: 1,
        params: vec![("xs".to_string(), "List<Int>".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("xs".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::EmptyList,
                    body: sbb(Expr::Literal(Literal::Int(0))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Cons("h".to_string(), "t".to_string()),
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "len".to_string(),
                        vec![sb(Expr::Ident("t".to_string()))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(len.clone()));
    ctx.fn_defs.push(len);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected List structural recursion to be accepted, got: {:?}",
        issues
    );
}

#[test]
fn proof_mode_accepts_single_list_structural_recursion_on_nonfirst_param() {
    let mut ctx = empty_ctx();
    let len_from = FnDef {
        name: "lenFrom".to_string(),
        line: 1,
        params: vec![
            ("count".to_string(), "Int".to_string()),
            ("xs".to_string(), "List<Int>".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("xs".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::EmptyList,
                    body: sbb(Expr::Ident("count".to_string())),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Cons("h".to_string(), "t".to_string()),
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "lenFrom".to_string(),
                        vec![
                            sb(Expr::BinOp(
                                BinOp::Add,
                                sbb(Expr::Ident("count".to_string())),
                                sbb(Expr::Literal(Literal::Int(1))),
                            )),
                            sb(Expr::Ident("t".to_string())),
                        ],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(len_from.clone()));
    ctx.fn_defs.push(len_from);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected non-first List structural recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("termination_by xs.length"));
    assert!(!lean.contains("partial def lenFrom"));
}

#[test]
fn proof_mode_accepts_single_string_pos_advance_recursion() {
    let mut ctx = empty_ctx();
    let skip_ws = FnDef {
        name: "skipWs".to_string(),
        line: 1,
        params: vec![
            ("s".to_string(), "String".to_string()),
            ("pos".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::FnCall(
                sbb(Expr::Attr(
                    sbb(Expr::Ident("String".to_string())),
                    "charAt".to_string(),
                )),
                vec![
                    sb(Expr::Ident("s".to_string())),
                    sb(Expr::Ident("pos".to_string())),
                ],
            )),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
                    body: sbb(Expr::Ident("pos".to_string())),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "skipWs".to_string(),
                        vec![
                            sb(Expr::Ident("s".to_string())),
                            sb(Expr::BinOp(
                                BinOp::Add,
                                sbb(Expr::Ident("pos".to_string())),
                                sbb(Expr::Literal(Literal::Int(1))),
                            )),
                        ],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(skip_ws.clone()));
    ctx.fn_defs.push(skip_ws);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected String+pos recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("def skipWs__fuel"));
    assert!(!lean.contains("partial def skipWs"));
}

#[test]
fn proof_mode_graduates_simple_string_pos_skipper_to_native() {
    // The simple string-position SKIP shape (skipWs family) graduates to a
    // native fuel-free `def` with a `termination_by` measure, so Lean derives
    // a real `.induct`. This SUBSUMES the #643 single-fn fuel-stability lemma:
    // the graduated shape has no `__fuel` wrapper and no `_stable` lemma
    // (native `.induct` is strictly stronger). The stability-lemma emission
    // path is now unreachable for single fns — see the `walk`-shape decline
    // test below, which pins that a NON-skip string-position fn stays fueled.
    let source = r#"module FuelStable
    intent = "simple string-position graduation"
    effects []

fn skipSpaces(s: String, pos: Int) -> Int
    match String.charAt(s, pos)
        Option.None -> pos
        Option.Some(c) -> match c
            " " -> skipSpaces(s, pos + 1)
            _ -> pos
"#;
    let mut ctx = ctx_from_source(source, "fuel_stable");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(
        lean.contains("def skipSpaces (s : String) (pos : Int) : Int :="),
        "expected native fuel-free skipSpaces def:\n{lean}"
    );
    assert!(
        lean.contains("termination_by (s.toList.length - pos.toNat)"),
        "expected the StringLenMinusPos measure as termination_by:\n{lean}"
    );
    assert!(
        lean.contains("String.charAt_some_bounds"),
        "decreasing_by must cite the prelude bounds lemma:\n{lean}"
    );
    assert!(
        !lean.contains("def skipSpaces__fuel"),
        "graduated skipper must NOT emit a fuel wrapper:\n{lean}"
    );
    assert!(
        !lean.contains("skipSpaces__fuel_stable"),
        "graduated skipper must NOT emit the fuel-stability lemma (subsumed by native):\n{lean}"
    );
}

#[test]
fn proof_mode_declines_stability_lemma_for_non_skip_string_pos_shape() {
    let source = r#"module FuelStableDecline
    intent = "string-position recursion outside the stability shape"
    effects []

fn walk(s: String, pos: Int) -> Int
    match String.charAt(s, pos)
        Option.None -> pos
        Option.Some(_) -> walk(s, pos + 1)
"#;
    let mut ctx = ctx_from_source(source, "fuel_stable_decline");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("def walk__fuel"));
    assert!(
        !lean.contains("walk__fuel_stable"),
        "out-of-shape string-position recursion must not get an unprobed stability lemma:\n{lean}"
    );
}

#[test]
fn proof_mode_declines_graduation_for_non_unit_advance_arm() {
    // FAIL-CLOSED graduation: a skip scanner whose inner char-match mixes the
    // exact `self(s, pos + 1)` advance with a NON-unit `self(s, pos + 2)` arm
    // must stay FUELED, not graduate — a native `def` cannot sorry-floor a
    // `decreasing_by`, so a step shape the recognizer cannot affirmatively
    // classify must never reach native emission. The upstream StringPosAdvance
    // classifier admits `pos + k` for any k >= 1, so this shape reaches the
    // gate; before the fix the `pos + 2` arm fell through the detector's
    // `_ => {}` and the sibling `pos + 1` arm graduated the whole fn. A fuel
    // wrapper always builds.
    let source = r#"module NonUnitAdvance
    intent = "mixed advance skip scanner"
    effects []

fn skipMixed(s: String, pos: Int) -> Int
    match String.charAt(s, pos)
        Option.None -> pos
        Option.Some(c) -> match c
            " " -> skipMixed(s, pos + 1)
            "x" -> skipMixed(s, pos + 2)
            _ -> pos
"#;
    let mut ctx = ctx_from_source(source, "non_unit_advance");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(
        lean.contains("def skipMixed__fuel"),
        "the mixed-advance scanner must stay fueled:\n{lean}"
    );
    assert!(
        !lean.contains("String.charAt_some_bounds")
            && !lean.contains("termination_by (s.toList.length - pos.toNat)"),
        "the mixed-advance scanner must NOT graduate to a native def:\n{lean}"
    );
}

#[test]
fn graduation_gate_declines_unclassifiable_arms() {
    // Direct fail-closed net on the graduation recognizer. The upstream
    // classifier rejects some of these shapes to `partial def`, so the gate
    // is exercised in isolation: a self-call arm that is NOT the exact
    // `self(s, pos + 1)` advance, or an outer arm that is not the exact
    // charAt none/some pair, must make `detect_simple_string_pos_skip_literal`
    // decline — anything it accepts is emitted as a native `def` whose
    // `decreasing_by` cannot be sorry-floored.
    use crate::codegen::lean::toplevel::fuel::detect_simple_string_pos_skip_literal;
    fn fd_named<'a>(ctx: &'a CodegenContext, name: &str) -> &'a FnDef {
        ctx.fn_defs
            .iter()
            .find(|fd| fd.name == name)
            .unwrap_or_else(|| panic!("fn {name} not found"))
    }

    // Positive control: the canonical uniform `pos + 1` skip shape graduates.
    let good = ctx_from_source(
        "module GateGood\n    effects []\n\n\
         fn skipWs(s: String, pos: Int) -> Int\n    match String.charAt(s, pos)\n        Option.None -> pos\n        Option.Some(c) -> match c\n            \" \" -> skipWs(s, pos + 1)\n            _ -> pos\n",
        "gate_good",
    );
    assert!(
        detect_simple_string_pos_skip_literal(fd_named(&good, "skipWs")).is_some(),
        "the canonical uniform pos+1 skipper must still be recognized"
    );

    // BLOCKER 1 (:691): a non-advancing `self(s, pos)` arm alongside a real
    // `self(s, pos + 1)` arm — `decreasing_by` would fail on the non-advancing
    // call, so decline.
    let non_adv = ctx_from_source(
        "module GateNonAdv\n    effects []\n\n\
         fn skipMixed(s: String, pos: Int) -> Int\n    match String.charAt(s, pos)\n        Option.None -> pos\n        Option.Some(c) -> match c\n            \" \" -> skipMixed(s, pos + 1)\n            \"x\" -> skipMixed(s, pos)\n            _ -> pos\n",
        "gate_non_adv",
    );
    assert!(
        detect_simple_string_pos_skip_literal(fd_named(&non_adv, "skipMixed")).is_none(),
        "a non-advancing self-call arm must decline graduation"
    );

    // BLOCKER 1 (:691): the advance routed through a helper `self(s, bump(pos))`
    // — an opaque step `decreasing_by` cannot discharge, so decline.
    let helper = ctx_from_source(
        "module GateHelper\n    effects []\n\n\
         fn bump(pos: Int) -> Int\n    pos + 1\n\n\
         fn skipMixed(s: String, pos: Int) -> Int\n    match String.charAt(s, pos)\n        Option.None -> pos\n        Option.Some(c) -> match c\n            \" \" -> skipMixed(s, pos + 1)\n            \"x\" -> skipMixed(s, bump(pos))\n            _ -> pos\n",
        "gate_helper",
    );
    assert!(
        detect_simple_string_pos_skip_literal(fd_named(&helper, "skipMixed")).is_none(),
        "a helper-routed advance arm must decline graduation"
    );

    // BLOCKER 2 (:621): an outer catch-all `_` on the charAt Option. The native
    // emitter cannot name a `= some c` discriminant off a wildcard, so a
    // graduated def would hard-error — the outer match must be exactly the
    // none/some pair.
    let outer_wild = ctx_from_source(
        "module GateOuterWild\n    effects []\n\n\
         fn skipR(s: String, pos: Int) -> Int\n    match String.charAt(s, pos)\n        Option.None -> pos\n        Option.Some(c) -> match c\n            \" \" -> skipR(s, pos + 1)\n            _ -> pos\n        _ -> pos\n",
        "gate_outer_wild",
    );
    assert!(
        detect_simple_string_pos_skip_literal(fd_named(&outer_wild, "skipR")).is_none(),
        "an outer wildcard on the charAt Option must decline graduation"
    );
}

#[test]
fn proof_mode_accepts_mutual_int_countdown_recursion() {
    let mut ctx = empty_ctx();
    let even = FnDef {
        name: "even".to_string(),
        line: 1,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Bool".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("n".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Int(0)),
                    body: sbb(Expr::Literal(Literal::Bool(true))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "odd".to_string(),
                        vec![sb(Expr::BinOp(
                            BinOp::Sub,
                            sbb(Expr::Ident("n".to_string())),
                            sbb(Expr::Literal(Literal::Int(1))),
                        ))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    let odd = FnDef {
        name: "odd".to_string(),
        line: 2,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Bool".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("n".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Int(0)),
                    body: sbb(Expr::Literal(Literal::Bool(false))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "even".to_string(),
                        vec![sb(Expr::BinOp(
                            BinOp::Sub,
                            sbb(Expr::Ident("n".to_string())),
                            sbb(Expr::Literal(Literal::Int(1))),
                        ))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(even.clone()));
    ctx.items.push(TopLevel::FnDef(odd.clone()));
    ctx.fn_defs.push(even);
    ctx.fn_defs.push(odd);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected mutual Int countdown recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("def even__fuel"));
    assert!(lean.contains("def odd__fuel"));
    assert!(lean.contains("def even (n : Int) : Bool :="));
    assert!(lean.contains("even__fuel ((Int.natAbs n) + 1) n"));
}

#[test]
fn proof_mode_accepts_mutual_string_pos_recursion_with_ranked_same_edges() {
    let mut ctx = empty_ctx();
    let f = FnDef {
        name: "f".to_string(),
        line: 1,
        params: vec![
            ("s".to_string(), "String".to_string()),
            ("pos".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::BinOp(
                BinOp::Gte,
                sbb(Expr::Ident("pos".to_string())),
                sbb(Expr::Literal(Literal::Int(3))),
            )),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(true)),
                    body: sbb(Expr::Ident("pos".to_string())),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "g".to_string(),
                        vec![
                            sb(Expr::Ident("s".to_string())),
                            sb(Expr::Ident("pos".to_string())),
                        ],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    let g = FnDef {
        name: "g".to_string(),
        line: 2,
        params: vec![
            ("s".to_string(), "String".to_string()),
            ("pos".to_string(), "Int".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::BinOp(
                BinOp::Gte,
                sbb(Expr::Ident("pos".to_string())),
                sbb(Expr::Literal(Literal::Int(3))),
            )),
            arms: vec![
                MatchArm {
                    pattern: Pattern::Literal(Literal::Bool(true)),
                    body: sbb(Expr::Ident("pos".to_string())),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Wildcard,
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "f".to_string(),
                        vec![
                            sb(Expr::Ident("s".to_string())),
                            sb(Expr::BinOp(
                                BinOp::Add,
                                sbb(Expr::Ident("pos".to_string())),
                                sbb(Expr::Literal(Literal::Int(1))),
                            )),
                        ],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(f.clone()));
    ctx.items.push(TopLevel::FnDef(g.clone()));
    ctx.fn_defs.push(f);
    ctx.fn_defs.push(g);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected mutual String+pos recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("def f__fuel"));
    assert!(lean.contains("def g__fuel"));
    assert!(!lean.contains("partial def f"));
}

#[test]
fn proof_mode_accepts_mutual_ranked_sizeof_recursion() {
    let mut ctx = empty_ctx();
    let f = FnDef {
        name: "f".to_string(),
        line: 1,
        params: vec![("xs".to_string(), "List<Int>".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::TailCall(Box::new(
            TailCallData::new(
                "g".to_string(),
                vec![
                    sb(Expr::Literal(Literal::Str("acc".to_string()))),
                    sb(Expr::Ident("xs".to_string())),
                ],
            ),
        ))))),
        resolution: None,
    };
    let g = FnDef {
        name: "g".to_string(),
        line: 2,
        params: vec![
            ("acc".to_string(), "String".to_string()),
            ("xs".to_string(), "List<Int>".to_string()),
        ],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::Match {
            subject: sbb(Expr::Ident("xs".to_string())),
            arms: vec![
                MatchArm {
                    pattern: Pattern::EmptyList,
                    body: sbb(Expr::Literal(Literal::Int(0))),
                    binding_slots: std::sync::OnceLock::new(),
                },
                MatchArm {
                    pattern: Pattern::Cons("h".to_string(), "t".to_string()),
                    body: sbb(Expr::TailCall(Box::new(TailCallData::new(
                        "f".to_string(),
                        vec![sb(Expr::Ident("t".to_string()))],
                    )))),
                    binding_slots: std::sync::OnceLock::new(),
                },
            ],
        }))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(f.clone()));
    ctx.items.push(TopLevel::FnDef(g.clone()));
    ctx.fn_defs.push(f);
    ctx.fn_defs.push(g);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected mutual ranked-sizeOf recursion to be accepted, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    // After the native-decreases path landed for mutual sizeOf
    // SCCs (PR #84), this group emits as a plain `mutual ...
    // end` block with `termination_by` instead of the older
    // `__fuel` helper-and-wrapper pair. The classifier still
    // recognises the recursion (no proof-mode issues raised),
    // which is what this test pins.
    assert!(lean.contains("mutual"));
    assert!(lean.contains("def f"));
    assert!(lean.contains("def g"));
    assert!(lean.contains("termination_by"));
    assert!(!lean.contains("partial def f"));
    assert!(!lean.contains("partial def g"));
}

#[test]
fn proof_mode_rejects_recursive_pure_functions() {
    let mut ctx = empty_ctx();
    let recursive_fn = FnDef {
        name: "loop".to_string(),
        line: 1,
        params: vec![("n".to_string(), "Int".to_string())],
        return_type: "Int".to_string(),
        effects: vec![],
        desc: None,
        body: Rc::new(FnBody::from_expr(sb(Expr::FnCall(
            sbb(Expr::Ident("loop".to_string())),
            vec![sb(Expr::Ident("n".to_string()))],
        )))),
        resolution: None,
    };
    ctx.items.push(TopLevel::FnDef(recursive_fn.clone()));
    ctx.fn_defs.push(recursive_fn);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.iter().any(|i| i.contains("outside proof subset")),
        "expected recursive function blocker, got: {:?}",
        issues
    );
}

#[test]
fn proof_mode_allows_recursive_types() {
    let mut ctx = empty_ctx();
    let recursive_type = TypeDef::Sum {
        name: "Node".to_string(),
        variants: vec![TypeVariant {
            name: "Cons".to_string(),
            fields: vec!["Node".to_string()],
        }],
        line: 1,
    };
    ctx.items.push(TopLevel::TypeDef(recursive_type.clone()));
    ctx.type_defs.push(recursive_type);

    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues
            .iter()
            .all(|i| !i.contains("recursive types require unsafe DecidableEq shim")),
        "did not expect recursive type blocker, got: {:?}",
        issues
    );
}

#[test]
fn law_auto_example_exports_real_proof_artifacts() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/formal/law_auto.av"),
        "law_auto",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("theorem add_law_commutative :"));
    assert!(lean.contains("theorem id'_law_reflexive : ∀ (x : Int), x = x := by"));
    assert!(lean.contains("theorem incCount_law_keyPresent :"));
    assert!(lean.contains("AverMap.has_set_self"));
    assert!(lean.contains("theorem add_law_commutative_sample_1 :"));
    assert!(lean.contains(":= by native_decide"));
}

#[test]
fn json_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected json example to stay inside proof subset, got: {:?}",
        issues
    );
}

#[test]
fn json_example_uses_total_defs_and_domain_guarded_laws_in_proof_mode() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(!lean.contains("partial def"));
    // skipWs is a single simple-skip scanner: it graduates to a native
    // fuel-free `def` with a `termination_by` measure (real `.induct`).
    assert!(lean.contains("def skipWs (s : String) (pos : Int) : Int :="));
    assert!(lean.contains("termination_by (s.toList.length - pos.toNat)"));
    assert!(!lean.contains("def skipWs__fuel"));
    // parseValue sits in a mutual parser clique — mutual groups stay fueled.
    assert!(lean.contains("def parseValue__fuel"));
    assert!(lean.contains("def toString' (j : Json) : String :="));
    assert!(
        lean.contains("def averMeasureJsonEntries_String (items : List (String × Json)) : Nat :=")
    );
    assert!(
        lean.contains(
            "| .jsonObject x0 => (averMeasureJsonEntries_String (AverMap.entries x0)) + 1"
        )
    );
    assert!(lean.contains("-- when jsonRoundtripSafe j"));
    assert!(!lean.contains("-- hint: verify law '"));
    assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
    assert!(
        lean.contains("theorem toString'_law_parseRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨")
    );
    assert!(
        lean.contains("jsonRoundtripSafe j = true -> fromString (toString' j) = Except.ok j := by")
    );
    assert!(lean.contains("theorem finishFloat_law_fromCanonicalFloat : ∀ (f : Float), f = 3.5 ∨"));
    assert!(lean.contains("theorem finishInt_law_fromCanonicalInt_checked_domain :"));
    assert!(
        lean.contains(
            "theorem toString'_law_parseValueRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨"
        )
    );
    assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
    assert!(
        lean.contains(
            "example : fromString \"null\" = Except.ok Json.jsonNull := by native_decide"
        )
    );
}

#[test]
fn transpile_injects_builtin_network_types_and_vector_get_support() {
    let mut ctx = ctx_from_source(
        r#"
fn firstOrMissing(xs: Vector<String>) -> Result<String, String>
    Option.toResult(Vector.get(xs, 0), "missing")

fn defaultHeaders() -> Map<String, List<String>>
    {"content-type" => ["application/json"]}

fn mkResponse(body: String) -> HttpResponse
    HttpResponse(status = 200, body = body, headers = defaultHeaders())

fn requestPath(req: HttpRequest) -> String
    req.path

fn echoConn(conn: Tcp.Connection) -> Tcp.Connection
    conn
"#,
        "network_helpers",
    );
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("structure HttpResponse where"));
    assert!(lean.contains("structure HttpRequest where"));
    // `Tcp.Connection` is opaque from the surface (Phase 4.7+
    // fix #11), but the Lean prelude still ships its struct
    // so functions that take/return `Tcp.Connection` typecheck.
    assert!(lean.contains("structure Tcp_Connection where"));
    assert!(lean.contains("port : Int"));
    // Headers field renders as the Map shape (Lean uses List of pairs).
    assert!(lean.contains("List (String × List String)"));
}

#[test]
fn law_auto_example_has_no_sorry_in_proof_mode() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/formal/law_auto.av"),
        "law_auto",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(
        !lean.contains("sorry"),
        "expected law_auto proof export to avoid sorry, got:\n{}",
        lean
    );
}

#[test]
fn map_example_has_no_sorry_in_proof_mode() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/data/map.av"), "map");
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected map example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    // After codegen change: universal theorems that can't be auto-proved get sorry
    assert!(lean.contains("theorem incCount_law_trackedCountStepsByOne :"));
    assert!(lean.contains("sorry"));
    // Universal theorems that can't be auto-proved now get sorry instead of being omitted
    assert!(lean.contains("theorem countWords_law_presenceMatchesContains_sample_1 :"));
    assert!(lean.contains("theorem countWords_law_trackedWordCount_sample_1 :"));
    assert!(lean.contains("AverMap.has_set_self"));
    assert!(lean.contains("AverMap.get_set_self"));
}

#[test]
fn spec_laws_example_has_no_sorry_in_proof_mode() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/formal/spec_laws.av"),
        "spec_laws",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected spec_laws example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(
        !lean.contains("sorry"),
        "expected spec_laws proof export to avoid sorry, got:\n{}",
        lean
    );
    assert!(lean.contains("theorem absVal_eq_absValSpec :"));
    assert!(lean.contains("theorem clampNonNegative_eq_clampNonNegativeSpec :"));
}

#[test]
fn rle_example_exports_sampled_roundtrip_laws_without_sorry() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/data/rle.av"), "rle");
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(
        lean.contains("sorry"),
        "expected rle proof export to contain sorry for unproved universal theorems"
    );
    assert!(lean.contains(
        "theorem encode_law_roundtrip_sample_1 : decode (encode []) = [] := by native_decide"
    ));
    assert!(lean.contains(
            "theorem encodeString_law_string_roundtrip_sample_1 : decodeString (encodeString \"\") = \"\" := by native_decide"
        ));
}

#[test]
fn fibonacci_example_uses_native_guarded_int_countdown_in_proof_mode() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/data/fibonacci.av"),
        "fibonacci",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    // Native guarded emission: an aux fn with the precondition
    // derived from `fib`'s `match (n < 0) { false -> fibTR(n,...) }`
    // arm (flipped to positive form `n >= 0` at extract time) +
    // termination on `n.natAbs`, plus a thin wrapper preserving the
    // source signature. Replaces the historical `def fibTR__fuel`
    // path so Lean can `simp`/`decide` through recursive calls
    // instead of treating the helper as opaque.
    assert!(
        lean.contains("def fibTR__aux (n : Int) (a : Int) (b : Int) (h_dom : ((n >= 0))) : Int :="),
        "expected fibTR aux with caller-derived precondition, got:\n{}",
        lean
    );
    assert!(
        lean.contains("if h_zero : n = 0 then a"),
        "expected dependent-if on literal 0, got:\n{}",
        lean
    );
    assert!(
        lean.contains("else fibTR__aux (n - 1) b (a + b) (by omega)"),
        "expected recursive call carrying (by omega), got:\n{}",
        lean
    );
    assert!(lean.contains("termination_by Int.natAbs n"));
    assert!(lean.contains("def fibTR (n : Int) (a : Int) (b : Int) : Int :="));
    assert!(lean.contains("if h_dom : ((n >= 0)) then fibTR__aux n a b h_dom"));
    assert!(!lean.contains("def fibTR__fuel"));
    assert!(!lean.contains("partial def fibTR"));
}

#[test]
fn fibonacci_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/data/fibonacci.av"),
        "fibonacci",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected fibonacci example to stay inside proof subset, got: {:?}",
        issues
    );
}

#[test]
fn fibonacci_example_matches_general_linear_recurrence_shapes() {
    let ctx = ctx_from_source(
        include_str!("../../../examples/data/fibonacci.av"),
        "fibonacci",
    );
    let fib = ctx.fn_defs.iter().find(|fd| fd.name == "fib").unwrap();
    let fib_tr = ctx.fn_defs.iter().find(|fd| fd.name == "fibTR").unwrap();
    let fib_spec = ctx.fn_defs.iter().find(|fd| fd.name == "fibSpec").unwrap();

    assert!(recurrence::detect_tailrec_int_linear_pair_wrapper(fib).is_some());
    assert!(recurrence::detect_tailrec_int_linear_pair_worker(fib_tr).is_some());
    assert!(recurrence::detect_second_order_int_linear_recurrence(fib_spec).is_some());
}

#[test]
fn fibonacci_example_auto_proves_general_linear_recurrence_spec_law() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/data/fibonacci.av"),
        "fibonacci",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    assert!(lean.contains("private def fibSpec__nat : Nat -> Int"));
    assert!(!lean.contains("partial def fibSpec"));
    assert!(lean.contains("private theorem fib_eq_fibSpec__worker_nat_shift"));
    assert!(lean.contains("private theorem fib_eq_fibSpec__helper_nat"));
    assert!(lean.contains("private theorem fib_eq_fibSpec__helper_seed"));
    assert!(lean.contains("theorem fib_eq_fibSpec : ∀ (n : Int), fib n = fibSpec n := by"));
    assert!(!lean.contains(
        "-- universal theorem fib_eq_fibSpec omitted: sampled law shape is not auto-proved yet"
    ));
}

#[test]
fn pell_like_example_auto_proves_same_general_shape() {
    let mut ctx = ctx_from_source(
        r#"
module Pell
    intent =
        "linear recurrence probe"

fn pellTR(n: Int, a: Int, b: Int) -> Int
    match n
        0 -> a
        _ -> pellTR(n - 1, b, a + 2 * b)

fn pell(n: Int) -> Int
    match n < 0
        true -> 0
        false -> pellTR(n, 0, 1)

fn pellSpec(n: Int) -> Int
    match n < 0
        true -> 0
        false -> match n
            0 -> 0
            1 -> 1
            _ -> pellSpec(n - 2) + 2 * pellSpec(n - 1)

verify pell law pellSpec
    given n: Int = [0, 1, 2, 3]
    pell(n) => pellSpec(n)
"#,
        "pell",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected pell example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("private def pellSpec__nat : Nat -> Int"));
    assert!(lean.contains("private theorem pell_eq_pellSpec__worker_nat_shift"));
    assert!(lean.contains("theorem pell_eq_pellSpec : ∀ (n : Int), pell n = pellSpec n := by"));
    assert!(!lean.contains(
        "-- universal theorem pell_eq_pellSpec omitted: sampled law shape is not auto-proved yet"
    ));
}

#[test]
fn nonlinear_pair_state_recurrence_is_not_auto_proved_as_linear_shape() {
    let mut ctx = ctx_from_source(
        r#"
module WeirdRec
    intent =
        "reject nonlinear pair-state recurrence from linear recurrence prover"

fn weirdTR(n: Int, a: Int, b: Int) -> Int
    match n
        0 -> a
        _ -> weirdTR(n - 1, b, a * b)

fn weird(n: Int) -> Int
    match n < 0
        true -> 0
        false -> weirdTR(n, 0, 1)

fn weirdSpec(n: Int) -> Int
    match n < 0
        true -> 0
        false -> match n
            0 -> 0
            1 -> 1
            _ -> weirdSpec(n - 1) * weirdSpec(n - 2)

verify weird law weirdSpec
    given n: Int = [0, 1, 2, 3]
    weird(n) => weirdSpec(n)
"#,
        "weirdrec",
    );
    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);

    // After codegen change: emit sorry instead of omitting universal theorems
    assert!(lean.contains("sorry"));
    assert!(!lean.contains("private theorem weird_eq_weirdSpec__worker_nat_shift"));
    assert!(lean.contains("theorem weird_eq_weirdSpec_sample_1 :"));
}

#[test]
fn date_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/data/date.av"), "date");
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected date example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(!lean.contains("partial def"));
    assert!(lean.contains("def parseIntSlice (s : String) (from' : Int) (to : Int) : Int :="));
}

#[test]
fn temperature_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/core/temperature.av"),
        "temperature",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected temperature example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(!lean.contains("partial def"));
    assert!(
        lean.contains("example : celsiusToFahr 0.0 = 32.0 := by native_decide"),
        "expected verify examples to survive proof export, got:\n{}",
        lean
    );
}

#[test]
fn quicksort_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/data/quicksort.av"),
        "quicksort",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected quicksort example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("def isOrderedFrom"));
    assert!(!lean.contains("partial def isOrderedFrom"));
    assert!(lean.contains("termination_by xs.length"));
}

#[test]
fn grok_s_language_example_uses_total_ranked_sizeof_mutual_recursion() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/core/grok_s_language.av"),
        "grok_s_language",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected grok_s_language example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("mutual"));
    assert!(lean.contains("def parseListItems__fuel"));
    assert!(!lean.contains("partial def eval"));
    // The `eval` SCC stays FUEL: it has MULTI-`Sexpr`-carrier members
    // (`evalOpWithPair(_, leftExpr: Sexpr, rightExpr: Sexpr, _)`). Multi-carrier
    // ADT sum measures are native-closable for some shapes but not all (a
    // red-black-tree SCC's `decreasing_by` fails), so multi-carrier ADT stays
    // on fuel — only SINGLE-carrier structural ADT goes native.
    assert!(lean.contains("def eval__fuel"));
    assert!(lean.contains("def evalOpWithPair__fuel"));
    // The SINGLE-carrier structural `Sexpr` fns (`toString'`, `validSymbolNames`)
    // DO emit native `termination_by (sizeOf e, _)` now (no fuel) — structural
    // recursion on the ADT, Lean's own termination check accepts it.
    assert!(lean.contains("termination_by (sizeOf e,"));
    assert!(!lean.contains("def toString'__fuel"));
    assert!(lean.contains("-- when validSymbolNames e"));
    assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
    assert!(
        lean.contains(
            "theorem toString'_law_parseRoundtrip : ∀ (e : Sexpr), e = Sexpr.atomNum 42 ∨"
        )
    );
    assert!(lean.contains("validSymbolNames e = true -> parse (toString' e) = Except.ok e := by"));
    assert!(lean.contains("theorem toString'_law_parseSexprRoundtrip :"));
    assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
}

#[test]
fn lambda_example_keeps_only_eval_outside_proof_subset() {
    let mut ctx = ctx_from_source(include_str!("../../../examples/core/lambda.av"), "lambda");
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert_eq!(
            issues,
            vec!["recursive function 'eval' is outside proof subset (currently supported: Int countdown, guard-validated Int floor-division countdown by a literal divisor, second-order affine Int recurrences with pair-state worker, structural recursion on List/recursive ADTs, String+position, mutual Int countdown, mutual String+position, and ranked sizeOf recursion)".to_string()]
        );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    // termToString / subst / countS recurse structurally on the `Term`
    // ADT, so they emit as plain structural defs (Lean infers termination,
    // definitional unfolds) — the fuel retirement for SizeOfStructural. No
    // `__fuel` helper. `eval` stays outside the proof subset (`partial def`);
    // step/stepApp remain a mutual-fuel SCC (computed-arg recursion).
    assert!(lean.contains("def termToString (t : Term)"));
    assert!(lean.contains("def subst (x : String) (s : Term) (t : Term)"));
    assert!(lean.contains("def countS (t : Term)"));
    assert!(!lean.contains("def termToString__fuel"));
    assert!(!lean.contains("def subst__fuel"));
    assert!(!lean.contains("def countS__fuel"));
    assert!(!lean.contains("partial def termToString"));
    assert!(!lean.contains("partial def subst"));
    assert!(!lean.contains("partial def countS"));
    assert!(lean.contains("partial def eval"));
}

#[test]
fn mission_control_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/apps/mission_control.av"),
        "mission_control",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected mission_control example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(!lean.contains("partial def normalizeAngle"));
    assert!(lean.contains("def normalizeAngle__fuel"));
}

#[test]
fn notepad_store_example_stays_inside_proof_subset() {
    let mut ctx = ctx_from_source(
        include_str!("../../../examples/apps/notepad/store.av"),
        "notepad_store",
    );
    ctx.refresh_facts();
    let issues = proof_mode_issues(&ctx);
    assert!(
        issues.is_empty(),
        "expected notepad/store example to stay inside proof subset, got: {:?}",
        issues
    );

    let out = transpile_for_proof_mode(&mut ctx, VerifyEmitMode::NativeDecide);
    let lean = generated_lean_file(&out);
    assert!(lean.contains("def deserializeLine (line : String) : Except String Note :="));
    assert!(lean.contains("Except String (List Note)"));
    assert!(!lean.contains("partial def deserializeLine"));
    assert!(lean.contains("-- when noteRoundtripSafe note"));
    assert!(lean.contains("-- when notesRoundtripSafe notes"));
    assert!(lean.contains(
            "theorem serializeLine_law_lineRoundtrip : ∀ (note : Note), note = { id' := 1, title := \"Hello\", body := \"World\" : Note } ∨"
        ));
    assert!(lean.contains(
        "theorem serializeLines_law_notesRoundtrip : ∀ (notes : List Note), notes = [] ∨"
    ));
    assert!(lean.contains("notesRoundtripSafe notes = true ->"));
    assert!(lean.contains("parseNotes (s!\"{String.intercalate \"\\n\" (serializeLines notes)}\\n\") = Except.ok notes"));
    assert!(lean.contains("theorem serializeLine_law_lineRoundtrip_sample_1 :"));
    assert!(lean.contains("theorem serializeLines_law_notesRoundtrip_sample_1 :"));
}

/// Shape-gated `grind` rung, ADMIT side: a flat nonlinear arithmetic
/// law (`x * x >= 0`) whose cone is a single NON-recursive pure fn and
/// whose default ladder ends in an honest `sorry` (no `omega`/`rfl`
/// guaranteed closer for `var * var`) must lead with the cone-aware
/// `grind` rung — `grind`'s ring/order subsolvers close such flat goals
/// without induction. Codegen-only (no lake): asserts the emitted tactic.
#[test]
fn grind_rung_admitted_on_flat_nonrecursive_law() {
    // A flat, sorry-floored, non-recursive POLYNOMIAL IDENTITY (a Yields
    // equality `grind`'s ring subsolver closes but no pinned strategy
    // claims) must gain the cone-aware grind rung. The nonnegativity /
    // order shapes that used to exercise this now route to the dedicated
    // `NonlinearNonneg` closer (`aver_int_order`), so this uses a ring
    // identity — `x² + 2x + 1 = (x + 1)²` — instead.
    let src = "\
module FlatGrind
    effects []

fn lhsPoly(x: Int) -> Int
    ? \"x squared plus twice x plus one.\"
    x * x + 2 * x + 1

fn rhsPoly(x: Int) -> Int
    ? \"x plus one, squared.\"
    (x + 1) * (x + 1)

verify lhsPoly law squareExpansion
    given x: Int = [-7, -1, 0, 1, 9]
    lhsPoly(x) => rhsPoly(x)
";
    let mut ctx = ctx_from_source(src, "FlatGrind");
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);
    assert!(
        lean.contains("grind ["),
        "a flat, sorry-floored, non-recursive law must gain the cone-aware \
         grind rung:\n{lean}"
    );
}

/// Shape-gated `grind` rung, SKIP side (the "not worse" invariant): an
/// INDUCTIVE law whose cone contains a user-recursive pure fn
/// (`len`/`append`, a list-length monoid identity) routes to the
/// structural-induction path `grind` cannot close. The gate MUST NOT
/// emit `grind` there — emitting it would only burn ~1.2s per proof for
/// a guaranteed fall-through. Codegen-only: asserts NO `grind` anywhere
/// in the inductive law's module.
#[test]
fn grind_rung_skipped_on_inductive_recursive_law() {
    let src = "\
module IndNoGrind
    effects []

fn len(xs: List<Int>) -> Int
    match xs
        [] -> 0
        [x, ..rest] -> 1 + len(rest)

fn append(xs: List<Int>, ys: List<Int>) -> List<Int>
    match xs
        [] -> ys
        [x, ..rest] -> List.concat([x], append(rest, ys))

verify len law lenAppend
    given xs: List<Int> = [[], [1], [1, 2, 3]]
    given ys: List<Int> = [[], [4], [5, 6]]
    len(append(xs, ys)) => len(xs) + len(ys)
";
    let mut ctx = ctx_from_source(src, "IndNoGrind");
    let out = transpile(&mut ctx);
    let lean = generated_lean_file(&out);
    assert!(
        !lean.contains("grind"),
        "an inductive law over user-recursive fns (len/append) must NOT \
         gain a grind rung — grind cannot close a structural-induction \
         goal, so emitting it is pure waste:\n{lean}"
    );
}

/// Locate a `verify <fn> law <name>` block in a built context.
fn find_clique_law<'a>(
    ctx: &'a CodegenContext,
    fn_name: &str,
    law_name: &str,
) -> (&'a VerifyBlock, &'a VerifyLaw) {
    for item in &ctx.items {
        if let TopLevel::Verify(vb) = item
            && vb.fn_name == fn_name
            && let VerifyKind::Law(law) = &vb.kind
            && law.name == law_name
        {
            return (vb, law);
        }
    }
    panic!("law {fn_name}.{law_name} not found");
}

#[test]
fn clique_cursor_monotonicity_recognizes_self_contained_but_declines_on_missing_pool_law() {
    // A self-contained two-member string-position clique (no external cursor
    // edges) is recognized: its advance law will be proven universally by the
    // rung's own conjunction.
    let self_contained = r#"
type R
    Ok(Int, Int)
    Err(String)

fn a(s: String, pos: Int) -> R
    ? "a"
    match String.charAt(s, pos)
        Option.None -> R.Err("e")
        Option.Some(c) -> b(s, pos + 1)

fn b(s: String, pos: Int) -> R
    ? "b"
    match String.charAt(s, pos)
        Option.None -> R.Ok(0, pos)
        Option.Some(c) -> a(s, pos + 1)

verify a law aAdvances
    given s: String = ["x"]
    given pos: Int = [0]
    given v: Int = [0]
    given p: Int = [0]
    when a(s, pos) == R.Ok(v, p)
    p >= pos => true
"#;
    let ctx = ctx_from_source(self_contained, "SelfContained");
    let (vb, law) = find_clique_law(&ctx, "a", "aAdvances");
    assert!(
        super::law_auto::recognize_clique_position_monotonicity(vb, law, &ctx),
        "a self-contained clique must be recognized"
    );

    // The SAME clique, but `a` now scrutinizes a NON-clique sub-parser `ext`
    // whose returned position feeds the semantic edge. `ext` has NO universal
    // advance law in the pool, so the rung DECLINES (fail-closed) — the law
    // keeps its bounded proof rather than a silently weaker universal. This is
    // the decline-on-missing-pool-law path.
    let missing_pool_law = r#"
type R
    Ok(Int, Int)
    Err(String)

fn ext(s: String, pos: Int) -> R
    ? "ext"
    R.Ok(0, pos)

fn a(s: String, pos: Int) -> R
    ? "a"
    match ext(s, pos)
        R.Err(m) -> R.Err(m)
        R.Ok(v, p) -> b(s, p)

fn b(s: String, pos: Int) -> R
    ? "b"
    match String.charAt(s, pos)
        Option.None -> R.Err("e")
        Option.Some(c) -> a(s, pos + 1)

verify a law aAdvances
    given s: String = ["x"]
    given pos: Int = [0]
    given v: Int = [0]
    given p: Int = [0]
    when a(s, pos) == R.Ok(v, p)
    p >= pos => true
"#;
    let ctx2 = ctx_from_source(missing_pool_law, "MissingPoolLaw");
    let (vb2, law2) = find_clique_law(&ctx2, "a", "aAdvances");
    assert!(
        !super::law_auto::recognize_clique_position_monotonicity(vb2, law2, &ctx2),
        "a clique reaching a sub-parser with no universal advance law must decline"
    );
}