verif 0.2.0

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
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
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
//! Read contracts out of the *source*, because MIR does not carry attributes.
//!
//! # Why a macro block, and not an attribute
//!
//! The obvious syntax would be `#[requires(x < 10)]`, and it is what SPARK's
//! `Pre` looks like. It cannot be used here, for a reason worth stating: an
//! attribute that is not a built-in has to be expanded by a proc macro, and a
//! proc macro is a *crate dependency*. This crate's central claim is that it
//! has none — `cargo tree` must print exactly one line — and giving that up to
//! get nicer syntax would trade the property that makes the tool usable in a
//! bare-metal build for a cosmetic one.
//!
//! So the contract is a declarative macro block, which is real Rust syntax,
//! always compiles, expands to nothing, and needs no dependency:
//!
//! ```
//! # use verif::spec;
//! spec! {
//!     requires: b != 0,
//!     ensures: ret * b <= a,
//! }
//! fn div(a: u32, b: u32) -> u32 { a / b }
//! ```
//!
//! The scanner finds the block by its `spec!` head and reads each
//! `clause: body,` out of the source text. The `/// requires:` / `/// ensures:`
//! doc-comment spelling is still accepted — it feeds the same clause parser, so
//! the two cannot disagree about what a clause means — and it is what a source
//! that must not import `verif` uses. `//!` inner docs are skipped, so the
//! contract parser does not mistake its own documentation for a contract — a bug
//! this file had until the scanner was made to ignore `//!`.
//!
//! This is the one place the frontend looks at source text rather than at the
//! compiler's own IR, and the split is deliberate. Attributes are erased long
//! before MIR is printed, so a contract cannot ride along with the body. Reading
//! it from source instead keeps the two halves independent: the *body* comes
//! from `rustc`, and the *claim* comes from the file you wrote. Neither can
//! quietly rewrite the other, and a contract that names a function the MIR dump
//! does not contain is reported rather than ignored.
//!
//! # The expression language
//!
//! Deliberately small, and small enough to be obviously sound. A contract is a
//! comparison between two arithmetic expressions over the argument names, the
//! return value (`ret`), and integer literals:
//!
//! ```text
//!   requires: a < 1000,
//!   requires: b != 0,
//!   ensures: ret <= a + b,
//!   requires: a <= 100 && b <= 100,
//!   ensures: (ret - a) <= 50,
//! ```
//!
//! Operators: `+ - * / % & | ^ << >>`, comparisons `== != < <= > >=`, and
//! `&& || !`, with Rust's own precedence, plus `as` casts and the
//! `wrapping_*` methods. Anything outside that — a general function call, an
//! array index, an arbitrary method — is *refused*, and a refused contract means
//! the function is not verified at all. Refusing is the only safe response: a
//! contract the frontend cannot read exactly is a contract it cannot check, and
//! silently dropping it would report success for an unchecked property.

use std::collections::{BTreeMap, BTreeSet};

use crate::mir::parse::{split_top_level, Const, Ty, USIZE_WIDTH};
use crate::smt::{self, Pred, Var};

/// How long an array may be before a symbolic subscript is refused.
///
/// `a[i]` is modelled as an ite chain over the array's whole domain, so the cost
/// is linear in the length. A bound keeps a very large array from turning a
/// contract into a term the solver cannot handle; past it the subscript is
/// refused rather than silently approximated.
pub const MAX_INDEX_CHAIN: u64 = 64;

/// The bound a symbolic subscript's ite chain is valid under.
///
/// The chain is built by enumerating a *finite* range and selecting the element
/// whose index matches. An array's range is its type length, a constant. A
/// slice's length is a symbolic input, so its range is the length variable --
/// but the chain can only enumerate a bounded number of steps, so a slice's
/// chain is valid only where the length is within that bound.
///
/// Carrying the bound as a type rather than as a `u64` is what keeps the two
/// from being confused: a slice has no constant to put in the `u64`, and writing
/// one would be a guess about the caller.
#[derive(Clone, Copy, Debug)]
pub enum IndexBound {
    /// An array: the length is in the type, so the bound is that constant, and
    /// `i < n` is the whole obligation.
    Const(u64),
    /// A slice: the length is a symbolic input, and the chain enumerates
    /// `0..MAX_INDEX_CHAIN`, so the chain is exact only where
    /// `len <= MAX_INDEX_CHAIN`. The obligation is that *and* `i < len`.
    ///
    /// The length bound is what makes the chain exact for *every* index in the
    /// slice rather than only for the index the contract named: with
    /// `i < len <= MAX` any index the body reads is one the enumeration covers.
    /// Bounding the index alone would leave a read at some other index falling
    /// through the chain to a wrong value.
    Len(Var),
}

/// A contract attached to a function.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FnContract {
    /// Raw text of each `#[requires(...)]`, in source order.
    pub requires: Vec<String>,
    /// Raw text of each `#[ensures(...)]`, in source order.
    pub ensures: Vec<String>,
    /// Raw text of each loop `invariant:`, in source order.
    ///
    /// A loop invariant is not inferred. `wp` already made that call for its own
    /// frontend (`Stmt::While::invariant` is not optional), and for the same
    /// reason: the invariant is the induction hypothesis, and guessing it means
    /// guessing the proof. A loop with no invariant is unwound and reported
    /// incomplete, which is what happened here before this field existed.
    ///
    /// The text is not tied to a loop in the source. A function with one loop has
    /// one invariant; a function with several loops and several `invariant:`
    /// lines is refused rather than guessed at, because attaching the wrong
    /// invariant to the wrong loop would be unsound.
    pub invariants: Vec<String>,
    /// Raw text of each `decreases:` clause, in source order.
    ///
    /// A recursive function needs a measure that strictly decreases at each
    /// recursive call, or the induction has no well-founded basis and assuming the
    /// callee's contract at the recursive call would assume the conclusion. The
    /// clause is what licenses that assumption: the call is sound only when the
    /// measure is smaller at the call than at entry *and* stays non-negative.
    ///
    /// It is not inferred. A guessed measure is a guessed proof, which is the same
    /// reason a loop invariant is supplied rather than synthesised. A function with
    /// no `decreases` that calls itself is refused at the call rather than assumed.
    ///
    /// More than one is refused, like more than one `invariant:`, because two
    /// measures could disagree and picking either would be guessing which proof the
    /// source asked for.
    pub decreases: Vec<String>,
    /// The loop termination measure, from `/// variant: <expr>`.
    ///
    /// Without one, a loop is proved for *partial* correctness only: a divergent
    /// loop can verify, because nothing says the header is ever left. The measure
    /// is the well-founded quantity the loop counts down, and it is supplied
    /// rather than inferred for the same reason an invariant is -- a guessed
    /// measure is a guessed proof.
    ///
    /// The measure is checked against the loop the `invariant:` attaches to, so a
    /// `variant:` without an `invariant:` is refused rather than silently ignored
    /// (there would be no loop head to evaluate it at, and no invariant to carry
    /// it). Like `decreases:`, at most one is taken: two measures could disagree,
    /// and picking either would be guessing which proof the source asked for.
    pub variant: Option<String>,
    /// The loop-unwinding bound, from `/// unwind: <n>`.
    ///
    /// A function with a loop and no `invariant:` is *unwound*: the header is
    /// re-entered up to `DEFAULT_UNWIND` times and the path is then reported
    /// unknown. The default is deliberately small, and a loop that needs more
    /// iterations than it allows is a *reported* refusal, not a silent cut. This
    /// clause is how a caller says "unwind further": `unwind: 40` raises the bound
    /// for this function so a loop too long for the default is decided rather than
    /// refused. It is a bound on the number of times the *back edge* may be taken,
    /// so it has to be at least the loop's trip count.
    ///
    /// It is supplied rather than inferred for the same reason an invariant is:
    /// guessing a bound means guessing a proof. A non-numeric or zero value is
    /// refused rather than defaulted.
    ///
    /// A *declared* bound is a claim ("this loop finishes within `n` iterations"),
    /// so a path that runs off the end of it is Kani's **unwinding assertion**: a
    /// `Failed` obligation naming the bound, not an incompleteness. That is what
    /// keeps the clause sound -- a `verified` under `unwind: 3` would otherwise be
    /// a statement about the first three iterations only. A loop with *no* bound
    /// still cuts off at `DEFAULT_UNWIND`, but that default is not a claim the
    /// caller made, so it is reported as incompleteness rather than refuted.
    ///
    /// Raising the bound is only useful because the walk *prunes* unsatisfiable
    /// paths: once a guard folds to a constant the impossible edge is dropped, so a
    /// loop reaches its exit edge at its real trip count instead of at the bound.
    /// Without that pruning a raised bound is honoured but the loop still cannot
    /// decide, because the infeasible exit edges are explored too.
    pub unwind: Option<u32>,
    /// Clause-shaped doc-comment lines that are *not* clauses this frontend
    /// understands, as `(line number, the line as written)`.
    ///
    /// A line that looks like a clause (`word: ...`) but is not one of the four
    /// keywords is the dangerous shape, because the reader cannot tell a typo
    /// from prose. `/// ensuers: ret == 99` used to be dropped on the floor: the
    /// function then had *no* postcondition, was checked against `true`, and was
    /// reported `Verified` with zero obligations -- a green report for a claim
    /// nobody read. The same held for `variant:` (a loop measure this frontend
    /// does not yet take), which a reader would reasonably expect to be
    /// *honoured* rather than ignored. Both are recorded here and the function is
    /// *skipped* rather than silently verified without them, which is the same
    /// discipline the unreadable-contract path already follows.
    ///
    /// Only a line whose leading word is close to a real keyword is recorded, so
    /// ordinary prose that happens to use a colon (`/// direction: ...`) is left
    /// alone. A near miss is the typo case; a distant word is a sentence.
    pub unknown: Vec<(usize, String)>,
    /// Line number of the `fn` item, for diagnostics.
    pub line: usize,
    /// The parameter names and types from the signature, in declaration order.
    ///
    /// A callee whose body is in the dump gets its parameter *names* from the
    /// dump's `debug` bindings, which is where the executor reads them. A callee
    /// whose body is *not* in the dump has no `debug` bindings at all, so the
    /// source signature is the only place its names exist -- and a call answered
    /// from that callee's contract has to bind the contract's `requires: n <= 10`
    /// to the right argument, which needs the name. Positional binding is the only
    /// thing tying the two together, so a signature this scanner could not read
    /// leaves the list empty and the call is refused rather than bound by guess.
    pub params: Vec<(String, Ty)>,
    /// The declared return type, for a postcondition over `ret`. `None` when the
    /// scanner could not read the signature, which refuses the call rather than
    /// defaulting the type -- a `ret` of the wrong width would make a postcondition
    /// comparison meaningless.
    pub ret: Option<Ty>,
    /// This signature's parameter slots, by position, *including* a receiver.
    ///
    /// [`Self::params`] drops a receiver because a call's argument list has none,
    /// which is what the call route needs. The *body* route needs the opposite: a
    /// trait declaration's contract names the declaration's parameters, and an
    /// implementation may name them differently, so the two signatures have to be
    /// lined up slot by slot -- and a receiver occupies a slot. `None` when the
    /// signature could not be read whole, which refuses an inherited contract
    /// rather than binding a name to the wrong argument. See
    /// [`Specs::contract_for_fn`].
    pub slots: Option<Vec<ParamSlot>>,
}

/// One parameter slot of a source signature, by position.
///
/// A contract on a trait *declaration* names the declaration's parameters, and an
/// implementation is free to name them differently -- `fn f(&self, a: u8, b: u8)`
/// and `fn f(&self, b: u8, a: u8)` are the same method. Aligning the two is a
/// matter of *position*, so a reader that has to do it must keep the positions,
/// and the receiver is position 0 of every method.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParamSlot {
    /// `self`, `&self`, `&mut self` or `mut self`. It holds a position but names
    /// no value a contract can compare, so nothing is rewritten for it.
    Receiver,
    /// A `name: Type` parameter.
    Named(String),
}

/// Every function's contract, keyed by function name.
#[derive(Clone, Debug, Default)]
pub struct Specs {
    /// Contracts keyed by function name. A function with no entry has no
    /// contract, which means "check panic freedom on every input" rather than
    /// "skip it".
    pub by_fn: BTreeMap<String, FnContract>,
    /// Struct layouts read from the same source, keyed by struct name.
    ///
    /// A contract that names a field (`c.lo`) needs two things the MIR dump does
    /// not carry: which *index* that name is (declaration order), and the field's
    /// width and signedness. The dump prints `_1: &Config` and nothing about
    /// `Config`, so the layout has to come from the source — the same place the
    /// contract text itself comes from, which keeps the two consistent by
    /// construction. A struct with no entry here has no readable fields, and a
    /// contract naming one is refused rather than guessed.
    ///
    /// A struct declared inside a `mod` is keyed by its *module-qualified* path
    /// (`m::Outer`), with the bare name also inserted when it is unique
    /// crate-wide. Two modules that each declare `Outer` must not share one
    /// layout: the drop-glue check would read whichever `Outer` was inserted last,
    /// and if that one is glue-free a panicking field destructor disappears from
    /// the proof. Lookups go through [`Specs::struct_of`], which prefers the
    /// qualified key and falls back to the bare one.
    pub structs: BTreeMap<String, StructDef>,
    /// Enum layouts read from the same source, keyed by enum name.
    ///
    /// An enum argument has no width of its own, but its *tag* does, and the
    /// `switchInt` a `match` lowers to compares that tag against the variant
    /// indices. Those indices are not in the MIR dump -- it prints `_2 =
    /// discriminant(_1)` and `switchInt(move _2) -> [0: bb4, 1: bb3, 2: bb2]`,
    /// which is a number per arm and no name at all. So the same reasoning as
    /// [`Specs::structs`] applies: the layout has to come from the source, and a
    /// contract naming a variant is refused rather than guessed at when it is not
    /// there.
    pub enums: BTreeMap<String, EnumDef>,
    /// The names of `const` items declared at *module* scope (outside any `fn`
    /// body), read from the source.
    ///
    /// The MIR dump prints a crate-level `const` and a function-local one
    /// identically (`const L: u8 = const 3_u8;`), so the definition alone cannot
    /// say which it is. A crate-level item is *used* bare (`const L`) while a
    /// local one is used qualified (`const f::L`), and that use site is the usual
    /// tell -- but a crate-level item a contract names and the body never uses has
    /// no use site at all, so it would be dropped and the contract left
    /// unreadable. This set is the second tell: a name declared here is
    /// module-scoped and its bare definition must be kept. See
    /// [`crate_level_consts`] and `parse::parse_program_scoped`.
    pub crate_consts: BTreeSet<String>,
    /// The names of `const` generic parameters declared anywhere in the source.
    ///
    /// A `const` generic parameter's *uses* print as a bare `const N`, the same
    /// spelling a crate-level item's use site gets, so the whole-crate bare-use
    /// heuristic would keep a function-local `const N` under a bare program-wide
    /// key and let an unrelated contract resolve `N` to that local's value -- a
    /// false proof. This set is what the parser subtracts from the bare uses. See
    /// [`const_generic_params`].
    pub const_generics: BTreeSet<String>,
    /// The owner type of each `impl` block, keyed by the 1-based `(line, column)`
    /// of its `impl` keyword -- the same location rustc prints in a method's
    /// definition name `<impl at FILE:L:C: L:C>::m`.
    ///
    /// The dump's method name identifies the `impl` by location and names no
    /// type; without this map there is no way to tell `A::value` from `B::value`
    /// (a lost proof: each is checked against the other's contract) or a local
    /// `impl Foo::from` from an external `u16::from` (a false proof: a call to the
    /// external function is answered by the local body). See `line_scopes`.
    pub impl_owners: BTreeMap<(usize, usize), String>,
    /// The *trait* each `impl` block implements, keyed by the same location as
    /// [`Self::impl_owners`]. Absent for an inherent `impl`, which is the common
    /// case. The value is the trait's *path* as written (`From`,
    /// `std::convert::From`), not just its last segment.
    ///
    /// This is the second half of telling a local `impl From<u8> for u16` from the
    /// standard library's: both print a call as `<u16 as From<u8>>::from` when the
    /// local `From` is in scope, and both have owner `u16`, so the *owner alone
    /// cannot separate them*. The trait path can, because the compiler qualifies
    /// the library trait in the call it resolved there
    /// (`<u16 as std::convert::From<u8>>::from`) and the local impl's bare `From`
    /// is not a suffix of that. See `impl_trait` and the executor's
    /// `resolve_callee`.
    pub impl_traits: BTreeMap<(usize, usize), String>,
    /// The *trait arguments* each `impl` block instantiates, keyed as
    /// [`Self::impl_traits`] and holding them as written (`u8` for
    /// `impl From<u8> for u16`). Absent for an inherent `impl` or a trait with no
    /// arguments.
    ///
    /// Path and owner cannot separate the library's `From<u8> for u16` from a local
    /// `From<Local> for u16`; both have owner `u16` and both answer the method tail
    /// `from`. The instantiation is what separates them, so a call to one is not
    /// answered from the other's body. See `impl_trait_args` and the executor's
    /// `resolve_callee`.
    pub impl_trait_args: BTreeMap<(usize, usize), String>,
    /// The traits the crate itself declares, as module-qualified paths: `From` for
    /// a crate-root trait, `m::Trait` for one inside `mod m`.
    ///
    /// rustc prints a trait in a call as its *shortest crate-unique* path, so a
    /// bare `Trait` in a dump names this crate's crate-root trait only when the
    /// crate declares no other trait of that name. Without this set a bare call
    /// name cannot be told apart from an unrelated same-named trait in another
    /// module, and a suffix match would let the wrong `impl` answer -- a false
    /// proof. See the executor's `trait_candidate_admits`.
    pub declared_traits: BTreeSet<String>,
    /// Contracts on methods, keyed by `(impl line, impl column, method name)`.
    ///
    /// A method's contract cannot live in [`Self::by_fn`] under its bare name: two
    /// `impl` blocks may each declare a `value`, and one entry would silently
    /// overwrite the other, so one method's body would be checked against the
    /// other's claim. The location disambiguates them, exactly as it does in the
    /// dump. [`Self::by_fn`] keeps free functions (whose bare name is unique
    /// within a file); a method is recorded here instead.
    pub by_method: BTreeMap<(usize, usize, String), FnContract>,
    /// Contracts on *trait method declarations*, keyed by `Trait::method` with the
    /// trait's module-qualified path (`Bump::bump`, `m::Bump::bump`).
    ///
    /// A declaration has no body, so rustc emits no MIR for it and it can never be
    /// a verification target on its own. Its contract is a promise the trait's
    /// *implementations* inherit, so it is checked on each impl rather than on the
    /// declaration.
    ///
    /// It must not live in [`Self::by_fn`], and that is not a filing preference:
    /// `by_fn` keys are matched by *unique path suffix*, so a key `Bump::bump`
    /// answers a lookup for a free function named `bump` -- a different item. A
    /// free `fn bump() -> u8 { 9 }` would then be checked against the trait's
    /// `ensures: ret == 9`, pass, and be reported as `Bump::bump: Verified`, which
    /// reads as "the trait's promise is discharged" when in fact *no* implementation
    /// was ever checked. A separate table is what keeps the two apart.
    pub by_trait: BTreeMap<String, FnContract>,
    /// The contracted functions declared with *no body* -- an `extern` block item,
    /// or a trait-free `fn …;`.
    ///
    /// Such a declaration has no MIR by construction, so it can never be a target,
    /// and its contract is *assumed* at each call instead (the modular case the
    /// executor's `CalleeEnv` answers). That is not a lost proof, so it must not be
    /// reported `missing` like a contract whose body was expected and not found --
    /// a file whose only external call verified was nevertheless `is_clean() ==
    /// false`, which is the false alarm that trains a reader to ignore the report.
    /// Recorded here so the report can tell the two apart.
    pub bodyless: BTreeSet<String>,
}

/// An enum's variants, in declaration order.
///
/// The *discriminant* is stored per variant, not taken from the vector position.
/// rustc numbers variants by declaration order *unless* the source gives an
/// explicit value (`B = 3`), and then a later variant's discriminant is neither
/// its position nor its predecessor's value. A reader numbering by position puts
/// a contract naming `E::C` on the wrong tag, and -- because the `match` arm
/// constants come from rustc, not from this reader -- the contract and the arm
/// then disagree about which variant a value is.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EnumDef {
    /// `(name, payload types, discriminant)` per variant, in declaration order.
    /// A unit variant has an empty payload; a struct variant records no payload
    /// types, so a contract naming one of its fields is refused rather than bound
    /// to the wrong thing.
    pub variants: Vec<(String, Vec<Ty>, u64)>,
}

impl EnumDef {
    /// The discriminant for `name`, or `None` if the enum has no such variant.
    pub fn index_of(&self, name: &str) -> Option<u64> {
        self.variants.iter().find(|(n, _, _)| n == name).map(|(_, _, d)| *d)
    }

    /// The width that can hold every discriminant, and no more.
    ///
    /// A tag's domain is the set of discriminants, so the width is the largest
    /// one's. Taking the variant *count*'s width instead is only the same thing
    /// when the discriminants are `0..count`, which an explicit discriminant
    /// breaks: `A, B = 3, C` needs three bits for the tag `4`, not the two bits a
    /// count of three would give.
    pub fn tag_width(&self) -> u8 {
        let max = self.variants.iter().map(|(_, _, d)| *d).max().unwrap_or(0);
        (64 - max.leading_zeros()).max(1) as u8
    }

    /// The predicate that a value of this enum's tag is one of its variants.
    ///
    /// This is what the run may *assume* about a symbolic tag, and it has to be
    /// exact rather than a count. `tag < arity` is a fact about the type only when
    /// the discriminants are consecutive from zero; with `A, B = 3, C` the real
    /// tags are `0`, `3` and `4`, and `tag < 3` would exclude `4` -- excluding a
    /// value the type admits. An assumed bound that is *false* for a real input is
    /// the unsound direction: it can make a proof vacuous. The disjunction of
    /// equalities is exact for any numbering.
    pub fn tag_bound(&self, tag: Var) -> Pred {
        let mut acc: Option<Pred> = None;
        for (_, _, d) in &self.variants {
            let p = smt::eq_const(tag, *d);
            acc = Some(match acc {
                None => p,
                Some(prev) => smt::or(prev, p),
            });
        }
        acc.unwrap_or_else(|| smt::truth(false))
    }
}

/// A struct's fields, in declaration order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StructDef {
    /// `(name, type)` for each field. The index in this vector *is* the MIR field
    /// index, because a struct without `repr(transparent)`/reordering has its
    /// fields in declaration order and rustc prints `.0` for the first one.
    pub fields: Vec<(String, Ty)>,
}

impl StructDef {
    /// The field index for `name`, or `None` if the struct has no such field.
    pub fn index_of(&self, name: &str) -> Option<u32> {
        self.fields.iter().position(|(n, _)| n == name).map(|i| i as u32)
    }
}

impl Specs {
    /// The contract attached to `name`, if the source declared one.
    ///
    /// Only free functions are looked up: a method's contract is keyed by its
    /// `impl`'s location, so [`Self::resolve`] is the entry point that takes the
    /// MIR name. This stays for callers that already know they hold a bare name.
    pub fn get(&self, name: &str) -> Option<&FnContract> {
        self.by_fn.get(name)
    }

    /// The contract for a function whose MIR definition name is `name`.
    ///
    /// The name is rustc's: a free function's path-qualified name (`f`, `a::f`,
    /// `f::g`), a trait default's `T::value`, or a method's
    /// `<impl at FILE:L:C: L:C>::m`. A method's contract is found by that
    /// `(line, column)` and the method's tail -- never by the tail alone, because
    /// two `impl` blocks may each declare `m` and a tail match would then hand one
    /// method the other's contract (a lost proof: a true postcondition refuted, or
    /// worse, a false one proved).
    ///
    /// A non-method contract is keyed by its *full source path* (see
    /// [`Specs::by_fn`]). rustc prints a definition by the shortest crate-unique
    /// path suffix, so the printed name is either the full path or a `::`-aligned
    /// tail of it: `f` when the name is unique crate-wide, `a::f` when two modules
    /// each declare `f`, `T::value` for a trait default. The match is exact first
    /// (so `a::f` and `b::a::f` stay apart -- rustc prints both in full once they
    /// collide), then a unique suffix. An ambiguous suffix is *refused*, not
    /// guessed: a wrong pairing is a lost or false proof, whereas a refusal makes
    /// the caller report the contract `missing`, which is visible.
    ///
    /// Matching only the exact name left every nested item's contract unresolved,
    /// and an unresolved contract is not a refusal: `verify_function` builds its
    /// precondition and postcondition from `contract`, so a missing one means
    /// `requires: true` and *no* `ensures` -- a function with a false postcondition
    /// was reported verified with zero obligations, the body never checked at all.
    pub fn resolve(&self, name: &str) -> Option<&FnContract> {
        if let Some(c) = self.by_fn.get(name) {
            return Some(c);
        }
        if let Some(loc) = impl_location(name) {
            let tail = name.rsplit("::").next()?;
            if let Some(c) = self.by_method.get(&(loc.0, loc.1, tail.to_string())) {
                return Some(c);
            }
            // No contract on the impl itself. The trait's *declaration* may carry
            // one, and an implementation inherits it: that is what a trait contract
            // means. Without this an impl of a contracted trait was checked against
            // nothing at all, and the trait's promise was reported `missing` with no
            // hint that an impl existed to carry it. See [`Self::by_trait`].
            return self.trait_contract(loc.0, loc.1, tail);
        }
        // A path-qualified non-method name (`a::f`, `T::value`): the contract may
        // be keyed by that exact path, or by a longer path it is a suffix of.
        // Collect every suffix match and take it only when it is unique.
        let mut hit: Option<&FnContract> = None;
        let mut count = 0usize;
        for (key, c) in &self.by_fn {
            if is_path_suffix(key, name) {
                hit = Some(c);
                count += 1;
            }
        }
        if count == 1 {
            hit
        } else {
            None
        }
    }

    /// The struct layout for a type name, qualified-first.
    ///
    /// `name` is a `Ty::Other` spelling, which may be module-qualified
    /// (`m::Outer`), carry generic arguments (`Vec<u8>`), or be bare. The lookup
    /// tries, in order:
    ///
    /// 1. the full name as written (`m::Outer`);
    /// 2. the name with generics stripped (`Vec`);
    /// 3. the bare tail (`Outer`), for a struct declared at the crate root or whose
    ///    qualified key was not recorded.
    ///
    /// The qualified key wins, which is what keeps two same-named structs in
    /// different modules apart. Falling back to the bare tail is only safe because
    /// the scanner inserts a bare key solely for a struct whose bare name is
    /// unique crate-wide; when two share a name, only the qualified keys exist and
    /// a bare-tail miss is a refusal (the caller reports "not modelled"), not a
    /// wrong layout.
    pub fn struct_of(&self, name: &str) -> Option<&StructDef> {
        struct_lookup(&self.structs, name)
    }

    /// A second contract the `impl` method `name` carries, when it has both its
    /// own and its trait's.
    ///
    /// `resolve` returns one contract, so when both exist the other is silently
    /// dropped whichever way it goes. Neither choice is defensible: preferring the
    /// impl's drops the trait's promise (the trait's contract was written to hold
    /// for *every* implementation), and preferring the trait's drops a claim the
    /// impl's author wrote about their own body. The caller refuses on this and
    /// names both, which is the only answer that loses nothing.
    pub fn contract_conflict(&self, name: &str) -> Option<String> {
        let loc = impl_location(name)?;
        let tail = name.rsplit("::").next()?;
        if !self.by_method.contains_key(&(loc.0, loc.1, tail.to_string())) {
            return None;
        }
        let tr = self.impl_traits.get(&(loc.0, loc.1))?;
        if !self.by_trait.contains_key(&format!("{tr}::{tail}")) {
            return None;
        }
        Some(format!(
            "the implementation of `{tail}` declares its own contract and the trait `{tr}` declares one for the same method, so the two would have to agree; the frontend checks one specification per function and refuses rather than dropping either"
        ))
    }

    /// The contract the `impl` at `(line, col)` inherits from the trait it
    /// implements, for the method named `tail`.
    ///
    /// `None` when the impl implements no trait (an inherent `impl`), when the
    /// trait declares no contract for that method, or when the trait's path and the
    /// method tail do not name a declaration this scanner read. A `None` here is
    /// what makes [`Self::resolve`] fall through to "no contract", which the caller
    /// reports rather than treating as a promise.
    pub fn trait_contract(&self, line: usize, col: usize, tail: &str) -> Option<&FnContract> {
        let tr = self.impl_traits.get(&(line, col))?;
        self.by_trait.get(&format!("{tr}::{tail}"))
    }

    /// The contract for one *body* in the dump, together with the names it uses
    /// for that body's arguments.
    ///
    /// The inherited case is why this exists. An implementation may name its
    /// parameters differently from the trait it implements, and the declaration's
    /// contract names the *declaration's* parameters. [`Self::resolve`] returns the
    /// right contract but nothing about the alignment, so binding it by the
    /// implementation's own names would attach `ret == a` to whichever argument the
    /// implementation calls `a` -- the wrong value whenever the names are swapped,
    /// which is a false proof and not a lost one.
    ///
    /// `Err` when a trait contract is inherited but the two signatures cannot be
    /// aligned exactly (an unreadable signature, or a different number of slots).
    /// The caller refuses then: an inherited contract that cannot be bound
    /// positionally is not a contract that may be guessed at.
    pub fn contract_for_fn<'a>(
        &'a self,
        f: &crate::mir::parse::MirFn,
    ) -> Result<(Option<&'a FnContract>, Option<ArgRename>), String> {
        let Some(loc) = impl_location(&f.name) else {
            return Ok((self.resolve(&f.name), None));
        };
        let Some(tail) = f.name.rsplit("::").next() else {
            return Ok((self.resolve(&f.name), None));
        };
        // The impl's own contract wins and needs no rename: it was written against
        // this very signature.
        if let Some(c) = self.by_method.get(&(loc.0, loc.1, tail.to_string())) {
            return Ok((Some(c), None));
        }
        let Some(decl) = self.trait_contract(loc.0, loc.1, tail) else {
            return Ok((None, None));
        };
        let Some(tr) = self.impl_traits.get(&(loc.0, loc.1)) else {
            return Ok((Some(decl), None));
        };
        let rename = self.align_signature(decl, f, tr, tail)?;
        Ok((Some(decl), rename))
    }

    /// The map from a body's argument locals to the names the inherited contract
    /// uses, or `Err` when the two signatures cannot be aligned exactly.
    fn align_signature(
        &self,
        decl: &FnContract,
        f: &crate::mir::parse::MirFn,
        tr: &str,
        tail: &str,
    ) -> Result<Option<ArgRename>, String> {
        let Some(slots) = decl.slots.as_ref() else {
            return Err(format!(
                "the trait `{tr}` declares a contract for `{tail}`, but its signature could not be read, so the contract's parameters cannot be aligned with the implementation's by position"
            ));
        };
        // A body has one MIR local per parameter, receiver included, and the trait
        // declaration has one slot per parameter, receiver included. Equal counts
        // are what makes "the Nth name means the Nth local" true; a mismatch means
        // one of the two readings is short, and binding by position would then
        // attach a name to the wrong argument.
        if slots.len() != f.arg_locals.len() {
            return Err(format!(
                "the trait `{tr}` declares {} parameter slot(s) for `{tail}`, but the implementation has {} argument local(s), so the contract cannot be aligned with the body by position",
                slots.len(),
                f.arg_locals.len()
            ));
        }
        let mut map = BTreeMap::new();
        for (slot, &local) in slots.iter().zip(&f.arg_locals) {
            if let ParamSlot::Named(name) = slot {
                // The trait's name for this *position*. Recorded even when it
                // matches the body's own name, so the map is a complete statement
                // of what each argument means rather than a diff that a later
                // change could quietly get wrong.
                map.insert(local, name.clone());
            }
        }
        Ok(Some(ArgRename(map)))
    }
}

/// The `(line, column)` an `<impl at FILE:L:C: L:C>` name carries, if it is one.
///
/// rustc prints a method's definition as `<impl at FILE:L:C: L:C>::m`. The name
/// holds *two* locations: the first is the `impl` keyword itself, the second is
/// the end of the `impl` header (`impl A` spans columns 1..7, so `impl A {` prints
/// `4:1: 4:7`). The owner type is the thing at the keyword, so the first pair is
/// the one that matters -- and it is what `line_scopes` records.
///
/// The file part is split off at the `: ` that separates the two locations, so a
/// path containing a colon (a Windows drive) does not confuse the parse.
pub(crate) fn impl_location(name: &str) -> Option<(usize, usize)> {
    // A method may be module-qualified (`inner::<impl at …>::d`), so the marker
    // is searched for rather than required at the front.
    let start = name.find("<impl at ")? + "<impl at ".len();
    let inner = name[start..].split('>').next()?;
    // `FILE:L:C: L:C` -- the head is the keyword's own `L:C`.
    let (head, _end) = inner.rsplit_once(": ")?;
    let mut parts = head.rsplit(':');
    let col = parts.next()?;
    let line = parts.next()?;
    Some((line.trim().parse().ok()?, col.trim().parse().ok()?))
}

/// The names of `const` generic parameters declared anywhere in the source.
///
/// A `const` generic parameter (`fn f<const N: usize>()`) is erased from the MIR
/// dump's function header, but its *uses* print as a bare `const N` -- the same
/// spelling a crate-level `const N` item's use site gets. That collides with the
/// whole-crate heuristic [`crate_level_consts`] and `parse::bare_const_uses` use to
/// tell a crate-level item from a function-local one: a const-generic `N` makes
/// `N` look "used bare", so a function-local `const N` in some *other* function
/// keeps a bare program-wide key, and an unrelated contract naming `N` resolves to
/// that local's value -- a false proof (or a spurious vacuous-precondition
/// failure). The names are read here so both passes can ignore them.
///
/// The tell is positional: a `const` generic parameter is always written
/// `const NAME:` after a `<` (first parameter) or a `,` (a later one), whereas a
/// `const` *item* is never preceded by either. So a `const NAME:` whose
/// preceding non-space character is `<` or `,` is a parameter.
///
/// Rust allows arbitrary whitespace and comments between the `const` keyword and
/// the name, so `const\n    N: usize` and `const/*c*/N: usize` are the same
/// parameter as `const N: usize`. Matching a literal `"const "` would miss both,
/// leaving the name in `const_generics` absent and its bare uses in the parser's
/// heuristic -- the leak this function exists to close. So the keyword is read as
/// a token and the name is taken after any run of whitespace and comments.
pub fn const_generic_params(source: &str) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    let bytes = source.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        // Skip comments and string/char literals so a `const N:` in text is not read.
        if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') {
            while i < bytes.len() && bytes[i] != b'\n' {
                i += 1;
            }
            continue;
        }
        if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
            i += 2;
            while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                i += 1;
            }
            i += 2;
            continue;
        }
        if bytes[i] == b'"' {
            i += 1;
            while i < bytes.len() && bytes[i] != b'"' {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            continue;
        }
        // The `const` keyword must be a whole word: `constant` is not one.
        if bytes[i..].starts_with(b"const")
            && !bytes.get(i + 5).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_')
        {
            // The preceding non-space character decides: `<`/`,` means a generic
            // parameter, anything else (or the start of the file) an item.
            let before = source[..i].trim_end().as_bytes().last().copied();
            if matches!(before, Some(b'<') | Some(b',')) {
                // Skip whitespace and comments between `const` and the name.
                let mut j = i + "const".len();
                loop {
                    while j < bytes.len() && bytes[j].is_ascii_whitespace() {
                        j += 1;
                    }
                    if bytes.get(j) == Some(&b'/') && bytes.get(j + 1) == Some(&b'/') {
                        while j < bytes.len() && bytes[j] != b'\n' {
                            j += 1;
                        }
                        continue;
                    }
                    if bytes.get(j) == Some(&b'/') && bytes.get(j + 1) == Some(&b'*') {
                        j += 2;
                        while j + 1 < bytes.len() && !(bytes[j] == b'*' && bytes[j + 1] == b'/') {
                            j += 1;
                        }
                        // An unterminated block comment runs to the end of the
                        // source; `j` must not pass `bytes.len()`, or the slice
                        // below panics. `verify_file_with` scans contracts before
                        // it invokes rustc, so malformed source must not crash
                        // verification -- it is rustc's error to report.
                        j = (j + 2).min(bytes.len());
                        continue;
                    }
                    break;
                }
                let after = &source[j..];
                let name: String = after
                    .chars()
                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
                    .collect();
                let plain =
                    name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
                if plain && after[name.len()..].trim_start().starts_with(':') {
                    out.insert(name);
                }
            }
            i += "const".len();
            continue;
        }
        i += 1;
    }
    out
}

/// The names of `const` items declared at module scope -- outside any brace.
///
/// The MIR dump prints a crate-level `const` and a function-local one
/// identically, so the definition alone cannot say which it is; the use site
/// (`const L` bare vs `const f::L` qualified) is the usual tell. A crate-level
/// constant that a *contract* names but the body never uses has no use site at
/// all, so that tell is silent and the definition would be dropped, leaving the
/// contract unreadable. The source, though, says plainly whether the item is
/// inside a `fn` body: a crate-level item sits at brace depth zero.
///
/// The scan tracks brace depth over the whole file, ignoring braces inside string
/// and character literals and inside comments, and records the name of every
/// `const NAME: …` seen at depth zero. It deliberately does not try to be a Rust
/// parser: a `const` generic parameter or an associated constant inside an `impl`
/// is at depth > 0 and so is not recorded, which is the safe direction (recording
/// too much would re-open the local-leak false proof).
pub fn crate_level_consts(source: &str) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    let mut depth: i32 = 0;
    let mut in_block_comment = false;
    // The last non-whitespace byte of the preceding lines, so a `const NAME:`
    // that starts a line can still be told a generic parameter (the `<` or `,`
    // sits on an earlier line) from an item. See [`const_generic_params`].
    let mut prev_last: Option<u8> = None;
    for raw in source.lines() {
        let mut line = raw;
        // Block comments can span lines; a brace inside one is not code.
        loop {
            if in_block_comment {
                match line.find("*/") {
                    Some(i) => {
                        in_block_comment = false;
                        line = &line[i + 2..];
                    }
                    None => line = "",
                }
            } else if let Some(i) = line.find("/*") {
                in_block_comment = true;
                line = &line[i + 2..];
            } else {
                break;
            }
        }
        // A `const NAME: …` at depth zero is a crate-level item. The name is read
        // before the braces on the line are counted, so `const L: u8 = 3;` is
        // caught while a `const` inside a `fn` body (depth > 0) is not. A
        // `const` generic parameter is not an item, and is told apart by what
        // precedes it: a parameter follows a `<` or `,`, an item never does. The
        // `<`/`,` may sit on an earlier line (a multi-line parameter list), which
        // is what `prev_last` carries. See [`const_generic_params`].
        if depth == 0 {
            let t = line.trim_start();
            let t = t.strip_prefix("pub(crate) ").or_else(|| t.strip_prefix("pub ")).unwrap_or(t);
            if let Some(after) = t.strip_prefix("const ") {
                let preceded = line[..line.len() - t.len()].trim_end().as_bytes().last().copied();
                let before = preceded.or(prev_last);
                let name: String = after
                    .chars()
                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
                    .collect();
                let plain =
                    name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
                if plain
                    && !matches!(before, Some(b'<') | Some(b','))
                    && after[name.len()..].trim_start().starts_with(':')
                {
                    out.insert(name);
                }
            }
        }
        // Count braces outside strings, chars and line comments.
        let bytes = line.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'/' if bytes.get(i + 1) == Some(&b'/') => break,
                b'"' => {
                    i += 1;
                    while i < bytes.len() && bytes[i] != b'"' {
                        if bytes[i] == b'\\' {
                            i += 1;
                        }
                        i += 1;
                    }
                }
                b'\'' => {
                    i += 1;
                    while i < bytes.len() && bytes[i] != b'\'' {
                        if bytes[i] == b'\\' {
                            i += 1;
                        }
                        i += 1;
                    }
                }
                b'{' => depth += 1,
                b'}' => depth -= 1,
                _ => {}
            }
            i += 1;
        }
        if let Some(c) = line.trim_end().as_bytes().last() {
            prev_last = Some(*c);
        }
    }
    out
}

/// One source line's scope, from [`line_scopes`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineScope {
    /// The innermost `impl` the line sits inside, as the `(line, column)` of its
    /// `impl` keyword, or `None`. See [`Specs::impl_owners`].
    pub impl_loc: Option<(usize, usize)>,
    /// The enclosing `trait` names, outermost first -- empty outside a trait.
    ///
    /// Separate from [`Self::path`], which mixes `mod`, `trait` and `fn`: a `fn`
    /// declared directly in a trait is a *method of that trait*, and its contract
    /// is a promise the trait's implementations inherit, while a `fn` declared in a
    /// `mod` is an ordinary free function. Telling the two apart from a mixed path
    /// would mean guessing which element was the trait. See [`Specs::by_trait`].
    pub trait_path: Vec<String>,
    /// The enclosing `mod`/`trait`/`fn` item names, outermost first. A method's
    /// `impl` is *not* an element (it is named by location, not by a path); a
    /// `fn`'s own name is not an element of the scope of the line that declares
    /// it, because the scope is read before that line's items open. A nested `fn`
    /// therefore sees its outer `fn` in `path`, which is exactly how rustc composes
    /// `f::g`.
    pub path: Vec<String>,
}

/// The kind of item a source line opens, for [`line_scopes`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum ItemKind {
    Impl,
    Mod,
    Trait,
    Fn,
}

/// One open item on the [`line_scopes`] stack.
struct ScopeFrame {
    kind: ItemKind,
    name: String,
    impl_loc: Option<(usize, usize)>,
    /// The depth the item's *body* brace opened at, once seen. `None` while the
    /// header has not opened its body yet (a brace on a later line, or a
    /// braceless item). A brace inside a generic argument list does not count, so
    /// `impl Foo<{ 1 }>` stays `None` until the real body brace. See
    /// [`line_scopes`].
    body_depth: Option<i32>,
}

/// The scope of every source line: the innermost `impl` (its keyword location)
/// and the enclosing `mod`/`trait`/`fn` path.
///
/// rustc names a function's *definition* by its shortest crate-unique path
/// suffix, so a free function inside a `mod` is printed `a::f` (or bare `f` when
/// that is already unique crate-wide), a trait's default method is printed
/// `T::value`, and a function nested in a function is printed `f::g`. The source
/// is the only place the full path exists, so this pass recovers it: it walks the
/// file counting brace depth (outside strings, chars and comments) and, for each
/// line, records the `impl` it is inside and the `mod`/`trait`/`fn` names around
/// it. [`Specs::resolve`] then matches a MIR name to a contract by that path, so a
/// nested item's contract is found rather than silently dropped (a false proof).
///
/// The map is indexed by 0-based line number, so a contract's `fn` at 1-based
/// line `L` looks up `L - 1`.
pub(crate) fn line_scopes(source: &str) -> Vec<LineScope> {
    let lines: Vec<&str> = source.lines().collect();
    let mut out: Vec<LineScope> = vec![LineScope::default(); lines.len()];
    // Innermost-last. A frame records the depth its *body* brace opened at, which
    // is what a brace-on-the-next-line header needs: Rust accepts `impl Foo` (or
    // `mod a`, `fn f()`) with the `{` on a later line, and such a header raises no
    // depth on its own line -- so a pop keyed on "depth has not increased" would
    // drop it *before* its items, and every nested contract would be keyed as if
    // the item were absent (a false proof). Recording the body depth keeps the
    // header alive until its own brace opens and the depth returns to it, and
    // ignores a brace that belongs to the *header* (a const-expression generic
    // argument, `impl Foo<{ 1 }>`), which would otherwise pop the frame early.
    let mut stack: Vec<ScopeFrame> = Vec::new();
    let mut depth: i32 = 0;
    let mut in_block_comment = false;
    for (idx, raw) in lines.iter().enumerate() {
        let mut line = *raw;
        // A brace inside a block comment is not code.
        loop {
            if in_block_comment {
                match line.find("*/") {
                    Some(i) => {
                        in_block_comment = false;
                        line = &line[i + 2..];
                    }
                    None => line = "",
                }
            } else if let Some(i) = line.find("/*") {
                in_block_comment = true;
                line = &line[i + 2..];
            } else {
                break;
            }
        }
        // The scope of this line is read *before* its own items open, so a `fn`
        // that declares a contract is not inside itself.
        let impl_loc =
            stack.iter().rev().find(|f| f.kind == ItemKind::Impl).and_then(|f| f.impl_loc);
        let path: Vec<String> = stack
            .iter()
            .filter(|f| matches!(f.kind, ItemKind::Mod | ItemKind::Trait | ItemKind::Fn))
            .map(|f| f.name.clone())
            .collect();
        let trait_path: Vec<String> = stack
            .iter()
            .filter(|f| f.kind == ItemKind::Trait)
            .map(|f| f.name.clone())
            .collect();
        out[idx] = LineScope { impl_loc, path, trait_path };
        if let Some(col) = impl_keyword_col(raw) {
            stack.push(ScopeFrame {
                kind: ItemKind::Impl,
                name: String::new(),
                impl_loc: Some((idx + 1, col)),
                body_depth: None,
            });
        } else if let Some((kind, name)) = item_head(raw) {
            stack.push(ScopeFrame {
                kind,
                name,
                impl_loc: None,
                body_depth: None,
            });
        }
        // Count braces outside strings, chars, line comments and angle brackets.
        //
        // The depth at which an item's *body* opens is what tells a header
        // whether its body has opened yet: a one-line body (`fn f() -> u8 { 1 }`)
        // raises and returns the depth within the line, so comparing the *final*
        // depth would miss it and leave the frame on the stack, qualifying every
        // later line. The body-opening brace is the first `{` reached while no
        // `<` is open -- a generic argument list can contain a brace-delimited
        // const expression (`impl Foo<{ 1 }>`), and that brace belongs to the
        // *header*, not the body: counting it would mark the frame opened and pop
        // it before the real body, so every method under a brace-in-header `impl`
        // lost its `impl` location and its contract was dropped (a false proof).
        //
        // `depth` is updated for *every* brace so the scope stays right even when
        // a body line contains a `<` that is the comparison operator, not a
        // generic bracket. Angle brackets only decide whether a brace is the body
        // brace, and only until the body is seen.
        let bytes = line.as_bytes();
        let mut body_open_depth: Option<i32> = None;
        let mut body_seen = false;
        let mut angle = 0i32;
        let mut angle_depth: Option<i32> = None;
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'/' if bytes.get(i + 1) == Some(&b'/') => break,
                b'"' => {
                    i += 1;
                    while i < bytes.len() && bytes[i] != b'"' {
                        if bytes[i] == b'\\' {
                            i += 1;
                        }
                        i += 1;
                    }
                }
                b'\'' => {
                    // `'a` is a lifetime; `'a'`, `'{'`, `'\n'` are char literals.
                    // Skipping to the *next* quote would swallow the rest of a
                    // `<'a>` generic list -- including its `>` -- so a lifetime
                    // advances one byte and only a real literal is scanned.
                    let lifetime = matches!(bytes.get(i + 1), Some(c) if c.is_ascii_alphabetic() || *c == b'_')
                        && bytes.get(i + 2) != Some(&b'\'');
                    if !lifetime {
                        i += 1;
                        while i < bytes.len() && bytes[i] != b'\'' {
                            if bytes[i] == b'\\' {
                                i += 1;
                            }
                            i += 1;
                        }
                    }
                }
                b'{' if body_seen || angle == 0 => {
                    if !body_seen {
                        body_seen = true;
                        body_open_depth = Some(depth + 1);
                    }
                    depth += 1;
                }
                b'{' => depth += 1,
                b'}' => depth -= 1,
                b'<' if !body_seen && angle == 0 => {
                    angle = 1;
                    angle_depth = Some(depth);
                }
                b'<' if !body_seen && angle_depth == Some(depth) => angle += 1,
                b'>' if !body_seen && angle > 0 && angle_depth == Some(depth) => angle -= 1,
                _ => {}
            }
            i += 1;
        }
        // Record the depth the header's body brace opened at, once, so its pop
        // waits for the matching close instead of firing on the header line. A
        // frame that has already opened is left alone: a later brace inside its
        // body belongs to that body, not to the header.
        if let Some(last) = stack.last_mut() {
            if last.body_depth.is_none() {
                if let Some(d) = body_open_depth {
                    last.body_depth = Some(d);
                }
            }
        }
        // A header with no brace that ends in `;` declares an item without a body
        // (`mod a;`, a trait's `fn f();`): it never opens, so it must not linger on
        // the stack and qualify every later line.
        if let Some(last) = stack.last() {
            if last.body_depth.is_none() && line.trim_end().ends_with(';') {
                stack.pop();
            }
        }
        // An item whose block has closed by the end of this line is no longer
        // enclosing anything: pop it once its body brace has opened and the depth
        // returns to the depth that brace opened at. A header that has not opened
        // yet is kept. The comparison uses the recorded body depth rather than the
        // pre-header depth, so an `impl` header that shares its line with the
        // enclosing block's close still pops at the right point.
        while let Some(f) = stack.last() {
            if let Some(d) = f.body_depth {
                if depth < d {
                    stack.pop();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }
    out
}

/// The `mod`/`trait`/`fn` item a source line opens, if it opens one.
///
/// Only a line whose first token (after visibility and modifiers) is `mod`,
/// `trait` or `fn` counts, so a mention inside a comment or a call like
/// `fn_call()` is not an item. The name is the leading identifier, which is all
/// rustc's own path uses -- generics (`fn f<T>`) and arguments are dropped.
fn item_head(raw: &str) -> Option<(ItemKind, String)> {
    let mut rest = raw.trim_start();
    loop {
        let t = rest.trim_start();
        let mut advanced = false;
        for p in [
            "pub(crate)",
            "pub(self)",
            "pub(super)",
            "pub",
            "unsafe",
            "async",
            "const",
            "default",
            "extern",
        ] {
            if let Some(r) = t.strip_prefix(p) {
                if r.starts_with(|c: char| c.is_whitespace()) {
                    rest = r;
                    advanced = true;
                    break;
                }
            }
        }
        if !advanced {
            rest = t;
            break;
        }
    }
    // An `extern "C"` ABI string sits between the keyword and `fn`.
    if let Some(after) = rest.strip_prefix('"') {
        if let Some(end) = after.find('"') {
            rest = after[end + 1..].trim_start();
        }
    }
    let (kw, kind) = if let Some(r) = rest.strip_prefix("mod ") {
        (r, ItemKind::Mod)
    } else if let Some(r) = rest.strip_prefix("trait ") {
        (r, ItemKind::Trait)
    } else if rest.starts_with("fn ") {
        return Some((ItemKind::Fn, fn_name(raw)?));
    } else {
        return None;
    };
    let name: String = kw.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
    if name.is_empty() {
        None
    } else {
        Some((kind, name))
    }
}

/// Whether `suffix` is a `::`-aligned tail of `path` (`f` and `b::f` are tails of
/// `a::b::f`; `b::f` is not a tail of `a::bf`).
///
/// This is the inverse of how rustc shortens a definition name: it prints the
/// shortest path suffix that is unique crate-wide, so the printed name is always a
/// `::`-aligned tail of the item's full path.
pub(crate) fn is_path_suffix(path: &str, suffix: &str) -> bool {
    if suffix.is_empty() || path.len() <= suffix.len() {
        return false;
    }
    if !path.ends_with(suffix) {
        return false;
    }
    path.as_bytes()[path.len() - suffix.len() - 1] == b':'
}

/// The 1-based column of an `impl` keyword on this line, if it has one.
///
/// The column is what rustc prints in `<impl at FILE:L:C: …>`, so it must match
/// rustc's own count: 1-based, counting characters from the start of the line.
/// Only a line whose first non-space token is `impl` (optionally after `unsafe`)
/// counts, so a nested `impl` inside a body is found but a mention of `impl` in a
/// comment or identifier is not.
fn impl_keyword_col(raw: &str) -> Option<usize> {
    let trimmed = raw.trim_start();
    let offset = raw.len() - trimmed.len();
    let (rest, col0) = match trimmed.strip_prefix("unsafe ") {
        Some(r) => (r, offset + "unsafe ".len()),
        None => (trimmed, offset),
    };
    let rest = rest.strip_prefix("impl")?;
    // `impl` must be a whole word: `impl_thing` is an identifier.
    if rest.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {
        return None;
    }
    Some(raw[..col0].chars().count() + 1)
}

/// The owner type of an `impl` header, as the base type name rustc prints in a
/// call (`Foo` in `Foo::m`, `Slot` in `<Slot as Stow>::stash`).
///
/// `impl Foo` -> `Foo`; `impl Stow for Slot` -> `Slot` (the type after `for`);
/// `impl<T> Gen<T>` -> `Gen`; `impl From<u8> for Bar` -> `Bar`. A generic
/// parameter list is skipped before the first type name, and the base name is
/// taken so a call's `base_type` (which strips generics) compares equal.
pub(crate) fn impl_owner(header: &str) -> Option<String> {
    let after = header.trim_start().strip_prefix("unsafe ").unwrap_or(header.trim_start());
    let rest = after.strip_prefix("impl")?;
    // Skip an `impl<T, U>` parameter list.
    let rest = rest.trim_start();
    let rest = if let Some(r) = rest.strip_prefix('<') {
        let mut depth = 1usize;
        let mut end = 0usize;
        for (i, c) in r.char_indices() {
            match c {
                '<' => depth += 1,
                '>' => {
                    depth -= 1;
                    if depth == 0 {
                        end = i + 1;
                        break;
                    }
                }
                _ => {}
            }
        }
        &r[end..]
    } else {
        rest
    };
    // `for` selects the implementing type; otherwise the first type is the owner.
    let (before, after_for) = match rest.split_once(" for ") {
        Some((b, a)) => (b, Some(a)),
        None => (rest, None),
    };
    let source = after_for.unwrap_or(before);
    let name: String = source
        .trim_start()
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
        .collect();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// The text inside the first balanced `<…>` of `s`, or `None` when there is none.
///
/// Balanced rather than "up to the first `>`": a trait argument can itself be
/// generic (`impl Trait<Option<u8>> for Foo`), and cutting at the first `>` would
/// read `Option<u8` as the argument -- a different instantiation from the call's
/// `Option<u8>`, so a call to the impl would be refused. See [`impl_trait_args`].
pub(crate) fn angle_inner(s: &str) -> Option<&str> {
    let open = s.find('<')?;
    let mut depth = 0usize;
    for (i, c) in s[open..].char_indices() {
        match c {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    return Some(s[open + 1..open + i].trim());
                }
            }
            _ => {}
        }
    }
    None
}

/// The text of an `impl` header's *trait clause*: everything between the skipped
/// `impl<…>` parameter list and the ` for `, or `None` for an inherent `impl`.
///
/// `impl<T> From<T> for Wrapper<T>` gives `From<T>`, `impl From<u8> for u16` gives
/// `From<u8>`, and `impl u16` gives `None`. This is the shared reading of the two
/// things an `impl` says about its trait: the path ([`impl_trait`]) and the
/// arguments ([`impl_trait_args`]).
fn impl_trait_clause(header: &str) -> Option<&str> {
    let after = header.trim_start().strip_prefix("unsafe ").unwrap_or(header.trim_start());
    let rest = after.strip_prefix("impl")?;
    // Skip an `impl<T, U>` parameter list, as `impl_owner` does.
    let rest = rest.trim_start();
    let rest = if let Some(r) = rest.strip_prefix('<') {
        let mut depth = 1usize;
        let mut end = 0usize;
        for (i, c) in r.char_indices() {
            match c {
                '<' => depth += 1,
                '>' => {
                    depth -= 1;
                    if depth == 0 {
                        end = i + 1;
                        break;
                    }
                }
                _ => {}
            }
        }
        &r[end..]
    } else {
        rest
    };
    // A trait impl has `Trait for Type`; an inherent one has only `Type`.
    let (before, _) = rest.split_once(" for ")?;
    Some(before)
}

/// The *trait* an `impl` block implements, read from its header, or `None` for an
/// inherent `impl`.
///
/// `impl From<u8> for u16` yields `Some("From")`, `impl std::convert::From<u8>
/// for u16` yields `Some("std::convert::From")` and `impl u16` yields `None`. The
/// full path is kept, not just the last segment, because that is exactly what
/// separates a local `impl From<u8> for u16` from the standard library's: a call
/// the compiler resolved to the library trait prints its path
/// (`<u16 as std::convert::From<u8>>::from`), which is *not* a suffix of the bare
/// `From` a local impl was written with. See [`Specs::impl_traits`].
///
/// The `impl`'s type parameters (`impl<T> From<T> for …`) are skipped first,
/// exactly as in [`impl_owner`], and the trait is the text *before* ` for ` when
/// there is one, up to (not including) its own `<…>` type-argument list.
pub(crate) fn impl_trait(header: &str) -> Option<String> {
    let before = impl_trait_clause(header)?;
    // The trait path is the leading `a::b::C` of the clause; its own `<…>` type
    // arguments and any `where` clause are dropped.
    let path: String = before
        .trim_start()
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ':')
        .collect();
    let path = path.trim_end_matches(':').to_string();
    if path.is_empty() {
        None
    } else {
        Some(path)
    }
}

/// The *trait arguments* an `impl` block instantiates, as written, or `None` for an
/// inherent `impl` or one whose trait names no arguments.
///
/// `impl From<u8> for u16` yields `Some("u8")` and `impl From<Local> for u16` yields
/// `Some("Local")`. These are the one thing that separates two impls of a generic
/// trait that share a path, an owner and a method: the library's `From<u8> for u16`
/// and a local `From<Local> for u16` differ only here, so a call to one must not be
/// answered from the other's body. See [`Specs::impl_trait_args`].
pub(crate) fn impl_trait_args(header: &str) -> Option<String> {
    let before = impl_trait_clause(header)?;
    let inner = angle_inner(before)?;
    (!inner.is_empty()).then(|| inner.to_string())
}

/// Whether a trait path written in an `impl` header names an external crate, so
/// that prefixing the enclosing module would be wrong.
///
/// `std::convert::From`, `core::cmp::Ord`, `alloc::…` and a `crate::`/`self::`
/// path are already rooted; a bare `From` or a `super::m::From` is relative to the
/// module the `impl` sits in. See [`extract`]'s use of [`Specs::impl_traits`].
fn is_absolute_trait_path(path: &str) -> bool {
    let first = path.split("::").next().unwrap_or(path);
    matches!(first, "std" | "core" | "alloc" | "crate" | "self" | "super")
}

/// The traits the crate declares, as module-qualified paths (`Trait` for a
/// crate-root trait, `m::Trait` for one inside `mod m`).
///
/// rustc prints a trait in a call as its *shortest crate-unique* path, so a bare
/// name in a dump is this crate's crate-root trait only when one exists; when it
/// does not, a bare name is the shortening of the crate's only trait of that name
/// (or an external trait). Recording the declared set is what lets the executor
/// tell those apart instead of treating a same-named suffix as identity. See
/// [`Specs::declared_traits`].
pub(crate) fn declared_traits(scopes: &[LineScope], lines: &[&str]) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for (idx, raw) in lines.iter().enumerate() {
        // `item_head` already ignores an `impl` line and every other item kind.
        let Some((ItemKind::Trait, name)) = item_head(raw) else {
            continue;
        };
        let qualified = if scopes[idx].path.is_empty() {
            name
        } else {
            format!("{}::{}", scopes[idx].path.join("::"), name)
        };
        out.insert(qualified);
    }
    out
}

/// Qualify a trait path written in an `impl` header the way rustc prints a call
/// to it: resolve a leading name through the module's imports, then prefix the
/// enclosing module path.
///
/// `use std::convert::From;` makes a bare `From` inside that module the standard
/// trait, whose call prints as `std::convert::From`; without resolving the import
/// the scanner would record `m::From` and no call would match -- a lost proof. A
/// path that already names a crate (`std::…`, `core::…`) is kept as written, and a
/// bare name with no import is prefixed with the module, which is how rustc prints
/// a module-local trait. See [`Specs::impl_traits`].
fn qualify_trait(
    written: &str,
    scope: &[String],
    imports: &BTreeMap<String, String>,
) -> String {
    // A path written with a *relative* root names the same trait as the
    // module-qualified path the declaration is keyed by, so it has to be resolved
    // to that spelling or the two never meet:
    //
    // * `crate::T` at the crate root is `T`; inside `mod m` it is still `T`, since
    //   `crate` names the root and the root's module path is empty.
    // * `self::T` inside `mod m` is `m::T`.
    // * `super::T` inside `mod m::inner` is `m::T`.
    //
    // Without this, `impl crate::T for S` was never paired with `T`'s declaration
    // contract: the impl was not checked against it at all, and the declaration was
    // reported as having no implementation -- the promise silently unenforced, which
    // is the outcome this frontend treats as worse than a refusal.
    if let Some(normalized) = resolve_relative_trait_path(written, scope) {
        return normalized;
    }
    if is_absolute_trait_path(written) {
        return written.to_string();
    }
    let first = written.split("::").next().unwrap_or(written);
    if let Some(full) = imports.get(first) {
        return format!("{full}{}", &written[first.len()..]);
    }
    if scope.is_empty() {
        written.to_string()
    } else {
        format!("{}::{}", scope.join("::"), written)
    }
}

/// Resolve a trait path written with a leading `crate`/`self`/`super` to the
/// module-qualified path a declaration is keyed by.
///
/// `None` when the path has no such root, which leaves the caller's import and
/// module-prefix logic to handle it. A leading `self` at the crate root resolves to
/// the root, so `self::T` and `T` are the same key; a `super` with no enclosing
/// module cannot resolve and is left to the caller rather than guessed at.
fn resolve_relative_trait_path(written: &str, scope: &[String]) -> Option<String> {
    let mut segments: Vec<&str> = written.split("::").collect();
    let mut base: Vec<String> = scope.to_vec();
    let mut saw_root = false;
    while let Some(first) = segments.first().copied() {
        match first {
            "crate" => {
                base.clear();
                segments.remove(0);
                saw_root = true;
            }
            "self" => {
                segments.remove(0);
                saw_root = true;
            }
            "super" => {
                // A `super` past the root cannot resolve; the caller keeps the
                // written form, which will simply not match a declaration.
                base.pop()?;
                segments.remove(0);
                saw_root = true;
            }
            _ => break,
        }
    }
    if !saw_root {
        return None;
    }
    // `self::` / `crate::` with nothing after it names the module itself, which is
    // not a trait; keeping the written form makes it a non-match rather than a key.
    if segments.is_empty() {
        return None;
    }
    base.extend(segments.into_iter().map(|s| s.to_string()));
    Some(base.join("::"))
}

/// The text of an `impl` header, spanning lines until its body-opening `{` (or the
/// `;` of a bodyless item).
///
/// Rust permits the header to wrap, so `impl Trait\n    for Foo {` declares the
/// same impl as a one-line spelling. Reading only the `impl` keyword's own line
/// loses the trait there, and a lost trait is a refused projected call -- a lost
/// proof. See [`extract`].
fn impl_header(lines: &[&str], start: usize) -> String {
    let mut out = String::new();
    let mut angle = 0i32;
    let mut seen_angle = false;
    for raw in &lines[start..] {
        let mut line = *raw;
        // Drop a trailing line comment so a `{` inside it is not the body brace.
        if let Some(i) = line.find("//") {
            line = &line[..i];
        }
        let mut cut = line.len();
        for (i, c) in line.char_indices() {
            match c {
                '<' if !seen_angle => {
                    angle += 1;
                    seen_angle = true;
                }
                '<' if angle > 0 => angle += 1,
                '>' if angle > 0 => angle -= 1,
                '{' if angle == 0 => {
                    cut = i;
                    break;
                }
                ';' if angle == 0 => {
                    cut = i;
                    break;
                }
                _ => {}
            }
        }
        out.push_str(&line[..cut]);
        if cut < line.len() {
            break;
        }
        out.push(' ');
    }
    out
}

/// The `use` imports visible on each line, keyed by the enclosing module path.
///
/// A trait's *written* name need not name a trait the crate declares: `use
/// std::convert::From;` makes a bare `From` inside that module the standard
/// trait, and rustc prints the call with the library path it resolved. Without
/// this map the scanner would qualify the impl with its own module
/// (`m::From`) and no call would match it -- a lost proof. See [`extract`].
///
/// Imports are kept *per module path*, not in one running map. A Rust import is
/// visible across its whole scope, so the map for `m` must hold what `m` imports
/// even at a line that comes after a nested `mod nested {}`: a single map that is
/// reset on every scope change (the old behaviour) loses `m`'s `use` for the rest
/// of `m`, and the later `impl From<…>` in `m` is then qualified `m::From` and no
/// call matches it -- a lost proof. Item imports are also order-independent
/// (`use` after the impl still binds), so each module's map is assembled from
/// every `use` at its own nesting depth before any line reads it. See
/// [`Specs::impl_traits`].
///
/// A `#[cfg]`-conditional import is the one that is *not* order-independent: it
/// binds only when its condition holds, and rustc then binds nothing at all. The
/// source cannot evaluate an arbitrary condition, so a conditional binding is
/// held below an unconditional one and never displaces it: a live
/// `use std::convert::From as Conv;` followed by a disabled
/// `#[cfg(any())] use crate::Other as Conv;` must keep `Conv` bound to the
/// standard trait, or the impl written with `Conv` is recorded with the wrong
/// trait and its call is lost. See [`is_cfg_use`].
fn module_imports(scopes: &[LineScope], lines: &[&str]) -> Vec<BTreeMap<String, String>> {
    // One map per module path, assembled from every `use` at that path, then handed
    // to each line of that module. Each entry carries whether the binding came from
    // an unconditional `use`, which is what decides precedence.
    let mut per_module: BTreeMap<Vec<String>, BTreeMap<String, (String, bool)>> = BTreeMap::new();
    let mut i = 0;
    while i < lines.len() {
        if !is_use_start(lines[i]) {
            i += 1;
            continue;
        }
        let conditional = is_cfg_use(lines, i);
        // A `use` item ends at its `;`, which may be on a later line
        // (`use a::b::{\n    C,\n};`). Reading one line at a time loses such an
        // import, and a lost import is a wrongly qualified impl -- a lost proof.
        // Join the item's lines, then read the whole thing. See [`parse_use`].
        let mut item = String::new();
        let mut j = i;
        loop {
            item.push_str(lines[j]);
            item.push(' ');
            if lines[j].contains(';') || j + 1 >= lines.len() {
                break;
            }
            j += 1;
        }
        let map = per_module.entry(scopes[i].path.clone()).or_default();
        for (short, full) in parse_use(&item) {
            // An unconditional binding is definitely live, so a conditional one must
            // not overwrite it (the conditional may be `#[cfg]`-disabled, in which
            // case rustc binds nothing and the earlier binding is the live one).
            let live_unconditional = map.get(&short).is_some_and(|(_, unconditional)| *unconditional);
            if conditional && live_unconditional {
                continue;
            }
            map.insert(short, (full, !conditional));
        }
        i = j + 1;
    }
    lines
        .iter()
        .enumerate()
        .map(|(idx, _)| {
            per_module
                .get(&scopes[idx].path)
                .map(|m| m.iter().map(|(k, (v, _))| (k.clone(), v.clone())).collect())
                .unwrap_or_default()
        })
        .collect()
}

/// Whether the `use` item starting at `lines[i]` carries a `#[cfg]` attribute.
///
/// The attribute sits on the line (or contiguous attribute lines) directly above
/// the item, or on the item's own line. A conditional import may be `#[cfg]`-disabled,
/// and rustc then binds nothing for it; treating it as live can rewrite an alias a
/// *live* import already bound, and a wrongly qualified impl is a lost proof. Only
/// the presence of a condition is read, never its value -- the source cannot
/// evaluate an arbitrary `cfg`, and a conservative "this may be off" is what
/// [`module_imports`] needs. See [`module_imports`].
fn is_cfg_use(lines: &[&str], i: usize) -> bool {
    // An attribute on the item's own line (`#[cfg(any())] use a::B;`).
    if split_leading_attrs(lines[i]).1 {
        return true;
    }
    // The attribute block directly above the item. Reading one line at a time misses
    // the head of a `#[cfg]` that spans lines -- the line next to the item is then
    // its closing `)]`, not its `#[cfg…` -- so a disabled import would look live and
    // displace a live alias. Read the whole block instead. See [`read_attr_run`].
    attrs_above_have_cfg(lines, i)
}

/// Whether the contiguous attribute block directly above `end` holds a `#[cfg…]`.
///
/// The block is the longest suffix of the contiguous non-blank lines above `end`
/// that parses as whole attributes; trying candidate starts from the top down finds
/// it, because the first start whose read covers exactly `[start, end)` is the real
/// block. A line that is not an attribute (a doc comment, or the tail of an earlier
/// item) makes every start at or above it fail, so an attribute belonging to another
/// item is never read as this item's. See [`read_attr_run`].
fn attrs_above_have_cfg(lines: &[&str], end: usize) -> bool {
    let mut top = end;
    while top > 0 && !lines[top - 1].trim().is_empty() {
        top -= 1;
    }
    (top..end).any(|start| read_attr_run(lines, start, end) == Some(true))
}

/// Whether a raw string literal opens at byte `i`, returning its `#` count and the
/// offset just past the opening `"`.
///
/// A raw string is `r"…"`, `r#"…"#`, `r##"…"##`, … with an optional `b` or `c`
/// prefix (`br#"…"#`, `cr#"…"#`). Inside one a backslash is *not* an escape, so the
/// closing `"` plus `#`s is the only thing that ends it -- `r"\"` is the two bytes
/// `\` and `"`, the `"` closing the string. Reading it as an ordinary string, the
/// `\` would escape that `"`, the real end would be missed, and a following
/// `#[cfg]` would go unread -- the lost proof this reader prevents. See
/// [`attr_close_offset`].
fn raw_string_start(bytes: &[u8], i: usize) -> Option<(usize, usize)> {
    let mut j = i;
    // An optional `b` or `c` prefix in front of the `r`.
    if matches!(bytes.get(j), Some(b'b') | Some(b'c')) {
        j += 1;
    }
    if bytes.get(j) != Some(&b'r') {
        return None;
    }
    j += 1;
    let mut hashes = 0;
    while bytes.get(j) == Some(&b'#') {
        hashes += 1;
        j += 1;
    }
    if bytes.get(j) != Some(&b'"') {
        return None;
    }
    Some((hashes, j + 1))
}

/// Whether the `'` at byte `i` opens a character literal rather than a lifetime.
///
/// A char literal holds one character (`'('`) or a backslash escape (`'\n'`,
/// `'\''`), so it opens only when a `\` follows or a closing `'` follows the next
/// character. A lifetime (`'a`, `'static`) has no closing quote and is left alone.
/// See [`attr_close_offset`].
fn is_char_literal_start_bytes(bytes: &[u8], i: usize) -> bool {
    match bytes.get(i + 1) {
        Some(b'\\') => true,
        Some(_) => bytes.get(i + 2) == Some(&b'\''),
        None => false,
    }
}

/// The offset just past the closing `"` of an ordinary string opening at `i`.
fn skip_string(bytes: &[u8], i: usize) -> usize {
    let mut j = i + 1;
    while j < bytes.len() {
        match bytes[j] {
            b'\\' => j += 2,
            b'"' => return j + 1,
            _ => j += 1,
        }
    }
    bytes.len()
}

/// The offset just past the closing `'` of a char literal opening at `i`.
fn skip_char(bytes: &[u8], i: usize) -> usize {
    let mut j = i + 1;
    if bytes.get(j) == Some(&b'\\') {
        j += 1;
    }
    j += 1;
    if bytes.get(j) == Some(&b'\'') {
        j + 1
    } else {
        j
    }
}

/// The offset just past a raw string's closing `"` + `#`s, whose opening `"` is at
/// `after_quote` and whose `#` count is `hashes`.
fn skip_raw_string(bytes: &[u8], after_quote: usize, hashes: usize) -> usize {
    let mut j = after_quote;
    while j < bytes.len() {
        if bytes[j] == b'"' {
            let mut h = 0;
            let mut k = j + 1;
            while h < hashes && bytes.get(k) == Some(&b'#') {
                h += 1;
                k += 1;
            }
            if h == hashes {
                return k;
            }
        }
        j += 1;
    }
    bytes.len()
}

/// The offset just past the `]` that closes an attribute whose `[` is at `open`.
///
/// The attribute body's `(…)`/`[…]` nest, so brackets are matched by depth. Text
/// that is *not* a delimiter is skipped whole: ordinary and raw string literals,
/// char literals, and `//` / `/* … */` comments. Each of these can hold a quote or
/// a bracket that, counted, would either end the attribute early or run it past
/// its real end -- and a run past the end reads a *disabled* `#[cfg]` as live, the
/// lost proof this reader exists to prevent. Comments are skipped because Rust
/// discards them before parsing: a `"` in a comment is not a string, and a `]` in
/// one is not the close. `None` when no `]` closes the attribute.
fn attr_close_offset(text: &str, open: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut depth = 1i32;
    let mut i = open + 1;
    while i < bytes.len() {
        match bytes[i] {
            // A line comment runs to the end of the line; a block comment nests and
            // may span lines.
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                let mut d = 1u32;
                i += 2;
                while i < bytes.len() && d > 0 {
                    if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                        d += 1;
                        i += 2;
                    } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                        d -= 1;
                        i += 2;
                    } else {
                        i += 1;
                    }
                }
            }
            b'"' => i = skip_string(bytes, i),
            b'\'' if is_char_literal_start_bytes(bytes, i) => i = skip_char(bytes, i),
            b'r' | b'b' | b'c' => match raw_string_start(bytes, i) {
                Some((hashes, after)) => i = skip_raw_string(bytes, after, hashes),
                None => i += 1,
            },
            b'[' | b'(' => {
                depth += 1;
                i += 1;
            }
            b']' | b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
                i += 1;
            }
            _ => i += 1,
        }
    }
    None
}

/// Read the lines `[start, end)` as a run of whole `#[…]` attributes, returning
/// whether any is a `#[cfg…]`; `None` when they are not all attributes.
///
/// Each attribute is read from its `#[` through the balanced `]` that closes it, so
/// one spanning lines (`#[cfg(all(\n    unix,\n))]`) is read whole rather than by its
/// first line alone. A delimiter inside quoted text is not a delimiter: `#[doc = "("]`
/// holds an unmatched `(` in a string, and counting it would make the attribute run
/// past its real end, exhaust the lines, and read a *disabled* `#[cfg]` as if it were
/// live -- the lost proof this reader exists to prevent. String, raw-string, char
/// literal and comment contents are therefore skipped whole. See [`is_cfg_use`] and
/// [`attr_close_offset`].
fn read_attr_run(lines: &[&str], start: usize, end: usize) -> Option<bool> {
    let mut cfg = false;
    let mut k = start;
    while k < end {
        let trimmed = lines[k].trim_start();
        let head = trimmed.strip_prefix("#[")?;
        // The `[` of `#[` sits this far into the line.
        let lead = lines[k].len() - trimmed.len();
        let flat = lines[k..end].join("\n");
        let close = attr_close_offset(&flat, lead + 1)?;
        // How many lines the attribute spans, so the next one starts after it.
        let spanned = flat[..close].matches('\n').count();
        if head.starts_with("cfg") {
            cfg = true;
        }
        k += spanned + 1;
    }
    Some(cfg)
}

/// Split any leading `#[…]` attributes off `line`, returning the rest and whether a
/// `#[cfg…]` attribute was among them.
///
/// An attribute on the item's own line (`#[cfg(any())] use a::B;`) would otherwise
/// hide the `use` from [`is_use_start`], and the item would be missed entirely -- a
/// lost import. The body's `(…)`/`[…]` nest, so brackets are matched by depth and the
/// attribute ends at the first `]` that closes its own `[`. Text that is not a
/// delimiter -- string, raw-string and char literal contents, and comments -- is
/// skipped by [`attr_close_offset`], so a `(` or a quote inside one does not hide
/// the `use` behind the attribute. See [`is_cfg_use`].
fn split_leading_attrs(line: &str) -> (&str, bool) {
    let mut rest = line.trim_start();
    let mut cfg = false;
    while let Some(after) = rest.strip_prefix("#[") {
        if after.starts_with("cfg") {
            cfg = true;
        }
        // `after` begins just past the `#[`, so the attribute's `[` is at index 1
        // of it; `attr_close_offset` returns the offset just past the closing `]`.
        match attr_close_offset(rest, 1) {
            // `after` is `rest[2..]`, so an offset `e` into `rest` is `e - 2` into
            // `after`.
            Some(e) => rest = after[e - 2..].trim_start(),
            // An unbalanced attribute is not one this reads; leave the line alone.
            None => break,
        }
    }
    (rest, cfg)
}

/// Strip a leading visibility (`pub`, `pub(crate)`, `pub(super)`, `pub(in …)`) from
/// an item's first line, so the `use` keyword behind it can be read.
///
/// A restricted visibility is not a `pub ` prefix, so the old `strip_prefix("pub ")`
/// missed `pub(crate) use …` entirely and the import was lost. `pub` must be
/// followed by whitespace or `(`, so a name that merely starts with it
/// (`public_thing`) is left alone.
fn strip_visibility(line: &str) -> &str {
    let s = split_leading_attrs(line).0;
    let Some(rest) = s.strip_prefix("pub") else {
        return s;
    };
    match rest.chars().next() {
        // `pub` alone, or `pub ` followed by the item.
        None => rest,
        Some(c) if c.is_whitespace() => rest.trim_start(),
        // `pub(crate)`, `pub(super)`, `pub(in path)`.
        Some('(') => match rest.find(')') {
            Some(close) => rest[close + 1..].trim_start(),
            None => rest,
        },
        // A name that merely starts with `pub` (`public_thing`) is not a visibility.
        Some(_) => s,
    }
}

/// Whether a line opens a `use` item (after any visibility).
fn is_use_start(line: &str) -> bool {
    strip_visibility(line).starts_with("use ")
        || strip_visibility(line).trim_end() == "use"
}

/// The `(short name, full path)` pairs a `use` item introduces.
///
/// Handles `use a::b::C;`, `use a::b::C as D;`, `use a::b::{C, D};` and the
/// `crate::`/`self::`/`super::` roots. A glob or a re-export with no name to bind
/// is skipped: the map is a hint for qualification, and a wrong entry would be
/// worse than a missing one.
fn parse_use(raw: &str) -> Vec<(String, String)> {
    let after_vis = strip_visibility(raw);
    let rest = match after_vis.strip_prefix("use ") {
        Some(r) => r,
        None => return Vec::new(),
    };
    // A folded multi-line item or a trailing line comment can follow the path, so
    // cut at the item's `;` (or a `//`) before reading it.
    let rest = match rest.find(';') {
        Some(i) => &rest[..i],
        None => rest,
    };
    let rest = match rest.find("//") {
        Some(i) => &rest[..i],
        None => rest,
    };
    let rest = rest.trim();
    // A grouped import: `a::b::{C, D as E}`.
    if let Some((prefix, group)) = rest.split_once("::{") {
        let group = group.strip_suffix('}').unwrap_or(group);
        let mut out = Vec::new();
        for item in group.split(',') {
            let item = item.trim();
            if item.is_empty() || item.contains('*') {
                continue;
            }
            let (path, alias) = match item.split_once(" as ") {
                Some((p, a)) => (p.trim(), a.trim()),
                None => (item, ""),
            };
            let full = format!("{}::{}", prefix, path);
            let short = if alias.is_empty() {
                path.rsplit("::").next().unwrap_or(path).to_string()
            } else {
                alias.to_string()
            };
            out.push((short, full));
        }
        return out;
    }
    if rest.contains('*') {
        return Vec::new();
    }
    let (path, alias) = match rest.split_once(" as ") {
        Some((p, a)) => (p.trim(), a.trim()),
        None => (rest, ""),
    };
    let short = if alias.is_empty() {
        path.rsplit("::").next().unwrap_or(path).to_string()
    } else {
        alias.to_string()
    };
    if short.is_empty() {
        Vec::new()
    } else {
        vec![(short, path.to_string())]
    }
}

/// Extract contracts from Rust source text.
///
/// The scanner is line-oriented and deliberately shallow: it collects
/// `requires:` / `ensures:` lines from doc comments and attaches them to the
/// next `fn` item. It fails closed — a contract it cannot parse becomes a
/// [`SpecError`] at evaluation time, which causes the function to be *skipped*
/// rather than verified against a contract that was silently dropped.
///
/// Only `///` (outer) doc comments are read. `//!` (inner) comments are ignored
/// so that module documentation describing the syntax is not read as a contract
/// for the next function in the file.
pub fn extract(source: &str) -> Specs {
    let mut specs = Specs::default();
    let mut pending = FnContract::default();
    let mut in_block_comment = false;
    // Which `const` items are declared at the crate root, before any brace opens.
    // The dump cannot tell a crate-level `const` from a function-local one, so a
    // contract that names a crate-level constant the body never uses would
    // otherwise lose its definition and go unreadable. See
    // [`Specs::crate_consts`].
    specs.crate_consts = crate_level_consts(source);
    // Which names are `const` generic parameters, so the parser can ignore their
    // bare uses when telling a crate-level `const` from a function-local one. See
    // [`const_generic_params`].
    specs.const_generics = const_generic_params(source);

    // Which `impl` block each line is inside, and the owner type of each. rustc
    // names a method's definition by the location of the `impl` keyword, so the
    // owner type -- the only thing that distinguishes `A::value` from `B::value`
    // -- has to be read here, from the same source the contract text comes from.
    // See [`Specs::impl_owners`].
    let scopes = line_scopes(source);
    let enclosing: Vec<Option<(usize, usize)>> =
        scopes.iter().map(|s| s.impl_loc).collect();
    let scope_path: Vec<Vec<String>> = scopes.iter().map(|s| s.path.clone()).collect();
    let lines: Vec<&str> = source.lines().collect();
    let imports = module_imports(&scopes, &lines);
    for (idx, raw) in lines.iter().enumerate() {
        if let Some(col) = impl_keyword_col(raw) {
            // The header can wrap over several lines, so the whole header through
            // its body-opening `{` is what names the owner and the trait. Reading
            // only the `impl` keyword's own line loses a trait declared as
            // `impl Trait\n    for Foo {` -- a refused projected call, a lost
            // proof. See [`impl_header`].
            let header = impl_header(&lines, idx);
            if let Some(owner) = impl_owner(&header) {
                specs.impl_owners.insert((idx + 1, col), owner);
            }
            if let Some(tr) = impl_trait(&header) {
                // Qualify the trait the way a call prints it: resolve a module
                // import first (`use std::convert::From;` makes the bare `From`
                // the library trait), then prefix the enclosing module for a
                // module-local trait. A path that already names a crate
                // (`std::convert::From`, `core::…`, `crate::…`) is kept as
                // written. See [`qualify_trait`].
                let qualified = qualify_trait(&tr, &scope_path[idx], &imports[idx]);
                specs.impl_traits.insert((idx + 1, col), qualified);
            }
            if let Some(args) = impl_trait_args(&header) {
                specs.impl_trait_args.insert((idx + 1, col), args);
            }
        }
    }
    // The traits the crate declares, so the executor can tell a *bare* call name
    // (`<u16 as Trait>::m`) that names this crate's crate-root trait from the
    // collision where the same bare name could be an unrelated module trait that
    // rustc shortened. See [`Specs::declared_traits`].
    specs.declared_traits = declared_traits(&scopes, &lines);

    // Struct layouts, read in the same pass. The MIR dump names a struct
    // (`_1: &Config`) but never prints its fields, so a contract like
    // `c.lo <= c.hi` has no way to learn that `lo` is field 0 of width 8 unless
    // the layout is read here.
    let mut cur_struct: Option<(String, StructDef)> = None;
    // Enum layouts, read in the same pass. An enum body is a list of variants
    // rather than a list of fields, so it needs its own cursor; a struct and an
    // enum cannot be open at once, so the two cursors never interleave.
    let mut cur_enum: Option<(String, EnumDef)> = None;
    // Struct names whose qualified key was recorded, so the bare-name
    // back-insertion can be deferred to the end and skipped when two structs
    // share a bare name. See `Specs::structs` and `Specs::struct_of`.
    let mut struct_paths: BTreeMap<String, String> = BTreeMap::new();
    let mut struct_name_counts: BTreeMap<String, u32> = BTreeMap::new();
    // Last line index consumed by a multi-line `spec! { … }` block, so the loop
    // below does not re-read its contents as ordinary lines.
    let mut skip_through: Option<usize> = None;

    for (lineno, raw_line) in source.lines().enumerate() {
        // A multi-line `spec! { … }` block is read whole by one iteration, so the
        // lines it spans are skipped here rather than re-examined -- otherwise a
        // clause inside it would also be seen as an ordinary line and the block's
        // own closing brace as an item boundary.
        if skip_through.is_some_and(|end| lineno <= end) {
            continue;
        }
        let line = raw_line.trim();
        if in_block_comment {
            if line.contains("*/") {
                in_block_comment = false;
            }
            continue;
        }
        if line.starts_with("/*") {
            if !line.contains("*/") {
                in_block_comment = true;
            }
            continue;
        }
        // Inside an enum body: read variants until the closing brace.
        if cur_enum.is_some() {
            if line.starts_with('}') {
                let (name, def) = cur_enum.take().unwrap();
                specs.enums.insert(name, def);
                continue;
            }
            match enum_variant(line) {
                VariantLine::Variant { name: vname, payload, explicit } => {
                    if let Some((_, def)) = cur_enum.as_mut() {
                        push_variant(def, vname, payload, explicit);
                    }
                }
                VariantLine::NotAVariant => {}
                // An explicit discriminant this reader cannot evaluate: the whole
                // layout is refused, because dropping the variant would shift
                // every later discriminant and guessing one would put a contract
                // on the wrong tag. Removing the enum makes a contract naming any
                // of its variants a refusal, which is the safe direction.
                VariantLine::UnreadableDiscriminant => {
                    cur_enum = None;
                }
            }
            continue;
        }
        // Inside a struct body: read fields until the closing brace.
        if cur_struct.is_some() {
            if line.starts_with('}') {
                let (name, def) = cur_struct.take().unwrap();
                specs.structs.insert(name, def);
                continue;
            }
            if let Some((fname, fty)) = struct_field(line) {
                if let Some((_, def)) = cur_struct.as_mut() {
                    def.fields.push((fname, Ty::parse(&fty)));
                }
            }
            continue;
        }
        if let Some(head) = struct_head(line) {
            // A doc comment above a struct documents the struct, not a function.
            // The pending contract is dropped here for the same reason the
            // catch-all below drops it: a contract must attach to the item it was
            // written above. Carrying it to the next `fn` was a false proof when
            // the leaked `requires` was satisfiable.
            pending = FnContract::default();
            // The layout is keyed by the struct's *module-qualified* source path
            // (`m::Outer`), and the bare name is back-inserted at the end only
            // when it is unique crate-wide. Two modules that each declare `Outer`
            // must not share one layout: the drop-glue check would otherwise read
            // whichever was recorded last, and if that one is glue-free a
            // panicking field destructor vanishes from the proof.
            let scope = scope_path.get(lineno).cloned().unwrap_or_default();
            let key_of = |name: &str| -> String {
                if scope.is_empty() {
                    name.to_string()
                } else {
                    let mut p = scope.clone();
                    p.push(name.to_string());
                    p.join("::")
                }
            };
            match head {
                // A tuple struct carries its fields in the head, numbered by
                // position, so there is no body to cursor over.
                StructHead::Tuple { name, fields } => {
                    let mut def = StructDef::default();
                    for (fname, fty) in fields {
                        def.fields.push((fname, Ty::parse(&fty)));
                    }
                    let key = key_of(&name);
                    *struct_name_counts.entry(name.clone()).or_insert(0) += 1;
                    if key != name {
                        struct_paths.insert(name, key.clone());
                    }
                    specs.structs.insert(key, def);
                }
                // A unit struct (`struct Guard;`) is a zero-field layout: the
                // drop-glue check must find no fields rather than refuse the type
                // as an unknown container, and a contract naming `.0` on it is
                // still an "unknown field" refusal because there is no field 0.
                StructHead::Unit { name } => {
                    let key = key_of(&name);
                    *struct_name_counts.entry(name.clone()).or_insert(0) += 1;
                    if key != name {
                        struct_paths.insert(name, key.clone());
                    }
                    specs.structs.insert(key, StructDef::default());
                }
                StructHead::Named { name, closed_inline } => {
                    // A one-line body is complete already; opening a cursor would run
                    // past the closing brace and consume every following line -- contracts
                    // and functions included -- as fields, so the functions would silently
                    // disappear from the spec table. Read the fields out of the head line
                    // instead, exactly as the enum path reads an `Inline` body.
                    if closed_inline {
                        let t =
                            line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
                        let mut def = StructDef::default();
                        if let Some(open) = t.find('{') {
                            if let Some(close) = t[open + 1..].rfind('}') {
                                for f in split_top_level(&t[open + 1..open + 1 + close], ',') {
                                    if let Some((fname, fty)) = struct_field(&f) {
                                        def.fields.push((fname, Ty::parse(&fty)));
                                    }
                                }
                            }
                        }
                        let key = key_of(&name);
                        *struct_name_counts.entry(name.clone()).or_insert(0) += 1;
                        if key != name {
                            struct_paths.insert(name, key.clone());
                        }
                        specs.structs.insert(key, def);
                    } else {
                        let key = key_of(&name);
                        *struct_name_counts.entry(name.clone()).or_insert(0) += 1;
                        if key != name {
                            struct_paths.insert(name, key.clone());
                        }
                        cur_struct = Some((key, StructDef::default()));
                    }
                }
            }
            continue;
        }
        if let Some((name, head)) = enum_head(line) {
            // Same as the struct head: a doc comment above an enum is the enum's,
            // not a function's, so the pending contract is dropped rather than
            // carried to the next `fn`.
            pending = FnContract::default();
            match head {
                // A one-line body is complete already; it needs no cursor.
                EnumHead::Inline(variants) => {
                    specs.enums.insert(name, EnumDef { variants });
                }
                EnumHead::MultiLine => cur_enum = Some((name, EnumDef::default())),
                // The body was refused *and* closed on this line. Opening a
                // cursor here would run past the brace and consume every
                // following line -- contracts included -- as enum contents, so
                // the layout is dropped and the cursor stays shut.
                EnumHead::Refused => {}
            }
            continue;
        }
        // Inner doc comments (`//!`) and ordinary comments are not contracts.
        if line.starts_with("//!") || line.starts_with("//") && !line.starts_with("///") {
            continue;
        }
        // A `spec! { requires: …, ensures: … }` block writes the clauses *inside
        // the code* instead of in a doc comment. It is read here, from the source
        // text, exactly like a `///` line -- the frontend never compiles it, and
        // the macro expands to nothing, so the artifact carries no trace.
        //
        // The block must be *closed* before it is believed. An unterminated one is
        // recorded as an unknown clause and the function is refused: reading a
        // partial block would attach half a contract to the next `fn`, which is the
        // silent-loss shape the clause checks exist to close.
        if in_code_block_start(line) {
            let (clauses, consumed) = in_code_block(&lines, lineno);
            if consumed == 0 {
                pending.unknown.push((
                    lineno + 1,
                    "unterminated `spec! { … }` block; the contract is not read".to_string(),
                ));
            } else {
                for (offset, text) in &clauses {
                    take_clause(&mut pending, text, lineno + 1 + offset, true);
                }
                skip_through = Some(lineno + consumed - 1);
            }
            continue;
        }
        // A `verif! { … }` block is *not* a contract block. It was accepted in an
        // earlier draft, and dropping the acceptance silently would leave the
        // function below with no contract at all -- verified against `true`, which
        // is the silent-loss shape the clause checks exist to close. So it is
        // *refused by name*: the block is consumed (so its tokens are not read as
        // prose) and the function is skipped with a reason that spells the fix.
        if is_legacy_verif_block(line) {
            let (_, consumed) = in_code_block(&lines, lineno);
            pending.unknown.push((
                lineno + 1,
                "`verif! { … }` is not a contract block; write `spec! { … }` (or \
                 `verif::spec! { … }`) so the block is read as clauses"
                    .to_string(),
            ));
            if consumed > 0 {
                skip_through = Some(lineno + consumed - 1);
            }
            continue;
        }
        // A `some_other_crate::spec! { … }` block is *not* this crate's macro, and
        // the reader cannot resolve the path to prove otherwise. Refused by name,
        // for the same reason as `verif!` above: reading an unrelated macro's tokens
        // as clauses would attach a contract the source never stated.
        if is_foreign_spec_block(line) {
            let (_, consumed) = in_code_block(&lines, lineno);
            pending.unknown.push((
                lineno + 1,
                "a `*::spec! { … }` block that is not `verif::spec!` cannot be read as \
                 a contract; write `spec! { … }` or `verif::spec! { … }`"
                    .to_string(),
            ));
            if consumed > 0 {
                skip_through = Some(lineno + consumed - 1);
            }
            continue;
        }
        if let Some(rest) = line.strip_prefix("///") {
            take_clause(&mut pending, rest.trim(), lineno + 1, false);
            continue;
        }
        // A function item: attach whatever is pending and start fresh. A
        // function with no contract is not recorded, so the set of entries is
        // exactly "the functions that carry a claim" rather than "every function
        // in the file".
        if let Some(name) = fn_name(line) {
            if !pending.requires.is_empty()
                || !pending.ensures.is_empty()
                || !pending.invariants.is_empty()
                || !pending.decreases.is_empty()
                || pending.variant.is_some()
                || pending.unwind.is_some()
                // A function carrying *only* a clause the frontend does not take
                // is still recorded, so it can be refused rather than dropped:
                // dropping it would leave the function unverified with no
                // mention, which is the same silent-loss shape `unknown` exists
                // to close.
                || !pending.unknown.is_empty()
            {
                pending.line = lineno + 1;
                let (params, ret, slots) = fn_signature_full(line);
                pending.params = params;
                pending.ret = ret;
                pending.slots = slots;
                // A method's contract is keyed by its `impl`'s location, so two
                // `impl` blocks that each declare `value` keep separate entries
                // instead of one overwriting the other.
                //
                // Anything else is keyed by its *full source path* -- the enclosing
                // `mod`/`trait`/`fn` names and its own. rustc names a definition by
                // the shortest crate-unique path suffix (`T::value` for a trait
                // default, `a::f` for a free function in `a`, `f::g` for a function
                // nested in `f`), and a bare key would (a) collide for two `mod`s
                // that each declare `f`, one silently overwriting the other (a lost
                // proof), and (b) never match a MIR name that carries the path, so
                // the contract would be dropped and the body checked against no
                // postcondition (a false proof). [`Specs::resolve`] matches the
                // full path, then a unique suffix of it.
                match enclosing.get(lineno).copied().flatten() {
                    Some(loc) => {
                        specs.by_method.insert((loc.0, loc.1, name), std::mem::take(&mut pending));
                    }
                    None => {
                        let mut path = scope_path.get(lineno).cloned().unwrap_or_default();
                        path.push(name);
                        let key = path.join("::");
                        // A *declaration* inside a `trait` (`fn f(&self) -> u8;`) is
                        // not a function: rustc emits no MIR for it, so keeping it in
                        // `by_fn` reports it `missing` forever and, worse, lets its
                        // key suffix-match an unrelated free function of the same
                        // name -- a false proof that the trait's promise was
                        // discharged. It goes to `by_trait`, where each `impl` of the
                        // trait inherits it. A trait *default* has a body, is real
                        // MIR, and stays in `by_fn` under the `T::value` key rustc
                        // prints for it.
                        let in_trait = !scopes[lineno].trait_path.is_empty();
                        if in_trait && !fn_has_body(&lines, lineno) {
                            specs.by_trait.insert(key, std::mem::take(&mut pending));
                        } else {
                            if !fn_has_body(&lines, lineno) {
                                specs.bodyless.insert(key.clone());
                            }
                            specs.by_fn.insert(key, std::mem::take(&mut pending));
                        }
                    }
                }
            }
            pending = FnContract::default();
            continue;
        }
        // Any other non-comment, non-blank line ends a doc block without a
        // function, so pending contracts are dropped rather than carried over to
        // an unrelated function further down the file.
        if !line.is_empty() && !line.starts_with('#') {
            pending = FnContract::default();
        }
    }
    // Back-insert a bare key for every struct whose bare name is unique
    // crate-wide, so a lookup by the bare tail still resolves. When two structs
    // share a bare name the bare key is *not* created: a bare-tail lookup then
    // misses, and the caller reports the layout as not modelled rather than
    // reading whichever of the two happened to be inserted last (the false proof
    // this keying exists to prevent).
    for (bare, count) in &struct_name_counts {
        if *count != 1 {
            continue;
        }
        if specs.structs.contains_key(bare) {
            continue;
        }
        if let Some(qualified) = struct_paths.get(bare) {
            if let Some(def) = specs.structs.get(qualified).cloned() {
                specs.structs.insert(bare.clone(), def);
            }
        }
    }
    specs
}

/// Does this line open an in-code contract block, `spec! { … }`?
///
/// The block is *data for the verifier*, not Rust that runs: the `spec!` macro
/// expands to nothing, so the clauses are inert at runtime and carry no symbols
/// into the artifact. Writing them here rather than in a `///` comment is the
/// difference between a contract a reader can edit only in prose and one that
/// sits next to the code it constrains -- and, more practically, a `spec!` block
/// is *checked to be syntactically valid Rust*, where a doc comment is not.
///
/// Only `spec!` is accepted, and the reason is a soundness one rather than a
/// naming preference. An earlier draft also accepted a bare `verif! { … }`, to
/// keep blocks written that way readable. But `verif` is a plausible name for a
/// *user's own* macro -- a test harness, an assertion helper -- and a macro the
/// crate did not define cannot promise to expand to nothing. Reading its
/// argument as a contract means an unrelated macro's token soup is parsed as
/// `requires:` / `ensures:` and attached to the next `fn`, which is a contract
/// the source never stated. Worse, it is the *false-proof* direction: a body of
/// `{ requires: n == 0, ensures: ret == 0 }` passed to a no-op user macro pinned
/// the precondition and **proved** a function the user never constrained. The
/// documented spelling is `spec!`; a qualified `verif::spec!` is still accepted,
/// because that path can only name this crate's macro.
///
/// **Only this crate's own paths are accepted, and that is a soundness rule, not a
/// naming preference.** The frontend reads source *text*; it cannot resolve a macro,
/// so it cannot tell a re-export of `verif::spec` from an unrelated macro that happens
/// to be called `spec`. An earlier version accepted any head ending in `::spec`, which
/// read `my_macros::spec! { requires: …, ensures: … }` as a contract -- the same
/// false-proof shape the bare `verif!` refusal exists to close, one spelling over. A
/// crate that re-exports the macro can write `verif::spec!` at the use site; losing
/// that convenience is a *lost* proof, which is the direction this crate always takes
/// over a wrong one.
fn spec_block_head(line: &str) -> Option<&str> {
    let brace = line.find('{')?;
    let head = line[..brace].trim_end();
    let head = head.strip_suffix('!').unwrap_or(head).trim_end();
    if head == "spec" || head.ends_with("::spec") {
        Some(head)
    } else {
        None
    }
}

/// Does this line open a `spec! { … }` block naming *this* crate's macro?
///
/// The accepted spellings are the bare `spec!` and the crate's own qualified path,
/// `verif::spec!` (with the edition-2018 absolute form `::verif::spec!`). Anything
/// else is refused by `is_foreign_spec_block` rather than read as clauses.
fn in_code_block_start(line: &str) -> bool {
    matches!(
        spec_block_head(line),
        Some("spec") | Some("verif::spec") | Some("::verif::spec")
    )
}

/// Does this line open a `*::spec! { … }` block that is *not* this crate's macro?
///
/// It is refused by name for the reason `in_code_block_start` gives: the frontend
/// cannot resolve the path, so it cannot know the macro expands to nothing, and
/// reading its argument as clauses would attach a contract the source never stated.
/// The caller consumes the block so its tokens do not fall through as prose, and
/// records a reason that names the fix -- a silent drop would leave the function
/// verified against `true`.
fn is_foreign_spec_block(line: &str) -> bool {
    matches!(
        spec_block_head(line),
        Some(h) if !matches!(h, "spec" | "verif::spec" | "::verif::spec")
    )
}

/// Does this line open a bare `verif! { … }` block, the spelling an earlier draft
/// accepted as a contract?
///
/// It is *not* read as a contract any more -- see `in_code_block_start` for why a
/// macro the crate does not define cannot be trusted to be a contract. The
/// question is kept as its own predicate because the caller must still *consume*
/// the block and refuse the function, rather than let the tokens fall through as
/// prose and leave the function silently unverified.
fn is_legacy_verif_block(line: &str) -> bool {
    let Some(brace) = line.find('{') else {
        return false;
    };
    let head = line[..brace].trim_end();
    let head = head.strip_suffix('!').unwrap_or(head).trim_end();
    head == "verif"
}

/// Read a `spec! { … }` block starting at `start`, returning its clauses as
/// `(line offset, clause text)` and how many lines the block spans.
///
/// Clauses are separated by top-level commas, which is the macro's own grammar:
///
/// ```text
/// spec! {
///     requires: n <= 200,
///     ensures: ret == n + 1,
/// }
/// ```
///
/// `consumed == 0` means the block never closed: the caller records that as a
/// refusal rather than reading a partial contract.
///
/// The split mirrors `macro_rules!`'s matcher on purpose. A clause body may span
/// lines (`$body:expr` allows it), so splitting per line would cut a body in half
/// -- and a truncated `ensures` is a *weaker* postcondition, which is a false
/// proof rather than a refusal. Reading the grammar the macro declares is what
/// keeps the two from diverging.
fn in_code_block(lines: &[&str], start: usize) -> (Vec<(usize, String)>, usize) {
    // The block is read as **one text**, scanned lexically, rather than per line
    // with `split_once('}')`. Three findings made the per-line version wrong, and
    // all three were silent:
    //
    // * a `}` inside a character literal (`ensures: ret == '}'`) closed the block
    //   early, truncating the clause inside the literal;
    // * a `//` comment after a clause comma was carried into the *next* clause, so
    //   that clause began with `//` and was dropped -- and a dropped `ensures:` is
    //   a false proof, not a lost one;
    // * a `}` inside a string or a block comment did the same as the char case.
    //
    // One scan fixes all three, because the same quote/comment/nesting state that
    // finds the closing brace also finds the clause commas. Two scans would be two
    // chances for them to disagree about where the block ends.
    let mut text = String::new();
    let mut origins: Vec<usize> = Vec::new();
    let mut first = true;
    let mut consumed = 0usize;
    let mut closed = false;
    'lines: for (offset, raw) in lines[start..].iter().enumerate() {
        let body = if first {
            first = false;
            match raw.split_once('{') {
                Some((_, rest)) => rest,
                None => continue,
            }
        } else {
            *raw
        };
        for ch in body.chars() {
            text.push(ch);
            origins.push(offset);
        }
        text.push('\n');
        origins.push(offset);
        consumed = offset + 1;
        // A `}` on this line may be inside a literal or a comment, so the closing
        // brace is decided by the scan, not by the line's text.
        if let Some(at) = block_close_offset(&text) {
            text.truncate(at);
            origins.truncate(at);
            closed = true;
            break 'lines;
        }
    }
    if !closed {
        return (Vec::new(), 0);
    }
    let (clauses, _) = split_clauses(&text, &origins);
    (clauses, consumed)
}

/// Replace a comment with one space, so the tokens on either side stay separate.
///
/// Only added when the piece already has content and does not end in whitespace, so
/// adjacent comments do not accumulate spaces and a leading comment does not make an
/// otherwise empty clause look non-empty.
fn push_separator(piece: &mut String, piece_start: Option<usize>) {
    if piece_start.is_some() && !piece.ends_with(char::is_whitespace) {
        piece.push(' ');
    }
}

/// Split a closed block's text into `(line offset, clause text)` pairs.
///
/// Top-level commas separate clauses -- the macro's grammar is
/// `$($clause:ident : $body:expr,)*` -- while a comma inside parentheses, brackets,
/// braces, a string, a char literal or a comment does not.
///
/// A comment is *replaced by a space*, never deleted. It is not content -- carrying
/// it into the clause made the next clause begin with `//`, so `take_clause` saw no
/// keyword and dropped it, a false proof when the dropped clause was the `ensures:`
/// -- but it *is* a token separator in Rust: `n/**/as` is the cast `n as`, and
/// deleting it glued the neighbours into the single identifier `nasu8`, a name nobody
/// wrote that a body returning an argument of that name could satisfy. The newline
/// ending a `//` comment is itself a separator and is kept.
fn split_clauses(text: &str, origins: &[usize]) -> (Vec<(usize, String)>, usize) {
    let bytes = text.as_bytes();
    let mut clauses: Vec<(usize, String)> = Vec::new();
    let mut depth = 0i32;
    // A turbofish's angle brackets nest like parentheses for the *comma* rule:
    // `max::<u8, u8>(1, 2)` has a comma inside `<>` that is not a clause separator.
    // Counting only `()[]{}` split that clause at the generic comma, so the body
    // became `ret == core::cmp::max::<u8` -- a truncated expression, which is a
    // weaker (or malformed) postcondition and therefore a false-proof shape.
    //
    // Only a `::<` opens the count, never a bare `<`: a comparison `a < b` is an
    // operator and must not start a generic list. Once inside, `<`/`>` balance so a
    // nested `Vec<u8>` counts, and a `>` that is half of `->` does not close it (a
    // `fn(u8) -> u8` is a legal generic argument).
    let mut angle = 0i32;
    let mut piece = String::new();
    let mut piece_start: Option<usize> = None;
    let mut i = 0usize;
    while i < bytes.len() {
        let ch = bytes[i];
        // Comments and literals are consumed whole, so a comma or brace inside one
        // is never a delimiter. Each branch skips to just past its construct.
        match ch {
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
                // A comment is a *token separator* in Rust: `n/**/as` is `n as`, and
                // `ret == n/**/as/**/u8` is the cast `n as u8`. Deleting the comment
                // instead of replacing it glued the neighbouring tokens into one
                // identifier (`nasu8`), so the clause named a variable nobody wrote
                // -- and a function with an argument of that name verified a
                // postcondition the source never states. One space preserves the
                // separation without changing what the clause means.
                push_separator(&mut piece, piece_start);
                continue;
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                let mut d = 1u32;
                i += 2;
                while i < bytes.len() && d > 0 {
                    if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                        d += 1;
                        i += 2;
                    } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                        d -= 1;
                        i += 2;
                    } else {
                        i += 1;
                    }
                }
                push_separator(&mut piece, piece_start);
                continue;
            }
            b'"' => {
                if piece_start.is_none() {
                    piece_start = origins.get(i).copied();
                }
                let end = skip_string(bytes, i);
                piece.push_str(&text[i..end]);
                i = end;
                continue;
            }
            b'\'' if is_char_literal_start_bytes(bytes, i) => {
                if piece_start.is_none() {
                    piece_start = origins.get(i).copied();
                }
                let end = skip_char(bytes, i);
                piece.push_str(&text[i..end]);
                i = end;
                continue;
            }
            b'r' | b'b' | b'c' => {
                if let Some((hashes, after)) = raw_string_start(bytes, i) {
                    if piece_start.is_none() {
                        piece_start = origins.get(i).copied();
                    }
                    let end = skip_raw_string(bytes, after, hashes);
                    piece.push_str(&text[i..end]);
                    i = end;
                    continue;
                }
                if piece_start.is_none() && !ch.is_ascii_whitespace() {
                    piece_start = origins.get(i).copied();
                }
                piece.push(ch as char);
                i += 1;
                continue;
            }
            _ => {}
        }
        match ch {
            b'<' if angle > 0 || is_turbofish_open(bytes, i) => {
                angle += 1;
                if piece_start.is_none() {
                    piece_start = origins.get(i).copied();
                }
                piece.push('<');
            }
            b'>' if angle > 0 && bytes.get(i.wrapping_sub(1)) != Some(&b'-') => {
                angle -= 1;
                piece.push('>');
            }
            b'(' | b'[' | b'{' => {
                depth += 1;
                if piece_start.is_none() {
                    piece_start = origins.get(i).copied();
                }
                piece.push(ch as char);
            }
            b')' | b']' | b'}' => {
                depth -= 1;
                piece.push(ch as char);
            }
            b',' if depth == 0 && angle == 0 => {
                let t = piece.trim();
                if !t.is_empty() {
                    clauses.push((piece_start.unwrap_or(0), t.to_string()));
                }
                piece.clear();
                piece_start = None;
            }
            _ => {
                if ch.is_ascii() {
                    if piece_start.is_none() && !(ch as char).is_whitespace() {
                        piece_start = origins.get(i).copied();
                    }
                    piece.push(ch as char);
                } else {
                    // A non-ASCII byte is the start of a multi-byte UTF-8 character,
                    // and every identifier Rust accepts may contain one (`µ`, `日本`).
                    // `ch as char` reads one byte as Latin-1, so `µ` (0xC2 0xB5) became
                    // `µ` -- a *different identifier* than the one written, which is a
                    // false proof when a contract names it and an argument of the
                    // mangled spelling exists. Decode the whole character instead.
                    let ch = text[i..].chars().next().unwrap_or('\u{fffd}');
                    if piece_start.is_none() && !ch.is_whitespace() {
                        piece_start = origins.get(i).copied();
                    }
                    piece.push(ch);
                    i += ch.len_utf8();
                    continue;
                }
            }
        }
        i += 1;
    }
    let t = piece.trim();
    if !t.is_empty() {
        clauses.push((piece_start.unwrap_or(0), t.to_string()));
    }
    (clauses, 0)
}

/// Is the `<` at `i` the opening of a turbofish (`::<`)?
///
/// Whitespace between the `::` and the `<` is allowed, because a clause body is an
/// expression a person wrote and rustfmt is not always run. A bare `<` is never a
/// generic opener here: `a < b` is a comparison, and treating it as one would make
/// every relational clause need a closing `>` it does not have.
fn is_turbofish_open(bytes: &[u8], i: usize) -> bool {
    let mut j = i;
    while j > 0 && bytes[j - 1].is_ascii_whitespace() {
        j -= 1;
    }
    j >= 2 && bytes[j - 1] == b':' && bytes[j - 2] == b':'
}

/// The byte offset of the block's closing `}`, ignoring braces inside literals and
/// comments. `None` while the block is still open.
///
/// The scan is the same one [`split_clauses`] runs, so the two cannot disagree about
/// where the block ends. The offset -- not a bare `bool` -- is what keeps the closing
/// brace *out* of the last clause: returning only "closed" left `ret == n + 1 }` as
/// the final clause body, which is a different expression from the one written.
fn block_close_offset(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut depth = 0i32;
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
                continue;
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                let mut d = 1u32;
                i += 2;
                while i < bytes.len() && d > 0 {
                    if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                        d += 1;
                        i += 2;
                    } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                        d -= 1;
                        i += 2;
                    } else {
                        i += 1;
                    }
                }
                continue;
            }
            b'"' => {
                i = skip_string(bytes, i);
                continue;
            }
            b'\'' if is_char_literal_start_bytes(bytes, i) => {
                i = skip_char(bytes, i);
                continue;
            }
            b'r' | b'b' | b'c' => {
                if let Some((hashes, after)) = raw_string_start(bytes, i) {
                    i = skip_raw_string(bytes, after, hashes);
                    continue;
                }
                i += 1;
                continue;
            }
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth < 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// The body of clause `keyword`, when `keyword` is exactly that identifier and a
/// colon followed it.
///
/// `keyword` and `rest` come from splitting the clause text at its first colon, so
/// `rest` is `Some` exactly when a colon was present. The keyword must be a bare
/// identifier equal to `want` -- not merely a prefix -- so `requires_extra: x` is not
/// read as a `requires:` clause.
fn body_after<'a>(keyword: &str, rest: Option<&'a str>, want: &str) -> Option<&'a str> {
    if keyword == want {
        rest
    } else {
        None
    }
}

/// Apply one clause's text to `pending`, whichever spelling produced it.
///
/// `lineno` is 1-based and used only for a diagnostic, so a refusal names the
/// line a reader can find. Both the `///` path and the in-code block go through
/// here; a second copy of this match is a second chance for the two spellings to
/// disagree about what `variant:` or an unknown clause does.
///
/// The keyword and its colon are split apart, so `requires : true` -- what a comment
/// before the colon becomes -- reads as a precondition. Rust's matcher is
/// `$clause:ident : $body:expr`, which allows that spacing.
fn take_clause(pending: &mut FnContract, text: &str, lineno: usize, from_block: bool) {
    let t = text.trim();
    if t.is_empty() {
        return;
    }
    // Split the keyword from its body at the first colon, allowing whitespace
    // between them: Rust's matcher is `$clause:ident : $body:expr`, which accepts a
    // comment (now a space) or plain spacing before the colon. Matching the literal
    // `requires:` refused `requires : true` -- valid syntax -- so a comment before
    // the colon silently dropped the clause and skipped the function.
    let (keyword, rest) = match t.split_once(':') {
        Some((k, r)) => (k.trim(), Some(r)),
        None => (t, None),
    };
    if let Some(r) = body_after(keyword, rest, "requires") {
        pending.requires.push(r.trim().to_string());
    } else if let Some(r) = body_after(keyword, rest, "ensures") {
        pending.ensures.push(r.trim().to_string());
    } else if let Some(r) = body_after(keyword, rest, "invariant") {
        pending.invariants.push(r.trim().to_string());
    } else if let Some(r) = body_after(keyword, rest, "decreases") {
        pending.decreases.push(r.trim().to_string());
    } else if let Some(r) = body_after(keyword, rest, "variant") {
        // A loop termination measure. Two would disagree, so a second is
        // recorded as an unknown clause and the function is refused -- the same
        // discipline as several `invariant:`.
        if pending.variant.is_some() {
            pending.unknown.push((
                lineno,
                format!("{t} — a second `variant:`; the first is the measure"),
            ));
        } else {
            pending.variant = Some(r.trim().to_string());
        }
    } else if let Some(r) = body_after(keyword, rest, "unwind") {
        // A loop-unwinding bound. It has to be a positive integer: a non-numeric
        // or zero value is refused rather than defaulted, so a typo cannot
        // silently fall back to `DEFAULT_UNWIND`.
        match r.trim().parse::<u32>() {
            Ok(n) if n > 0 => pending.unwind = Some(n),
            _ => pending
                .unknown
                .push((lineno, format!("{t} — `unwind:` needs a positive integer"))),
        }
    } else if let Some(note) = clause_shaped_word(t) {
        // A line that reads like a clause but is not one this frontend takes. A
        // typo (`ensuers:`) would otherwise be dropped and the function verified
        // with no postcondition at all; a `variant:` would be ignored although
        // the reader expects it honoured. Recorded and refused, never dropped.
        pending.unknown.push((lineno, format!("{t} — {note}")));
    } else if from_block && looks_like_clause(t) {
        // Inside a `spec! { … }` block every piece is *guaranteed* by the matcher
        // (`$($clause:ident : $body:expr,)*`) to be `ident : expr`, so an unknown
        // keyword here is not prose -- it is a clause the author wrote and this
        // frontend does not take. `postcondition: ret == 1` is nine edits from
        // every keyword, so the typo heuristic above does not fire, and the clause
        // was dropped silently: a function returning 0 was reported `Verified`
        // against a postcondition nobody read. A doc comment may be prose; a block
        // may not, so the block is strict.
        pending.unknown.push((
            lineno,
            format!("{t} — not a clause this frontend takes (`requires:`, `ensures:`, `invariant:`, `decreases:`, `variant:`, `unwind:`); a `spec!` block may not contain prose"),
        ));
    }
}

/// True when `t` is shaped `ident: …` -- an identifier, a colon, then a body.
///
/// This is the shape `spec!`'s matcher requires, so it distinguishes a clause the
/// author wrote from a fragment of a malformed block. It is deliberately narrower
/// than [`clause_shaped_word`]: that one guesses at typos, and this one does not
/// guess at all, because inside a block the shape is a promise rustc has kept.
fn looks_like_clause(t: &str) -> bool {
    let Some((word, body)) = t.split_once(':') else {
        return false;
    };
    let word = word.trim();
    !word.is_empty()
        && word.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
        && !body.trim().is_empty()
}

/// A note explaining why a clause-shaped doc-comment line was not taken, when
/// the line reads like a clause but is not one of the five the frontend accepts
/// (`requires:`, `ensures:`, `invariant:`, `decreases:`, `variant:`).
///
/// The shape that reaches here is a *typo*: `ensuers:` and `requiers:` are one
/// transposition from a real keyword. That is the dangerous case, because the
/// clause would otherwise be dropped and the function verified without it -- a
/// postcondition that is never checked reads as a green report. The note names
/// the keyword the line looks like.
///
/// Ordinary prose (`direction:`, `type:`) is more than two edits from every
/// keyword and is left as documentation, so a sentence that merely contains a
/// colon does not fire this.
fn clause_shaped_word(t: &str) -> Option<String> {
    const KEYWORDS: [&str; 6] =
        ["requires", "ensures", "invariant", "decreases", "variant", "unwind"];
    let word = t.split(':').next()?.trim();
    // A clause keyword is a bare identifier; anything else is prose or a value.
    if word.is_empty() || !word.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
        return None;
    }
    KEYWORDS
        .into_iter()
        .filter(|k| edit_distance_at_most_two(word, k))
        .min_by_key(|k| edit_distance(word, k))
        .map(|k| format!("did you mean `{k}:`?"))
}

/// True when `a` and `b` are within two single-character edits of each other.
///
/// A bounded Levenshtein: the band is two, so a word that differs by a typo
/// (`ensuers` vs `ensures`) is caught and a different word (`direction`) is not.
/// The bound is what keeps this from firing on prose.
fn edit_distance_at_most_two(a: &str, b: &str) -> bool {
    edit_distance(a, b) <= 2
}

/// The Levenshtein distance between two short words, saturating at 3.
fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    if a.len().abs_diff(b.len()) > 2 {
        return 3;
    }
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0usize; b.len() + 1];
    for (i, ca) in a.iter().enumerate() {
        cur[0] = i + 1;
        for (j, cb) in b.iter().enumerate() {
            let sub = prev[j] + usize::from(ca != cb);
            cur[j + 1] = sub.min(prev[j + 1] + 1).min(cur[j] + 1);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    prev[b.len()]
}

/// The parameter list and return type of an `fn` item, from its source signature.
///
/// This exists for the *callee outside the dump*: its body is not in the MIR, so
/// the `debug` bindings the executor usually reads a parameter's name from do not
/// exist, and the contract's `requires` has to be attached to an argument
/// positionally. A signature that cannot be read leaves both lists empty and the
/// call is refused, which is the safe direction: binding `requires: n <= 10` to
/// whatever argument happens to be first would prove a precondition nobody stated.
///
/// The parser is deliberately shallow. It takes the text between the parameter
/// list's parentheses and the text after `->`, splits the parameters on top-level
/// commas (so `&[u8; 4]`, `(u8, u8)` and `fn(u8) -> u8` stay whole), and reads the
/// text before each parameter's `:` as its name, dropping a leading `mut `. So
/// `mut x: u32` and `x: u32` are both `x`. Anything else before the colon -- `_`,
/// `self`, a destructuring pattern -- stops the whole list, because a positional
/// bind that is short by one would shift every later argument onto the wrong
/// parameter.
///
/// The return type is the text between `->` and the body's `{` (or a `;` for a
/// declaration), trimmed. A function with no `->` returns `()`.
/// Whether the `fn` item starting on line `start` has a body.
///
/// A trait *declaration* (`fn f(&self) -> u8;`) has none. That is what makes it a
/// promise to be inherited rather than a function to be checked: rustc emits no MIR
/// for it, so a caller that treats it as an ordinary item reports it `missing`
/// forever.
///
/// The scan stops at the first `{` or `;` reached outside line comments and outside
/// *any* bracketing, so a `;` that belongs to a bracketed type is not mistaken for
/// the declaration's own terminator. That is not hypothetical: `fn f(&self) -> [u8; 4]
/// { … }` has a `;` before its body brace, and reading it as the terminator would
/// file a *default* -- a real function with MIR -- as a bodyless declaration, so its
/// contract would be inherited by implementations instead of checked on its own
/// body. The same shape appears in `impl Trait<{ … }>` and in a parenthesised
/// argument list.
///
/// Quote characters are deliberately *not* treated as literals. A lifetime
/// (`fn f<'a>(&'a self) -> &'a u8`) looks like an opening `'` with no close, and a
/// scanner that skipped to the next `'` would swallow the closing `)` and then
/// refuse a real body as a declaration. A char or string literal in a *signature* is
/// not a shape that occurs, so the bracket depth alone is the honest rule.
///
/// Angle brackets stop counting once the first `>` returns to zero, so a later `<`
/// is the comparison operator rather than a bracket. Only the header is read, and it
/// may wrap over several lines.
fn fn_has_body(lines: &[&str], start: usize) -> bool {
    let mut angle = 0i32;
    let mut round = 0i32;
    let mut square = 0i32;
    let mut seen_angle = false;
    for raw in &lines[start..] {
        let mut line = *raw;
        if let Some(i) = line.find("//") {
            line = &line[..i];
        }
        for c in line.chars() {
            match c {
                '<' if !seen_angle => {
                    angle += 1;
                    seen_angle = true;
                }
                '<' if angle > 0 => angle += 1,
                '>' if angle > 0 => angle -= 1,
                '(' => round += 1,
                ')' => round -= 1,
                '[' => square += 1,
                ']' => square -= 1,
                '{' if angle == 0 && round <= 0 && square <= 0 => return true,
                ';' if angle == 0 && round <= 0 && square <= 0 => return false,
                _ => {}
            }
        }
    }
    false
}

#[cfg(test)]
fn fn_signature(line: &str) -> (Vec<(String, Ty)>, Option<Ty>) {
    let (params, ret, _) = fn_signature_full(line);
    (params, ret)
}

/// A source signature: `(params, return, slots)`.
///
/// The three travel together and are all derived from one line, so a named alias
/// keeps the reader's signature honest about that rather than repeating a
/// three-element tuple at each use. See [`fn_signature_full`].
type SourceSignature = (Vec<(String, Ty)>, Option<Ty>, Option<Vec<ParamSlot>>);

/// The signature reader, keeping the *positions*.
///
/// [`fn_signature`] is the call route's view: it drops a receiver, because a
/// call's argument list has none. This one keeps every slot, receiver included,
/// because the body route has to align a trait declaration's parameters with an
/// implementation's by position -- and the receiver holds one. See
/// [`FnContract::slots`].
///
/// The third component is `None` when the signature could not be read *whole*,
/// which is the only case in which a caller may not align by position.
fn fn_signature_full(line: &str) -> SourceSignature {
    let Some(open) = line.find('(') else {
        return (Vec::new(), None, None);
    };
    // The parameter list runs to its *matching* close paren, not the first one: a
    // parameter whose type is itself parenthesised (`a: (u8, u8)`) puts a `)`
    // inside the list, and stopping there would read `a: (u8, u8` as the whole
    // signature -- a list short by one parameter, which the positional bind would
    // then attach the wrong argument to. A signature that wraps onto a later line
    // is not read here, and the empty list it produces refuses the call rather
    // than binding wrongly.
    let mut depth = 0usize;
    let mut close = None;
    for (i, ch) in line[open..].char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(open + i);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(close) = close else {
        return (Vec::new(), None, None);
    };
    let mut params = Vec::new();
    let mut slots = Vec::new();
    let list = line[open + 1..close].trim();
    if !list.is_empty() {
        for part in split_top_level(list, ',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            // A receiver is a slot but names no value: `self`, `&self`,
            // `&mut self`, `mut self`. It has no `name: Type` form, so the
            // `name: Type` reader below would reject the whole signature and lose
            // every other position with it.
            if is_receiver(part) {
                slots.push(ParamSlot::Receiver);
                continue;
            }
            // `name: Type`, with an optional `mut`/`ref` before the name and a
            // pattern (`_`) in place of one.
            let Some(colon) = part.find(':') else {
                return (Vec::new(), None, None);
            };
            let before = part[..colon].trim();
            let name = before
                .strip_prefix("mut ")
                .unwrap_or(before)
                .trim()
                .to_string();
            // A pattern (`_`, `(a, b)`) has no single name to bind.
            if name.is_empty()
                || name == "_"
                || !name.chars().all(|c| c.is_alphanumeric() || c == '_')
            {
                return (Vec::new(), None, None);
            }
            params.push((name.clone(), Ty::parse(part[colon + 1..].trim())));
            slots.push(ParamSlot::Named(name));
        }
    }
    // The return type: after `->`, up to the body's `{` or the declaration's `;`.
    //
    // The terminator has to be on *this* line. A return type that wraps to the
    // next one leaves nothing between `->` and the end of the line, and reading
    // that as `Ty::Other("")` would make a signed return unsigned: a caller
    // testing `ext() < 0` would take the unsigned branch and could verify a false
    // postcondition. Refusing the whole signature is the safe answer, and it is
    // the same discipline the parameter list already follows.
    let after = &line[close..];
    let ret = match after.find("->") {
        None => None,
        Some(i) => {
            let rest = &after[i + 2..];
            match rest.find(['{', ';']) {
                Some(end) => Some(Ty::parse(rest[..end].trim())),
                // Nothing terminates the return type on this line. An empty
                // remainder is the wrapped case; a *non*-empty remainder with no
                // terminator is a header that continues on the next line.
                None => return (Vec::new(), None, None),
            }
        }
    };
    (params, ret, Some(slots))
}

/// True when a parameter is a receiver rather than a `name: Type`.
///
/// Covers `self`, `&self`, `&mut self`, `mut self`, and the `self: Box<Self>`
/// spelling, whose `:` is inside the receiver rather than after a name.
fn is_receiver(part: &str) -> bool {
    let t = part.trim();
    let t = t.strip_prefix("mut ").unwrap_or(t).trim();
    if t == "self" {
        return true;
    }
    if let Some(rest) = t.strip_prefix("&mut ") {
        return rest.trim() == "self";
    }
    if let Some(rest) = t.strip_prefix('&') {
        return rest.trim() == "self";
    }
    // `self: Box<Self>`, `self: &Self`, …
    t.split(':').next().map(|n| n.trim()) == Some("self")
}

fn fn_name(line: &str) -> Option<String> {
    let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
    let rest = t.strip_prefix("const ").unwrap_or(t).trim();
    let rest = rest.strip_prefix("async ").unwrap_or(rest).trim();
    let rest = rest.strip_prefix("unsafe ").unwrap_or(rest).trim();
    let rest = rest.strip_prefix("extern \"C\" ").unwrap_or(rest).trim();
    let rest = rest.strip_prefix("fn ")?;
    let name: String = rest
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

// ---------------------------------------------------------------------------
// Contract expression evaluation
// ---------------------------------------------------------------------------

/// Why a contract could not be turned into a predicate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpecError {
    /// The contract text that could not be read.
    pub text: String,
    /// Why it could not be read.
    pub reason: String,
}

impl SpecError {
    /// Re-point the error at the *source* contract text.
    ///
    /// The parser reads the text *after* the field rewrite, so its errors quote
    /// mangled names (`a__chain`, `c__f0`) that appear nowhere in the source.
    /// Reporting those to the user is a diagnosability bug, not just a cosmetic
    /// one: the name in the message cannot be searched for. The reason is kept as
    /// is -- it is about the rewritten form -- and only the quoted text is the
    /// source's.
    fn about(self, text: &str) -> Self {
        Self { text: text.to_string(), reason: self.reason }
    }
}

impl std::fmt::Display for SpecError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "cannot read contract `{}`: {}", self.text, self.reason)
    }
}

/// An array-typed field a contract may subscript: `o.a` in `o.a[0]`. The chain is the MIR
/// projection from the argument's base local to the array, so the executor can key the
/// element by the same path the body's write lands on.
#[derive(Clone, Debug)]
pub struct PathElem {
    /// The argument name, used to build the element's mangled variable name.
    pub arg: String,
    /// The local the argument is bound to.
    pub local: u32,
    /// The field chain from the local to the array (`[0]` for the first field).
    pub chain: Vec<u32>,
    /// The element width in bits.
    pub elem_w: u8,
    /// Whether the element is signed.
    pub elem_signed: bool,
    /// The array's length, so an index past it is refused rather than bound.
    pub len: u64,
}

/// The fields a contract may name, resolved to symbolic variables.
///
/// A contract writes `c.lo`, but the expression language knows only flat
/// identifiers. Rather than grow the grammar with a projection operator, each
/// readable field is *rewritten* to a mangled identifier (`c.lo` → `c__f0`) and
/// bound to a variable of the field's own width and signedness. The grammar stays
/// a comparison of arithmetic expressions over names, and the projection is a
/// binding decision made before parsing — one place, not one per operator.
///
/// The rewrite is textual and runs on the whole contract, so it must not fire
/// inside a longer identifier: `xs.len()` is handled separately (a length is a
/// property of the argument, not a field), and `myc.lo` must not match `c.lo`.
/// The scanner is therefore token-aware rather than a `replace`.
#[derive(Clone, Debug, Default)]
pub struct FieldEnv {
    /// Mangled name → the variable standing for that field.
    pub vars: BTreeMap<String, Var>,
    /// Which mangled names are signed, for comparison signedness.
    pub signed: BTreeSet<String>,
    /// `arg.field` → mangled name, so the rewrite can be driven by what actually
    /// exists rather than by a pattern.
    pub paths: BTreeMap<String, String>,
    /// A *nested* field path, keyed by the exact source spelling the contract
    /// writes (`o.i.v`) → the mangled name it is rewritten to.
    ///
    /// A single field is a property of the argument (`arg.field`), but a nested
    /// path is a property of the *path*: `o.i.v` and `o.i.w` share the outer
    /// projection `o.i` and differ only in the inner field. So the binding is
    /// keyed by the whole dotted spelling, and the rewrite matches the longest
    /// prefix that exists. The key is the source spelling because that is what the
    /// scanner has in hand; the value is the variable the path names, seeded into
    /// the executor's `nested` store under the same projection chain, so the
    /// contract's `o.i.v` and the body's `(((*_1).0).0)` are one input rather than
    /// two that look alike.
    pub nested_paths: BTreeMap<String, String>,
    /// The argument names that are aggregates *with a readable layout*, used only
    /// to *diagnose* a nested path that walks off the layout: `o.i` where `i` is a
    /// scalar, or `o.nope.v`. A name here that is followed by a dotted path with no
    /// binding gets a message naming the segment rather than a parser error about
    /// the `.` it cannot reduce.
    pub aggregate_args: BTreeSet<String>,
    /// The argument names known to be aggregates. Used only to *diagnose*: a
    /// contract naming `c.lo` where `c` is a struct but `lo` is not a field gets
    /// "unknown field `lo`" rather than a parser error about the `.` it cannot
    /// reduce. Both refuse; one says why.
    pub known_args: BTreeSet<String>,
    /// The first variable slot this environment may use. It is one past the
    /// highest local the function declares, so a field variable can never take an
    /// index a local already holds.
    ///
    /// A *fixed* base would be a soundness assumption about the input ("no
    /// function has 200 locals"). Two variables at one index is not a missing
    /// proof but a wrong one, so the base is derived from the function instead of
    /// assumed about it. If the fields do not fit below `MAX_VARS`, the field is
    /// refused rather than aliased.
    base: u32,
    /// How many fields have been bound, which is also the next variable slot.
    next_slot: u32,
    /// Base slot for `ret.N` bindings, so they cannot collide with argument
    /// field slots. The return value's own variable is allocated by the caller
    /// (it is a real local), so only the *projections* get slots here.
    next_ret_slot: u32,
    /// `(local, field index, variable)` for each bound field.
    ///
    /// The executor reads `_1.0` out of its own `fields` map, so the *same*
    /// variable the contract names as `c.lo` has to be seeded there under
    /// `(_1, 0)`. If the two disagreed, the contract would be about one symbolic
    /// input and the body about another, and every proof would be vacuous in the
    /// direction that matters. These seeds are how the two are made to agree by
    /// construction rather than by convention.
    /// The `bool` is the field's signedness, carried here so the executor can
    /// build a `Val::Sym` that *knows* its sign. A seed without one would force
    /// the executor to guess, which is the bug class this closes.
    pub seeds: Vec<(u32, u32, Var, bool)>,
    /// `(local, projection chain, variable, signed)` for each *nested* path a
    /// contract names, so the executor's nested store holds the same variable the
    /// contract's `o.i.v` was rewritten to.
    ///
    /// The chain is the MIR projection from the argument's base local: for `o.i.v`
    /// it is `[Field(0), Field(0)]`, and the executor seeds `((local, 0), 0)`. The
    /// chain is stored rather than a single index because a nested path is a walk,
    /// not a field: the executor has to place the value at the *end* of the walk,
    /// and the walk's shape is what makes `o.i.v` a different input from `o.j.v`.
    pub nested_seeds: Vec<(u32, Vec<u32>, Var, bool)>,
    /// `(local, fixed length)` for each *array* argument, so the executor can
    /// enumerate the domain a symbolic subscript needs. A slice has no entry:
    /// there is no fixed domain, so its `xs[i]` stays refused.
    pub array_lens: Vec<(u32, u64)>,
    /// `(local, length variable, element width)` for each slice or array
    /// argument.
    ///
    /// A slice has no length in its type, so the length is a symbolic input, and
    /// `xs.len()` in a contract and `PtrMetadata(_1)` in the body must name the
    /// same one. An array's length *is* in its type, so there it is the constant
    /// `N`, and the contract's `a.len()` and the body's `const N_usize` agree by
    /// being the same word. This is the indexed analogue of `seeds`.
    pub len_seeds: Vec<(u32, Var, u8, bool)>,
    /// `(local, index, element variable)` for each slice or array element the
    /// contract names. The body's `(*_1)[0]` reads the same variable, so `xs[0]`
    /// in a contract and `xs[0]` in the body are one value, not two that look
    /// alike.
    pub elem_seeds: Vec<(u32, u64, Var, bool)>,
    /// `(local, field chain, index, variable, signed)` for each element of an array
    /// reached through a *field path* (`o.a[0]`) that a contract names.
    ///
    /// Separate from [`elem_seeds`](Self::elem_seeds) because the executor keys these by the
    /// whole path: `o.a[0]` and `o.b[0]` are different words, and a store keyed by the local
    /// and index alone would collide them.
    pub path_elem_seeds: Vec<(u32, Vec<u32>, u64, Var, bool)>,
    /// `path -> array-field layout` for every array-typed field a contract may subscript
    /// (`o.a` in `o.a[0]`): the argument name, the local, the field chain to the array, the
    /// element width and signedness, and the array's length.
    pub path_elem_types: BTreeMap<String, PathElem>,
    /// `(local, tag variable, tag width, discriminants)` for each enum-typed
    /// argument.
    ///
    /// An enum argument has no bit width of its own, but its *tag* does, and the
    /// tag is the only thing a contract can say about an enum without naming a
    /// variant. It is a symbolic input whose domain is the set of variant
    /// discriminants — a fact about the type, so the run may assume it. The
    /// discriminants travel with the seed rather than a variant count, because
    /// `tag < count` is only the same domain when the numbering is `0..count`,
    /// which an explicit discriminant (`B = 3`) breaks. Seeding the tag here is
    /// what makes the contract's `m` and the body's `discriminant(_1)` one
    /// variable.
    pub tag_seeds: Vec<(u32, Var, u8, Vec<u64>)>,
    /// `(local, variant, variable, width, signed)` for each variant payload.
    ///
    /// A payload is a symbolic input like any other: the frontend cannot know what
    /// the caller put in it, so assuming a relation would be unsound. Seeding it
    /// means the body's `((_1 as Data).0)` and a contract's `m.Data` name one
    /// variable rather than two that look alike.
    pub payload_seeds: Vec<(u32, u64, Var, u8, bool)>,
    /// `Enum::Variant` → `(discriminant, tag width)`, so a contract can write
    /// `m == Mode::Idle` and have it mean the tag equals that variant's index.
    /// A name not in here is refused, which keeps a misspelled variant from being
    /// read as an unrelated integer.
    pub variant_consts: BTreeMap<String, (u64, u8)>,
    /// Named `const` items, name → the value rustc printed for them.
    ///
    /// A contract may name a constant the way the body does (`requires: x <=
    /// LIMIT`), and the name has to resolve to the same value the body reads at its
    /// use site. This is the *same table* the executor folds a body's `const LIMIT`
    /// from (`MirProgram::consts`), so the contract and the body cannot disagree:
    /// there is one value, read once by rustc.
    ///
    /// A name that is *not* here is refused rather than guessed at, which keeps a
    /// misspelled constant from being read as an argument that does not exist, or
    /// as zero. Only a constant whose printed body is a literal is in the table, so
    /// a constant built by an expression is refused too -- its value is in its own
    /// body, not in a declaration the reader can fold.
    pub consts: BTreeMap<String, Const>,
    /// `arg.Variant` → the mangled payload name, so a contract can name a payload
    /// the way the body's downcast reads it.
    pub payload_paths: BTreeMap<String, String>,
    /// The names of enum-typed arguments, for diagnostics: a contract naming
    /// `m.Nope` where `Nope` is not a variant gets a message about the variant.
    pub enum_args: BTreeSet<String>,
    /// `(tag variable, success discriminant, failure discriminant)` for an
    /// enum-returning function, so a contract can write `ret.is_ok()` /
    /// `ret.is_some()` / `ret.is_err()` / `ret.is_none()`.
    ///
    /// Kept apart from the bare `ret` binding on purpose: the *tag* is a value, but
    /// it is not the enum's value, so a bare `ret <= n` on an enum return stays a
    /// refusal (the return has no single word) rather than silently comparing the
    /// discriminant. Only the four methods -- which say what they test -- read the
    /// tag.
    pub ret_enum_tags: Option<(Var, u64, u64)>,
    /// `ret.<Variant>` → the discriminant the payload belongs to, so a contract
    /// clause that names a return payload is guarded on the tag.
    ///
    /// Keyed by the *mangled* variable name the rewrite emits (`ret__v_Ok`), because
    /// that is what the parser sees once `rewrite_fields` has run. A payload exists
    /// only on the variant's paths, so the parser wraps the clause containing it in
    /// `tag == discriminant` -- the guard travels with the *binding*, not with the
    /// spelling, so a contract that mentions `ret.Ok` anywhere gets the same
    /// treatment.
    pub ret_payload_guards: BTreeMap<String, (Var, u64)>,
    /// Indexed arguments (slices and arrays): name → (local, element width, the
    /// array's fixed length if it is one), so a contract's `xs.len()` and `xs[0]`
    /// can be bound without the IR's `Ty` in hand.
    ///
    /// The length is `Some(n)` for an array and `None` for a slice, which is what
    /// lets a contract naming `a[9]` on a `[u8; 4]` be refused as out of range
    /// rather than bound to a fresh variable for an element that does not exist.
    indexed: BTreeMap<String, (u32, u8, Option<u64>, bool)>,
    /// `arg -> index variable` for an array argument a contract subscripts with a
    /// *symbolic* index (`a[i]`).
    ///
    /// An array has a finite domain, so a symbolic subscript can be *modelled*
    /// rather than refused: `a[i]` becomes the ite chain over `0..N`, which is
    /// exact. The index variable is a fresh input, and the chain is built by the
    /// parser from the element variables in [`elem_seeds`](Self::elem_seeds) so
    /// the contract's `a[i]` and the body's `a[i]` are the same expression.
    ///
    /// A *slice* gets no entry: its length is a symbolic input, so there is no
    /// finite domain to enumerate and `xs[i]` stays a refusal. That is the honest
    /// boundary -- an array's length is in its type, a slice's is not.
    sym_index: BTreeMap<String, Var>,
    /// `arg -> every index spelling` for an array a contract subscripts
    /// symbolically, so the rewrite can tell `a[i]` (which has a chain) from
    /// `a[j]` (which does not) instead of rewriting both to the same chain.
    ///
    /// A *set*, not one name: one index variable can be spelled more than once —
    /// `a[i]` and `a[k]` where `let k = i`, or the same name twice — and every
    /// spelling of the bound index names the same element, so every spelling has
    /// to rewrite to the same chain. Keeping only the first left the second
    /// subscript unrewritten and the whole contract unreadable, which skipped a
    /// function that should have verified.
    sym_index_names: BTreeMap<String, BTreeSet<String>>,
    /// `arg -> the ite chain` for an array a contract subscripts symbolically.
    ///
    /// Built once by [`bind_sym_index`](Self::bind_sym_index) from the element
    /// variables, so the rewrite can replace `a[i]` with a *name* the parser
    /// resolves, and the chain is the same term every time it is used. An array
    /// argument has no variable of its own (its type has no bit width), so
    /// without this the parser would refuse `a` as an unknown name.
    sym_chain: BTreeMap<String, Var>,
    /// `arg -> the bound its chain is valid under` for an array or slice a
    /// contract subscripts symbolically.
    ///
    /// An array's bound is its type length; a slice's is its length *variable*,
    /// which is symbolic, so the chain is exact only under `len <=
    /// MAX_INDEX_CHAIN`. The caller turns this into the obligations the
    /// precondition must establish, and the executor takes the same bound so its
    /// own chain covers the same range the contract's does.
    sym_bound: BTreeMap<String, IndexBound>,
    /// Every *source* name in scope: the argument names.
    ///
    /// The bindings above are named by mangling (`a__len`, `c__f0`,
    /// `a__chain`), and those names are handed to the parser alongside the
    /// arguments. If a real argument happens to be called `a__chain`, the
    /// generated binding would shadow it: `eval_requires` extends the argument
    /// names with the generated ones, so the later insert wins and a contract
    /// naming that argument silently reads the array's chain instead. That is a
    /// false proof, not a parse error. Every generated name is therefore checked
    /// against this set before it is inserted, and the binding is refused rather
    /// than allowed to shadow an argument.
    declared: BTreeSet<String>,
}

impl FieldEnv {
    /// An environment carrying only a `const` table, for evaluating a contract
    /// that names a constant but binds no fields.
    ///
    /// A constant's value does not depend on the call site, so the table is the
    /// entry state's, not a fresh one; this is the constructor for the places
    /// (a recursive call) that need the constants without the field bindings.
    pub fn with_consts(consts: BTreeMap<String, Const>) -> FieldEnv {
        FieldEnv { consts, ..FieldEnv::default() }
    }

    /// Whether `name` may be introduced as a generated binding.
    ///
    /// It may not when a *source* name already holds it: the generated binding is
    /// inserted after the arguments when a contract is parsed, so a collision
    /// would let the generated value shadow the argument and a contract naming
    /// that argument would be checked against the wrong input.
    fn name_is_free(&self, name: &str) -> bool {
        !self.declared.contains(name)
    }

    /// Bind a field of an argument to a variable.
    ///
    /// The slot is handed out sequentially, not derived from a hash of the path.
    /// A hash can collide, and two fields sharing a variable is not a missing
    /// proof but a *wrong* one — `c.lo <= c.hi` would become `x <= x`. A counter
    /// cannot collide, so there is nothing to argue about.
    pub fn bind(&mut self, local: u32, arg: &str, field: &str, index: u32, ty: &Ty) -> Option<()> {
        self.bind_bits(local, arg, field, index, ty.width()?, ty.is_signed())
    }

    /// Record that `name` is an aggregate argument, so a contract naming a field
    /// it does not have gets a message about the field rather than about the dot.
    pub fn declare_arg(&mut self, name: &str) {
        self.known_args.insert(name.to_string());
        self.declared.insert(name.to_string());
    }

    /// `bind` by width and signedness, for callers outside the crate that
    /// cannot name the IR's `Ty`.
    ///
    /// This is the primitive; `bind` is the typed wrapper. Keeping the IR
    /// internal is deliberate (see the module docs), so the public entry point
    /// takes a width rather than a `Ty` and does not leak the parse tree.
    pub fn bind_bits(
        &mut self,
        local: u32,
        arg: &str,
        field: &str,
        index: u32,
        w: u8,
        signed: bool,
    ) -> Option<()> {
        if !(1..=64).contains(&w) {
            return None;
        }
        // A field is a distinct symbolic input from the argument's own variable.
        // `var_named` keys on the *local index*, so a field needs an index no
        // local of this function can use; the base is past the range rustc prints
        // for these corpora and `var_named` refuses anything at or above
        // `MAX_VARS`, which keeps a very large field count a refusal rather than
        // an alias.
        let slot = self.base + self.next_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        let mangled = format!("{arg}__f{index}");
        if !self.name_is_free(&mangled) {
            return None;
        }
        self.next_slot += 1;
        let v = smt::var_named(slot, w);
        self.vars.insert(mangled.clone(), v);
        self.seeds.push((local, index, v, signed));
        if signed {
            self.signed.insert(mangled.clone());
        }
        self.paths.insert(format!("{arg}.{field}"), mangled);
        self.known_args.insert(arg.to_string());
        Some(())
    }

    /// Bind a *nested* field path (`o.i.v`) to a fresh variable of the leaf
    /// field's width and signedness.
    ///
    /// `chain` is the MIR projection from the argument's base local to the leaf:
    /// for `o.i.v` it is `[0, 0]`, and the executor seeds the value at
    /// `((local, 0), 0)`. The whole chain is the identity of the input, because
    /// `o.i.v` and `o.j.v` are different words: the mangled name is derived from
    /// the chain, not from the leaf name, so the two cannot collide even though
    /// both end in `.v`.
    ///
    /// Every intermediate segment must itself be a *struct or tuple* with a
    /// readable layout. A segment that is a scalar, a reference, or an unknown
    /// type stops the walk, and the path is refused -- binding a fabricated word
    /// for `o.i` where `i` is a `u8` would let a contract about a field that does
    /// not exist be proved.
    pub fn bind_nested(&mut self, local: u32, arg: &str, path: &str, chain: &[u32], ty: &Ty) -> Option<()> {
        let w = ty.width()?;
        let slot = self.base + self.next_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        // The mangled name is the chain, so `o.i.v` and `o.j.v` differ even though
        // they share the leaf name. `__n` marks it as nested, keeping it distinct
        // from the single-field `__f` form for the same local.
        let mangled = format!(
            "{arg}__n{}",
            chain.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("_")
        );
        if !self.name_is_free(&mangled) {
            return None;
        }
        self.next_slot += 1;
        let v = smt::var_named(slot, w);
        self.vars.insert(mangled.clone(), v);
        if ty.is_signed() {
            self.signed.insert(mangled.clone());
        }
        self.nested_seeds.push((local, chain.to_vec(), v, ty.is_signed()));
        self.nested_paths.insert(path.to_string(), mangled);
        self.aggregate_args.insert(arg.to_string());
        self.known_args.insert(arg.to_string());
        Some(())
    }

    /// Bind an element of an array reached through a field path, `o.a[k]`.
    ///
    /// The key is the whole path -- the local, the field chain, the index -- so `o.a[0]` and
    /// `o.b[0]` are different words and cannot be confused. The mangled name embeds the chain,
    /// which is what keeps the two apart. An index past the array's declared length is refused
    /// rather than bound: the element does not exist, and a fresh variable there would make a
    /// meaningless precondition look real.
    pub fn bind_path_elem(&mut self, path: &str, index: u64) -> Option<Var> {
        let PathElem { arg, local, chain, elem_w, elem_signed, len } =
            self.path_elem_types.get(path)?.clone();
        if !(1..=64).contains(&elem_w) || index >= len {
            return None;
        }
        // The mangled name is built from the *chain*, not the dotted path: a `.` in a
        // generated name would be read by the parser as a field access, and the rewrite
        // hands the name to the parser verbatim. The chain keeps `x.a[0]` and `x.b[0]`
        // distinct even though both end in `.a`/`.b` of the same local.
        let mangled = format!(
            "{arg}__pe{}_e{index}",
            chain.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("_")
        );
        if let Some(v) = self.vars.get(&mangled) {
            return Some(*v);
        }
        if !self.name_is_free(&mangled) {
            return None;
        }
        let slot = self.base + self.next_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        self.next_slot += 1;
        let v = smt::var_named(slot, elem_w);
        self.vars.insert(mangled.clone(), v);
        if elem_signed {
            self.signed.insert(mangled.clone());
        }
        self.paths.insert(format!("{path}[{index}]"), mangled);
        self.path_elem_seeds.push((local, chain, index, v, elem_signed));
        Some(v)
    }

    /// Bind every nested field path a contract may name on an argument.
    ///
    /// `arg` is the source name, `ty` the argument's type (already read through a
    /// reference), and `structs` the declared layouts. The walk is depth-first over
    /// the fields whose type is itself a struct or tuple with a readable layout, so
    /// `o.i.v` is bound when `o.i` is a struct and `v` is a scalar leaf. A segment
    /// whose type has no layout -- a scalar, a reference, an unknown name -- ends
    /// that branch: the path is not bound, so a contract naming it is *refused*
    /// rather than bound to a fabricated word.
    ///
    /// Only paths of depth >= 2 are bound here: a single field is already bound by
    /// [`bind`](Self::bind), and binding it again under a second name would give one
    /// source field two variables.
    ///
    /// Depth is bounded by the type, not by a constant: a *recursive* type would
    /// make the walk unbounded, so the chain of type names on the current branch is
    /// kept and a type already on it stops the descent. The guard is the branch, not
    /// a global set, so two fields of the same type are both walked.
    pub fn bind_nested_paths(
        &mut self,
        local: u32,
        arg: &str,
        ty: &Ty,
        structs: &BTreeMap<String, StructDef>,
    ) {
        let mut w = NestedWalk { local, arg, structs, on_path: Vec::new() };
        self.walk_nested(&mut w, arg, &[], ty);
    }

    fn walk_nested(
        &mut self,
        w: &mut NestedWalk<'_>,
        prefix: &str,
        chain: &[u32],
        ty: &Ty,
    ) {
        // The fields of this aggregate, in field order, which *is* the MIR index.
        let fields: Vec<(String, Ty)> = match ty {
            Ty::Other(name) => match struct_lookup(w.structs, name) {
                Some(def) => def.fields.clone(),
                None => return,
            },
            Ty::Tuple(ts) => {
                ts.iter().enumerate().map(|(i, t)| (i.to_string(), t.clone())).collect()
            }
            _ => return,
        };
        if let Ty::Other(name) = ty {
            if w.on_path.iter().any(|n| n == name) {
                return;
            }
            w.on_path.push(name.clone());
        }
        for (index, (fname, fty)) in fields.iter().enumerate() {
            let mut child = chain.to_vec();
            child.push(index as u32);
            let path = format!("{prefix}.{fname}");
            // A leaf with a bit width is the value a contract can compare. An
            // aggregate is *not* bound (it has no single word) but is descended
            // into, so its scalar fields are reachable as deeper paths.
            if child.len() >= 2 && fty.width().is_some() {
                self.bind_nested(w.local, w.arg, &path, &child, fty);
            }
            // An array at any depth is subscriptable: `o.i.a[0]`. The first-level
            // pass only reaches `x.a`, so a nested array is recorded here with the
            // full chain the executor keys its element store by.
            if let Ty::Array(elem, n) = fty {
                if let Some(ew) = elem.width() {
                    self.path_elem_types.insert(
                        path.clone(),
                        PathElem {
                            arg: w.arg.to_string(),
                            local: w.local,
                            chain: child.clone(),
                            elem_w: ew,
                            elem_signed: elem.is_signed(),
                            len: *n,
                        },
                    );
                }
            }
            if matches!(fty, Ty::Other(_) | Ty::Tuple(_)) {
                self.walk_nested(w, &path, &child, fty);
            }
        }
        if matches!(ty, Ty::Other(_)) {
            w.on_path.pop();
        }
    }

    /// Bind an enum-typed argument: its tag, and each variant's payloads.
    ///
    /// The tag is the only thing a contract can compare against a variant, so it
    /// is always bound when the enum's layout is known. The payloads are bound
    /// too, so `m.Data` in a contract names the same input the body's downcast
    /// reads. A payload whose type has no bit width (a nested enum, a reference)
    /// is skipped, and a contract naming it is then refused rather than bound to
    /// a fabricated word.
    ///
    /// The tag's width is the *discriminants'*, not the dump's `isize`: the
    /// `switchInt` compares it against the variant constants, so the width only
    /// has to hold them. Using the discriminants' width keeps the tag and the
    /// payload in a width that `discriminant` reads back consistently.
    pub fn bind_enum(
        &mut self,
        local: u32,
        arg: &str,
        enum_name: &str,
        def: &EnumDef,
    ) -> Option<()> {
        if def.variants.is_empty() {
            return None;
        }
        // The tag needs enough bits for the *largest discriminant*, which an
        // explicit value can push past the variant count: `A, B = 3, C` needs
        // three bits for `4`, not the two a count of three would give.
        let width = def.tag_width();
        let tag_slot = self.base + self.next_slot;
        if tag_slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        let tag_name = format!("{arg}__tag");
        if !self.name_is_free(&tag_name) {
            return None;
        }
        self.next_slot += 1;
        let tag = smt::var_named(tag_slot, width);
        self.vars.insert(tag_name, tag);
        // The argument's own name is the tag, so `m == Mode::Idle` reads the tag
        // without a projection. Bound after the tag variable exists so the two are
        // the same word.
        self.vars.insert(arg.to_string(), tag);
        // The seeds carry the width and the *discriminant list*, because the
        // executor has to assume exactly the tag's domain -- a disjunction of the
        // real discriminants, not a `0..count` bound.
        let discs: Vec<u64> = def.variants.iter().map(|(_, _, d)| *d).collect();
        self.tag_seeds.push((local, tag, width, discs));
        self.enum_args.insert(arg.to_string());
        for (vname, payload, d) in def.variants.iter() {
            // The variant name is a constant of the tag's width, holding the
            // *discriminant* rustc assigned -- the same number a `match` arm
            // compares against. Numbering by position here is what put a contract
            // and an arm in disagreement.
            self.variant_consts.insert(format!("{enum_name}::{vname}"), (*d, width));
            self.variant_consts.insert(format!("{arg}::{vname}"), (*d, width));
            // A payload: `m.Data` is field 0 of variant `Data`. Only the first
            // payload is bound, because the MIR downcast this frontend models
            // reads `.0`; a second field would need a tuple projection the
            // executor does not carry for payloads.
            let Some(first) = payload.first() else { continue };
            let Some(w) = first.width() else { continue };
            let slot = self.base + self.next_slot;
            if slot as usize >= crate::smt::MAX_VARS {
                continue;
            }
            let mangled = format!("{arg}__v{d}_0");
            if !self.name_is_free(&mangled) {
                continue;
            }
            self.next_slot += 1;
            let v = smt::var_named(slot, w);
            self.vars.insert(mangled.clone(), v);
            // Keyed by the *discriminant*, because that is what a `Downcast`
            // projection carries: the executor stores and reads payloads under the
            // same number, and a positional key would not match a variant after an
            // explicit discriminant.
            self.payload_seeds.push((local, *d, v, w, first.is_signed()));
            if first.is_signed() {
                self.signed.insert(mangled.clone());
            }
            self.payload_paths.insert(format!("{arg}.{vname}"), mangled);
        }
        Some(())
    }
}


impl FieldEnv {
    /// Bind `ret.N` to a variable, for a postcondition that names a component of
    /// a tuple return.
    ///
    /// Unlike an argument field, the variable here is not fresh: it is whatever
    /// the executor holds for element `N` of the return place, so the contract's
    /// `ret.0` and the body's `_0.0` are the same value. `slot` is only used by
    /// the up-front parse probe, which needs *some* variable of the right width
    /// and does not care which.
    pub fn bind_ret(&mut self, index: u32, ty: &Ty, v: Var) -> Option<()> {
        // The component's own type decides. A `&T` component is *not* read
        // through to its referent here, because the executor seeds a scalar `&T`
        // argument as `Unknown` (`Ty::width` is `None` for `Ref`), so a `ret.1`
        // of type `&u8` has no value to bind. Reading through would make the probe
        // accept a component the run then cannot resolve -- the probe exists to
        // refuse exactly what the run would refuse, so it must refuse here too.
        ty.width()?;
        let mangled = format!("ret__f{index}");
        self.vars.insert(mangled.clone(), v);
        if ty.is_signed() {
            self.signed.insert(mangled.clone());
        }
        self.paths.insert(format!("ret.{index}"), mangled);
        Some(())
    }

    /// Record an enum return's tag and discriminants, so a contract can write
    /// `ret.is_ok()` / `ret.is_some()` / `ret.is_err()` / `ret.is_none()`.
    ///
    /// `is_ok`/`is_some` test the *success* variant (`Ok` is 0, `Some` is 1) and
    /// `is_err`/`is_none` the *failure* one. The tag is a value on every path (the
    /// executor passes it as the return word), so the four are total; a contract
    /// that writes them on a non-enum return is refused, because the tag they would
    /// test does not exist.
    ///
    /// A bare *payload* read (`ret.Ok <= n`) is bound separately, by
    /// [`bind_ret_payload`](Self::bind_ret_payload): it is meaningful only on the
    /// paths whose tag is that variant, so the clause it appears in is guarded on
    /// the discriminant rather than read on the wrong path.
    pub fn bind_ret_enum(&mut self, tag: Var, success: u64, failure: u64) {
        self.ret_enum_tags = Some((tag, success, failure));
    }

    /// Bind a *payload* of an enum return to a variable, so a contract can write
    /// `ret.Ok <= n` / `ret.Some <= n`.
    ///
    /// A payload is meaningful only on the paths whose tag is that variant, so the
    /// binding records the guard (`tag == discriminant`) beside the variable: the
    /// postcondition is then required only where the payload exists, and a path
    /// that returns the *other* variant makes the clause vacuous rather than
    /// checking the payload against a value it does not have. Binding the payload
    /// with no guard would compare it on every path -- a wrong value, not a weaker
    /// proof.
    ///
    /// The variable is the executor's, not a fresh one, so the contract's
    /// `ret.Ok` and the body's `((_0 as Ok).0)` name one value.
    pub fn bind_ret_payload(&mut self, vname: &str, var: Var, tag: Var, disc: u64, signed: bool) {
        let mangled = format!("ret__v_{vname}");
        // The generated name must not shadow a source name. `eval_ensures` merges
        // the field bindings *after* the arguments, so an argument literally named
        // `ret__v_Ok` would be replaced by the payload binding -- and
        // `ensures: ret.Ok == ret__v_Ok` then compares the payload with itself and
        // is *verified* for every argument value. Every other generated binding is
        // checked against `declared`; this one was inserted unconditionally, so it
        // is checked here too. On a collision the binding is dropped, and the
        // parser refuses `ret.Ok` as a name the return type does not have -- a
        // refusal, never a proof against the wrong value.
        if !self.name_is_free(&mangled) {
            return;
        }
        self.vars.insert(mangled.clone(), var);
        // `ret.Ok` and its alias `result.Ok` name the same value, so both rewrite
        // targets are recorded; the parser accepts either spelling of the return.
        self.paths.insert(format!("ret.{vname}"), mangled.clone());
        self.paths.insert(format!("result.{vname}"), mangled.clone());
        if signed {
            self.signed.insert(mangled.clone());
        }
        self.ret_payload_guards.insert(mangled, (tag, disc));
    }

    /// Bind the return payloads a contract *names*, for the parse probe.
    ///
    /// Only the named variants are bound, so a contract that never mentions a
    /// payload does not pay for one, and a payload whose type has no bit-vector
    /// width (`Ok(&u8)`) is refused only when a contract actually asks for it. The
    /// variable is throwaway (the probe discards its result); it only has to be the
    /// right width for the comparison to be well-formed.
    pub fn probe_ret_payloads(
        &mut self,
        ret_ty: &Ty,
        enums: &BTreeMap<String, EnumDef>,
        tag: Var,
        ensures: &[String],
    ) {
        let Some(def) = ret_enum_def(ret_ty, enums) else { return };
        for (vname, payload, disc) in &def.variants {
            let Some(first) = payload.first() else { continue };
            let Some(w) = first.width() else { continue };
            let named = ensures
                .iter()
                .any(|e| names_ret_variant(e, vname));
            if !named {
                continue;
            }
            let slot = self.base + self.next_slot + self.next_ret_slot;
            if slot as usize >= crate::smt::MAX_VARS {
                continue;
            }
            self.next_ret_slot += 1;
            let v = smt::var_named(slot, w);
            self.bind_ret_payload(vname, v, tag, *disc, first.is_signed());
        }
    }

    /// A fresh variable for an enum return's *tag*, for the parse probe only.
    ///
    /// Allocated above every slot the run will use -- the locals (`0..base`) and
    /// the argument field/tag slots (`base..base+next_slot`) -- so the probe's
    /// throwaway tag can never collide with a variable the run declares. A
    /// collision at a *different width* is what `var_named` refuses, and it would
    /// poison the whole arena and turn every obligation `Unknown`; a slot past the
    /// run's own allocation is what makes the probe free rather than harmful.
    pub fn probe_ret_enum_slot(&mut self, width: u8) -> Option<Var> {
        let slot = self.base + self.next_slot + self.next_ret_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        self.next_ret_slot += 1;
        Some(smt::var_named(slot, width.clamp(1, 64)))
    }

    /// A fresh variable for the `index`-th return projection, for the parse probe.
    ///
    /// Only called for a component a contract actually *names* (see
    /// [`named_ret_components`]). Binding every declared component instead made a
    /// `(u8, &u8)` return unprobeable -- component 1 is a reference with no
    /// bit-vector width -- so the whole function was skipped for a component no
    /// contract asked about, even when the contract only mentioned `ret.0`.
    pub fn probe_ret_slot(&mut self, index: u32, ty: &Ty) -> Option<Var> {
        let w = ty.width()?;
        // Past the field slots, so a return component and an argument field never
        // share an index.
        let slot = self.base + self.next_slot + self.next_ret_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        self.next_ret_slot += 1;
        let v = smt::var_named(slot, w);
        self.bind_ret(index, ty, v)?;
        Some(v)
    }

    /// Bind a slice argument's length to a fresh symbolic variable.
    ///
    /// `xs.len()` has no constant value — the length is whatever the caller
    /// passed — so it is an input, exactly like the elements. The same variable
    /// is handed to the executor as a `len_seed`, which is what makes the
    /// contract's `xs.len()` and the body's `PtrMetadata(_1)` one value.
    pub fn bind_indexed_len(
        &mut self,
        local: u32,
        arg: &str,
        elem_w: u8,
        elem_signed: bool,
    ) -> Option<Var> {
        // `elem_w == 0` is the unmodelled-width sentinel (a generic `&[T]`): the
        // length is still a value, so it is bound, but no element can be, which is
        // what keeps `v.len()`/`v.is_empty()` answerable while `v[0]` stays refused.
        if elem_w != 0 && !(1..=64).contains(&elem_w) {
            return None;
        }
        let len_name = format!("{arg}__len");
        if !self.name_is_free(&len_name) {
            return None;
        }
        let slot = self.base + self.next_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        self.next_slot += 1;
        let v = smt::var_named(slot, USIZE_WIDTH);
        self.vars.insert(len_name, v);
        self.paths.insert(format!("{arg}.len()"), format!("{arg}__len"));
        self.indexed.insert(arg.to_string(), (local, elem_w, None, elem_signed));
        self.len_seeds.push((local, v, elem_w, elem_signed));
        self.known_args.insert(arg.to_string());
        Some(v)
    }

    /// Bind an array argument's length to its *constant*, `N`.
    ///
    /// Unlike a slice, an array's length is part of its type, so `a.len()` is the
    /// constant `N` and not an input: there is nothing for the caller to choose.
    /// Binding it to a fresh variable would be the unsound direction — it would
    /// admit lengths the type excludes, so a contract proved at length 4 would
    /// claim to hold at any length.
    pub fn bind_array_len(
        &mut self,
        local: u32,
        arg: &str,
        elem_w: u8,
        elem_signed: bool,
        n: u64,
    ) -> Option<()> {
        if !(1..=64).contains(&elem_w) {
            return None;
        }
        let len_name = format!("{arg}__len");
        if !self.name_is_free(&len_name) {
            return None;
        }
        let v = smt::word(n, USIZE_WIDTH);
        self.vars.insert(len_name, v);
        self.paths.insert(format!("{arg}.len()"), format!("{arg}__len"));
        self.indexed.insert(arg.to_string(), (local, elem_w, Some(n), elem_signed));
        self.len_seeds.push((local, v, elem_w, elem_signed));
        self.array_lens.push((local, n));
        self.known_args.insert(arg.to_string());
        Some(())
    }

    /// Bind one element of a slice or array argument to a fresh symbolic variable.
    ///
    /// `xs[k]` is a distinct input per index — two indices are two variables, so
    /// `xs[0] == xs[1]` is not provable — and the same index twice is the same
    /// variable. The element width is the *referent* width (`u8` for `[u8; 4]`),
    /// not the length's.
    ///
    /// An array index past its length is refused rather than bound: the element
    /// does not exist, so a contract naming it is about nothing, and a fresh
    /// variable there would make a meaningless precondition look like a real one.
    fn bind_indexed_elem(&mut self, arg: &str, index: u64) -> Option<Var> {
        let (local, elem_w, fixed_len, elem_signed) = *self.indexed.get(arg)?;
        if !(1..=64).contains(&elem_w) {
            return None;
        }
        if let Some(n) = fixed_len {
            if index >= n {
                return None;
            }
        }
        // Already bound (the same index twice in one contract): reuse it, so
        // `xs[0] <= xs[0]` is `x <= x` rather than two unrelated inputs.
        let mangled = format!("{arg}__e{index}");
        if let Some(v) = self.vars.get(&mangled) {
            return Some(*v);
        }
        if !self.name_is_free(&mangled) {
            return None;
        }
        let slot = self.base + self.next_slot;
        if slot as usize >= crate::smt::MAX_VARS {
            return None;
        }
        self.next_slot += 1;
        let v = smt::var_named(slot, elem_w);
        self.vars.insert(mangled.clone(), v);
        // The element's signedness has to reach the *parser* too, not only the
        // executor's seeds. Every other binding site records it here, and this one
        // did not, so `is_signed_name("xs__e0")` was false for an `i8` element and
        // a contract read `xs[0] < 0` as unsigned -- never true -- which is the
        // exact confusion `signed_slice_element_is_signed` exists to catch. The
        // false reading also refused `xs[0] == i8::MIN` as a signed/unsigned mix
        // once that check was added, so the missing insert showed up twice.
        if elem_signed {
            self.signed.insert(mangled.clone());
        }
        self.paths.insert(format!("{arg}[{index}]"), mangled);
        self.elem_seeds.push((local, index, v, elem_signed));
        Some(v)
    }

    /// Bind a symbolic index: the index variable, and every element of the array
    /// or slice, so the parser can build the ite chain from bindings that already
    /// exist.
    ///
    /// The index is a fresh input (whatever the caller passed) and the elements
    /// are the same ones a literal `a[k]` would bind, so `a[i]` and `a[0]` share
    /// their element variables and the two cannot disagree. The *range* is not
    /// checked here: the bound is recorded in `sym_bound`, and the contract is
    /// refused unless the precondition establishes it.
    ///
    /// The range enumerated is [`IndexBound::Const`] for an array (its type
    /// length) and [`IndexBound::Len`] for a slice (its length variable, which is
    /// symbolic), so a slice's chain enumerates `0..MAX_INDEX_CHAIN` and is exact
    /// only where the length is within that.
    ///
    /// Every element is bound up front rather than on first use because the
    /// postcondition is evaluated in a closure that cannot hold a `&mut`, and
    /// because the executor is handed the same element variables as seeds: an
    /// element the contract did not bind would be created fresh by the body and
    /// the two `a[i]` would then be different values that look alike.
    pub fn bind_sym_index(
        &mut self,
        arg: &str,
        elem_w: u8,
        bound: IndexBound,
        index_name: &str,
        index: Var,
    ) -> Option<Var> {
        if !(1..=64).contains(&elem_w) {
            return None;
        }
        // A slice has no length in its type, so the chain enumerates
        // `0..MAX_INDEX_CHAIN` and is exact only where the length is within that.
        // The obligation is recorded in `sym_bound` and established by the caller.
        let steps = match bound {
            IndexBound::Const(n) if n <= MAX_INDEX_CHAIN => n,
            IndexBound::Const(_) => return None,
            IndexBound::Len(_) => MAX_INDEX_CHAIN,
        };
        if let Some(v) = self.sym_index.get(arg) {
            // The same array subscripted by two different indices has no single
            // chain to rewrite to. Refusing keeps the second subscript a refusal
            // rather than silently reusing the first chain.
            //
            // The comparison is on the *bound index variable*, not on the name, so
            // two spellings of one index (`a[i]` and `a[k]` where `let k = i`)
            // share a chain rather than colliding. That is what makes an alias a
            // rename and nothing more.
            if *v != index {
                return None;
            }
            // The same index under a new spelling: it names the same element, so
            // record the spelling and let the rewrite replace it too. Returning
            // early here left the second spelling unrewritten, and the parser then
            // refused the whole contract as an unknown name.
            self.sym_index_names.entry(arg.to_string()).or_default().insert(index_name.to_string());
            return Some(*v);
        }
        // The elements first, so the chain has all of them to build from.
        let mut elems = Vec::with_capacity(steps as usize);
        for k in 0..steps {
            elems.push(self.bind_indexed_elem(arg, k)?);
        }
        let v = index;
        self.sym_index.insert(arg.to_string(), v);
        self.sym_index_names.entry(arg.to_string()).or_default().insert(index_name.to_string());
        // `ite(i == 0, e0, ite(i == 1, e1, ... ite(i == N-1, e_{N-1}, 0)))`.
        // The fall-through is unreachable: every use of the chain is guarded by
        // `i < N` (conjoined by `eval_*`, or assumed from the body's own bounds
        // assert), so the value chosen for `i >= N` is never observed.
        let mut chain = smt::word(0, elem_w);
        for k in (0..steps).rev() {
            chain = smt::ite(smt::eq_const(v, k), elems[k as usize], chain);
        }
        self.sym_chain.insert(arg.to_string(), chain);
        // The rewrite replaces `a[i]` with this name, and the parser resolves it
        // from `vars`, so the chain has to be reachable by name.
        let chain_name = format!("{arg}__chain");
        if !self.name_is_free(&chain_name) {
            return None;
        }
        self.vars.insert(chain_name.clone(), chain);
        // The chain stands for an element of `arg`, so the parser must know the
        // element's signedness for the same reason `bind_indexed_elem` does: a
        // `a[i]` over `[i8; N]` read as unsigned makes `a[i] < 0` never true.
        if self.indexed.get(arg).is_some_and(|&(_, _, _, es)| es) {
            self.signed.insert(chain_name.clone());
        }
        self.paths.insert(chain_name.clone(), chain_name);
        self.sym_bound.insert(arg.to_string(), bound);
        Some(v)
    }

    /// `(index variable, bound)` for every indexed argument a contract
    /// subscripts symbolically, so the caller can require that the precondition
    /// establishes each index is in range.
    ///
    /// The ite chain has a fall-through for an out-of-range index (it has to
    /// return *something*), so the chain is only an honest model where the index
    /// is in range. Rather than refuse the subscript, the caller proves the
    /// precondition implies the bound; if it does not, the contract is refused.
    /// Conjoining the bound into the precondition instead would be unsound,
    /// because it would quietly strengthen what the source asked to be checked.
    ///
    /// The bound is an [`IndexBound`] rather than a `u64` because a slice's is a
    /// *term*: its length is a symbolic input. An array's is still the constant
    /// from its type, wrapped so the two travel as one shape.
    pub fn index_guards(&self) -> Vec<(Var, IndexBound)> {
        self.sym_index
            .iter()
            .filter_map(|(arg, v)| {
                let bound = *self.sym_bound.get(arg)?;
                Some((*v, bound))
            })
            .collect()
    }

    /// `(local, steps)` for every *slice* the contract subscripts symbolically,
    /// so the executor can build its own chain over the same range.
    ///
    /// Only slices appear here. An array's chain comes from its type length, which
    /// the executor already has from `array_lens`; a slice's has no type length,
    /// so the executor can only build one when the contract established
    /// `len <= MAX_INDEX_CHAIN`, which is exactly what `sym_bound` records. A
    /// slice whose bound the contract did *not* establish is absent, and its
    /// symbolic subscript stays refused rather than becoming a chain that
    /// enumerates a range the length may exceed.
    pub fn slice_chain_steps(&self) -> Vec<(u32, u64)> {
        self.sym_bound
            .iter()
            .filter_map(|(arg, bound)| {
                let (local, _, _, _) = self.indexed.get(arg)?;
                match bound {
                    IndexBound::Len(_) => Some((*local, MAX_INDEX_CHAIN)),
                    IndexBound::Const(_) => None,
                }
            })
            .collect()
    }

    /// Bind every indexed element a contract text names, so the rewrite has a
    /// binding for each and the run needs no mutable access to the environment.
    ///
    /// Scanning the text up front rather than binding on demand keeps
    /// `eval_requires` / `eval_ensures` taking `&FieldEnv`: the postcondition is
    /// evaluated inside an `Fn` closure the executor calls on every returning
    /// path, and that closure cannot hold a `&mut`. It also means an element the
    /// body reads but the contract does not is bound by the *executor* (through
    /// `index_elem`), and the two agree because both key on the same index.
    pub fn bind_index_refs(&mut self, text: &str, args: &BTreeMap<String, Var>) {
        let chars: Vec<char> = text.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            if chars[i].is_alphabetic() || chars[i] == '_' {
                let start = i;
                while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                let ident: String = chars[start..i].iter().collect();
                // An array reached through a field path, `x.a[0]`. The scanner reads `x` first,
                // so the dotted run has to be recognised from the *start* of the identifier, not
                // from a later segment. A run that has an element type recorded and is followed by
                // `[digits]` binds an element of that array; the whole-argument branch below only
                // sees the bare `a[0]` spelling, so the two do not overlap.
                if chars.get(i) == Some(&'.') {
                    if let Some((end, path)) = longest_dotted_run(&chars, start) {
                        if self.path_elem_types.contains_key(&path) && chars.get(end) == Some(&'[') {
                            let mut j = end + 1;
                            let digits: String =
                                chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
                            j += digits.len();
                            if !digits.is_empty() && chars.get(j) == Some(&']') {
                                if let Ok(k) = digits.parse::<u64>() {
                                    self.bind_path_elem(&path, k);
                                }
                                i = j + 1;
                                continue;
                            }
                        }
                    }
                }
                if chars.get(i) == Some(&'[') {
                    let mut j = i + 1;
                    let digits: String = chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
                    j += digits.len();
                    if !digits.is_empty() && chars.get(j) == Some(&']') {
                        if let Ok(k) = digits.parse::<u64>() {
                            self.bind_indexed_elem(&ident, k);
                        }
                        i = j + 1;
                        continue;
                    }
                    // Not a literal index: a symbolic subscript of an *array*,
                    // `a[i]`. Only an array has a finite domain to enumerate; a
                    // slice's length is a symbolic input, so `xs[i]` is left
                    // unbound and the parser refuses it. Binding here (rather
                    // than in the parser) keeps the element variables in
                    // `elem_seeds`, so the executor is handed the same ones.
                    // Anything that is not a name the contract may use is left
                    // unbound and refused by the parser -- a refusal, not a
                    // wrong value.
                    let close = chars[j..].iter().position(|c| *c == ']').map(|p| p + j);
                    if let Some(close) = close {
                        let inner: String = chars[i + 1..close].iter().collect();
                        // The index has to be a name the contract may use -- an
                        // argument, or a local that is a direct alias of one
                        // (`let k = i; a[k]`). A compound index (`a[i + 1]`) is
                        // left unbound and refused by the parser rather than
                        // mis-modelled.
                        if let Some(&index) = args.get(&inner) {
                            // The bound is the array's type length or, for a
                            // slice, the length *variable* -- which is why the
                            // argument's length has to be bound before this runs.
                            // A slice whose length the contract never named has
                            // no variable to bound the chain by, so it is left
                            // unbound and refused.
                            if let Some((_, elem_w, fixed_len, _)) =
                                self.indexed.get(&ident).copied()
                            {
                                let bound = match fixed_len {
                                    Some(n) => Some(IndexBound::Const(n)),
                                    None => self.vars.get(&format!("{ident}__len")).map(|l| {
                                        IndexBound::Len(*l)
                                    }),
                                };
                                if let Some(bound) = bound {
                                    self.bind_sym_index(
                                        &ident, elem_w, bound, &inner, index,
                                    );
                                }
                            }
                        }
                        i = close + 1;
                        continue;
                    }
                }
                continue;
            }
            i += 1;
        }
    }
}

/// Rewrite `arg.field` to its mangled binding, token-aware.
///
/// Only whole `ident.ident` runs that match a *bound* path are replaced, so an
/// unrelated `x.y` is left for the parser to refuse as an unknown name rather
/// than silently becoming something else.
/// The `ret.N` components the given contract texts name.
/// The up-front parse probe uses this to bind only what a contract can mention.
/// Binding *every* declared component of the return type makes a `(u8, &u8)`
/// return unprobeable: component 1 is a reference with no bit-vector width, so
/// the probe refuses and the function is `Skipped` -- for a component the
/// contract never named. `(u8, &u8)` and `(bool, &T)` returns are ordinary, so
/// that skip silently loses the proof.
///
/// Only `ret.N` is matched, not `result.N`: the rewrite that gives a component
/// its binding emits `ret.N`, so `result.N` was never resolvable and is left to
/// the parser to refuse rather than half-supported here.
pub fn named_ret_components(texts: &[String]) -> BTreeSet<u32> {
    let mut out = BTreeSet::new();
    for text in texts {
        let chars: Vec<char> = text.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            if chars[i].is_alphabetic() || chars[i] == '_' {
                let start = i;
                while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                let ident: String = chars[start..i].iter().collect();
                if ident == "ret" && chars.get(i) == Some(&'.') {
                    let j = i + 1;
                    let digits: String =
                        chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
                    if !digits.is_empty() {
                        if let Ok(k) = digits.parse::<u32>() {
                            out.insert(k);
                        }
                    }
                }
                continue;
            }
            i += 1;
        }
    }
    out
}

/// The longest dotted run starting at `start` (`ident` then `.seg` repeated), as
/// `(index past the run, the dotted path)`.
///
/// Used to recognise an array reached through a field path (`x.a` in `x.a[0]`). A run that is
/// not all identifiers ends before the offending character, so a subscript or a call is never
/// swallowed.
fn longest_dotted_run(chars: &[char], start: usize) -> Option<(usize, String)> {
    let mut end = start;
    while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
        end += 1;
    }
    if end == start {
        return None;
    }
    let mut last = end;
    while chars.get(end) == Some(&'.') {
        let mut j = end + 1;
        while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
            j += 1;
        }
        if j == end + 1 {
            break;
        }
        end = j;
        last = j;
    }
    Some((last, chars[start..last].iter().collect()))
}

/// The longest dotted run starting at `dot` that has a nested binding, as
/// `(index past the run, mangled name)`.
///
/// `dot` is the index of the first `.` in `ident.field...`. The run is scanned
/// segment by segment, and the longest prefix present in `nested_paths` wins: for
/// `o.i.v` with bindings for both `o.i` and `o.i.v`, the leaf wins, so the parser
/// sees the leaf variable rather than the intermediate one. A segment that is not
/// an identifier (`o.len()`, `o[0]`) ends the run, so a call or subscript is never
/// swallowed by a nested match.
fn longest_nested_match(
    chars: &[char],
    start: usize,
    dot: usize,
    fields: &FieldEnv,
) -> Option<(usize, String)> {
    let mut best: Option<(usize, String)> = None;
    let mut i = dot;
    while chars.get(i) == Some(&'.') {
        let mut j = i + 1;
        while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
            j += 1;
        }
        if j == i + 1 {
            break;
        }
        let candidate: String = chars[start..j].iter().collect();
        if let Some(m) = fields.nested_paths.get(&candidate) {
            best = Some((j, m.clone()));
        }
        i = j;
    }
    best
}

/// The segment name a nested refusal should name: the first dotted segment after
/// the longest prefix that *did* bind.
///
/// For `o.i.nope` where `o.i` binds, the failure is `nope`, so the message says
/// `unknown field \`nope\` of \`o\`` rather than repeating the whole path. When
/// nothing binds (the first segment is the bad one) it names that segment.
fn longest_bound_prefix(chars: &[char], start: usize, dot: usize, fields: &FieldEnv) -> String {
    let mut last_bound_end = dot;
    let mut i = dot;
    while chars.get(i) == Some(&'.') {
        let mut j = i + 1;
        while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
            j += 1;
        }
        if j == i + 1 {
            break;
        }
        let candidate: String = chars[start..j].iter().collect();
        if fields.nested_paths.contains_key(&candidate) {
            last_bound_end = j;
        }
        i = j;
    }
    // The segment right after the last bound prefix.
    let mut k = last_bound_end;
    if chars.get(k) == Some(&'.') {
        k += 1;
    }
    let mut e = k;
    while e < chars.len() && (chars[e].is_alphanumeric() || chars[e] == '_') {
        e += 1;
    }
    chars[k..e].iter().collect()
}

/// The context a nested-field walk carries: the argument being walked and the
/// struct layouts, plus the type names on the current branch (the recursion guard).
struct NestedWalk<'a> {
    local: u32,
    arg: &'a str,
    structs: &'a BTreeMap<String, StructDef>,
    on_path: Vec<String>,
}

fn rewrite_fields(text: &str, fields: &FieldEnv) -> Result<String, SpecError> {
    // A payload path is a rewrite target too, so an enum-only contract must not
    // take the early return: `m.Data` would be left spelled as a field access the
    // parser cannot reduce.
    if fields.paths.is_empty()
        && fields.known_args.is_empty()
        && fields.payload_paths.is_empty()
        && fields.nested_paths.is_empty()
    {
        return Ok(text.to_string());
    }
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c.is_alphabetic() || c == '_' {
            let start = i;
            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            // A field access: `ident.ident`, where the tail is alphanumeric.
            if chars.get(i) == Some(&'.') {
                let dot = i;
                let mut j = i + 1;
                while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
                    j += 1;
                }
                let field: String = chars[dot + 1..j].iter().collect();
                // An enum payload: `m.Data`. It is rewritten to the mangled
                // payload name the executor seeds, so the contract's `m.Data` and
                // the body's `((_1 as Data).0)` are one variable.
                if let Some(mangled) = fields.payload_paths.get(&format!("{ident}.{field}")) {
                    out.push_str(mangled);
                    i = j;
                    continue;
                }
                // A variant of an enum argument that has *no* payload (a unit
                // variant, or a struct variant whose fields are not modelled).
                // There is nothing to bind, so this is refused with a message
                // that names the variant rather than left for the parser to
                // report as a missing comparison operator. Refusing is the
                // honest answer: binding a fabricated value would let a false
                // contract about a payload that does not exist be proved.
                if fields.enum_args.contains(&ident)
                    && fields.variant_consts.contains_key(&format!("{ident}::{field}"))
                {
                    return Err(SpecError {
                        text: text.to_string(),
                        reason: format!(
                            "`{field}` is a variant of `{ident}` with no payload to read; \
                             compare the tag instead (`{ident} == ...`)"
                        ),
                    });
                }
                // `xs.len()` — the slice length. The parens are required, so a
                // bare `xs.len` (a field named `len`) is not silently accepted.
                let is_call = chars.get(j) == Some(&'(');
                if field == "len" && is_call {
                    let close = j + 1;
                    if chars.get(close) == Some(&')') {
                        if let Some(mangled) = fields.paths.get(&format!("{ident}.len()")) {
                            out.push_str(mangled);
                            i = close + 1;
                            continue;
                        }
                        if fields.known_args.contains(&ident) {
                            return Err(SpecError {
                                text: text.to_string(),
                                reason: format!(
                                    "`{ident}` is not a slice or array, so `len()` has no meaning here"
                                ),
                            });
                        }
                    }
                }
                let key = format!("{ident}.{field}");
                if !is_call && !field.is_empty() {
                    if let Some(mangled) = fields.paths.get(&key) {
                        out.push_str(mangled);
                        i = j;
                        continue;
                    }
                    // An element of an array reached through a field path: `x.a[0]`, or a
                    // deeper `o.i.a[0]`. The dotted run is the array's path and its element
                    // binding is in `paths`. Tried before the nested match so the subscript
                    // is not mistaken for the field `x.a` followed by a bracket. The run is
                    // taken from the start of the identifier, not from the first field, so a
                    // nested path is not cut short at `o.i`.
                    if let Some((end, path)) = longest_dotted_run(&chars, start) {
                        if chars.get(end) == Some(&'[') {
                            let mut k = end + 1;
                            let digits: String =
                                chars[k..].iter().take_while(|c| c.is_ascii_digit()).collect();
                            k += digits.len();
                            if !digits.is_empty() && chars.get(k) == Some(&']') {
                                if let Some(mangled) =
                                    fields.paths.get(&format!("{path}[{digits}]"))
                                {
                                    out.push_str(mangled);
                                    i = k + 1;
                                    continue;
                                }
                            }
                        }
                    }
                    // A *nested* path: `o.i.v`. The longest dotted run that has a
                    // binding wins, so `o.i.v` is preferred to a bare `o.i` when
                    // both exist, and the match ends after the segment it consumed.
                    // The run has to start at the first `.` and be all fields, which
                    // is what keeps `xs.len()` and `a[i]` out of it.
                    if let Some((end, mangled)) = longest_nested_match(&chars, start, dot, fields) {
                        out.push_str(&mangled);
                        i = end;
                        continue;
                    }
                    // A field of a known aggregate that has no binding: the struct
                    // has no such field, or its layout was not readable. Refuse
                    // with a message that names the field, rather than letting the
                    // `.` reach the parser and produce "expected a comparison
                    // operator" — the same refusal, a diagnosable one.
                    if fields.aggregate_args.contains(&ident) {
                        // The *segment* that failed is the one after the longest
                        // prefix that did bind, so the message names `v` in
                        // `o.i.v` rather than the whole path.
                        let bad = longest_bound_prefix(&chars, start, dot, fields);
                        return Err(SpecError {
                            text: text.to_string(),
                            reason: format!("unknown field `{bad}` of `{ident}`"),
                        });
                    }
                    if fields.known_args.contains(&ident) {
                        return Err(SpecError {
                            text: text.to_string(),
                            reason: format!("unknown field `{field}` of `{ident}`"),
                        });
                    }
                }
            }
            // `xs[k]` — a slice element. Only a literal index is rewritten; a
            // symbolic subscript has no binding to rewrite to and is left for the
            // parser to refuse, which is the same answer for a slice as for an
            // array.
            if chars.get(i) == Some(&'[') {
                let mut j = i + 1;
                let digits: String = chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
                j += digits.len();
                if !digits.is_empty() && chars.get(j) == Some(&']') {
                    if let Some(mangled) = fields.paths.get(&format!("{ident}[{digits}]")) {
                        out.push_str(mangled);
                        i = j + 1;
                        continue;
                    }
                }
                // `a[i]` on an array: replace the whole subscript with the ite
                // chain bound for `a`. The chain is an exact function of `i`, so
                // this is a definitional rewrite, not an approximation. The index
                // itself is left in place: the range guard (`i < N`) is conjoined
                // by the caller, which is what makes the chain's fall-through
                // unreachable.
                if let Some(close) = chars[j..].iter().position(|c| *c == ']').map(|p| p + j) {
                    let inner: String = chars[i + 1..close].iter().collect();
                    // The chain bound for `ident` is only `ident[inner]` when
                    // `inner` is the very index that chain was built from. A
                    // different index (`a[j]` where the chain is `a[i]`) has no
                    // chain, so it is left for the parser to refuse rather than
                    // rewritten to the wrong subscript.
                    let is_bound_index = fields
                        .sym_index_names
                        .get(&ident)
                        .map(|names| names.contains(&inner))
                        .unwrap_or(false);
                    if is_bound_index {
                        if let Some(mangled) = fields.paths.get(&format!("{ident}__chain")) {
                            out.push_str(mangled);
                            i = close + 1;
                            continue;
                        }
                    }
                }
            }
            out.push_str(&ident);
            continue;
        }
        out.push(c);
        i += 1;
    }
    Ok(out)
}

/// Turn a `requires` contract into a predicate over the named arguments.
pub fn eval_requires(
    text: &str,
    args: &BTreeMap<String, Var>,
    signed: &BTreeSet<String>,
    fields: &FieldEnv,
) -> Result<Pred, SpecError> {
    let orig = text;
    let text = rewrite_fields(text, fields)?;
    let mut names = args.clone();
    names.extend(fields.vars.iter().map(|(k, v)| (k.clone(), *v)));
    let mut sgn = signed.clone();
    sgn.extend(fields.signed.iter().cloned());
    let mut p = Parser::new(&text, &names, None, &sgn, false);
    p.variant_consts = fields.variant_consts.clone();
    p.enum_args = fields.enum_args.clone();
    p.consts = fields.consts.clone();
    let pred = p.parse_or().map_err(|e| e.about(orig))?;
    p.expect_end().map_err(|e| e.about(orig))?;
    Ok(pred)
}

/// The refusal when a bare `ret` names an aggregate return, which has no single
/// word. The contract has to name a component instead.
pub const RET_IS_AGGREGATE: &str =
    "the return type is an aggregate, so `ret` has no single value; name a component such as `ret.0`";

/// The refusal when a bare `ret` names a scalar return whose value the run does
/// not know on this path -- an unmodelled read, or a deref with no backing.
///
/// It is a *different* problem from an aggregate return, and saying "the return
/// type is an aggregate" here would be false: the return type is a plain `u8`,
/// and the reader would go looking for a tuple that does not exist.
pub const RET_IS_UNKNOWN: &str = "the return value is not known on this path";

/// Turn an `ensures` contract into a predicate over the arguments and `ret`.
#[allow(clippy::too_many_arguments)]
pub fn eval_ensures(
    text: &str,
    args: &BTreeMap<String, Var>,
    ret: Option<Var>,
    ret_absent: &'static str,
    signed: &BTreeSet<String>,
    ret_signed: bool,
    fields: &FieldEnv,
    old_args: &BTreeMap<String, Var>,
) -> Result<Pred, SpecError> {
    let orig = text;
    let text = rewrite_fields(text, fields)?;
    let mut names = args.clone();
    names.extend(fields.vars.iter().map(|(k, v)| (k.clone(), *v)));
    let mut sgn = signed.clone();
    sgn.extend(fields.signed.iter().cloned());
    let mut p = Parser::new(&text, &names, ret, &sgn, ret_signed);
    p.ret_absent = ret_absent;
    p.variant_consts = fields.variant_consts.clone();
    p.enum_args = fields.enum_args.clone();
    p.consts = fields.consts.clone();
    p.old_args = old_args.clone();
    p.ret_enum_tags = fields.ret_enum_tags;
    p.ret_payload_guards = fields.ret_payload_guards.clone();
    let pred = p.parse_or().map_err(|e| e.about(orig))?;
    p.expect_end().map_err(|e| e.about(orig))?;
    Ok(pred)
}

/// Turn a loop `invariant:` into a predicate over the function's locals.
///
/// `names` maps a source-level name to the variable standing for that local at
/// the loop head. It is the same expression language as `requires` / `ensures`,
/// but the identifiers resolve against locals (`s`, `i`) rather than only
/// parameters, because a loop invariant is usually about the accumulator.
///
/// A name that resolves to nothing is an error rather than a fresh variable:
/// a typo in an invariant must not become an unconstrained unknown that makes
/// the induction hypothesis vacuous.
pub fn eval_invariant(
    text: &str,
    names: &BTreeMap<String, Var>,
    signed: &BTreeSet<String>,
    consts: &BTreeMap<String, Const>,
) -> Result<Pred, SpecError> {
    let mut p = Parser::new(text, names, None, signed, false);
    p.consts = consts.clone();
    let pred = p.parse_or()?;
    p.expect_end()?;
    Ok(pred)
}

/// Read a `decreases:` measure as a *value* rather than a predicate.
///
/// A measure is an expression, not a proposition: `decreases: n` or `decreases:
/// len - i` names the quantity the induction counts down. So this parses at the
/// expression level and returns the term with its signedness, rather than a
/// `Pred`.
///
/// The signedness matters because the decrease test is `m < m_entry`, and the
/// relation that means is the measure's own: a signed measure compares with
/// `slt` and an unsigned one with `ult`. A measure that does not resolve is an
/// error, for the same reason an invariant that does not resolve is: a typo must
/// not become an unconstrained value that makes the decrease test vacuous and the
/// induction unsound.
pub fn eval_measure(
    text: &str,
    names: &BTreeMap<String, Var>,
    signed: &BTreeSet<String>,
    consts: &BTreeMap<String, Const>,
) -> Result<(Var, bool), SpecError> {
    let mut p = Parser::new(text, names, None, signed, false);
    p.consts = consts.clone();
    let (v, sgn) = p.parse_expr()?;
    p.expect_end()?;
    Ok((v, sgn.eval()))
}

/// The signedness of a subexpression: signed, unsigned, or *not yet known*.
///
/// A bare literal has no type of its own -- Rust infers it from the operand it
/// meets -- so reading it as either sign at the point it is parsed is a guess.
/// The guess is harmless where signed and unsigned agree (`+`, `&`, `==`) but
/// wrong where they do not (`>>`, `/`, `%`, an ordering comparison), and the
/// wrong pick *discharged* `ensures: ret <= (!0 >> 1)` for an `i8` (a false
/// proof: `!0 >> 1` is `127` unsigned and `-1` signed).
///
/// So an untyped operand is carried as `Literal` (a bare, non-negative literal,
/// whose value is unambiguous) or `Opaque` (an untyped constant that is not a
/// plain literal -- the complement of one, or a fold of untyped operands -- whose
/// sign cannot be recovered). An untyped operand adopts the typed operand's sign
/// at a bitwise or additive operator; a *sign-sensitive* operator (`>>`, `/`,
/// `%`, an ordering comparison, a widening cast) refuses an `Opaque` operand
/// rather than guessing, because the two readings disagree there.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Sign {
    Signed,
    Unsigned,
    /// A negated *bare* literal, `-1` or `-128`: signed, but — like a literal —
    /// its width is inferred from the operand it meets (`-1 < (x as i16)` is
    /// well-typed). A suffixed or bound constant (`-1i8`, `i8::MIN`) is `Signed`
    /// and carries its own width, so a mismatch with a typed partner is `E0308`.
    NegLiteral,
    Literal,
    /// An untyped constant that is not a bare literal -- the complement of one
    /// (`!0`, `!128`) -- whose sign cannot be recovered, so it takes the operand's.
    /// The payload is the *(min, max) envelope of the operand literals* Rust
    /// range-checks against the type the complement meets -- `(128, 128)` for
    /// `!128`, `(63, 128)` for `!(128 - 63)` -- because Rust checks those literals
    /// even though the reader holds the complement's value. It is carried here
    /// rather than recorded in the `range` map: the complement's value term is a
    /// plain constant (`!128` is `word(127, 8)`), so it is *hash-consed with an
    /// unrelated bare `127`* and attaching the operand's envelope to that id made
    /// the reader refuse the innocent literal. `None` when the operand is not a
    /// tracked constant, which is the conservative reading: the fit cannot be shown.
    Opaque(Option<(i128, i128)>),
}

impl Sign {
    fn from_bool(b: bool) -> Sign {
        if b {
            Sign::Signed
        } else {
            Sign::Unsigned
        }
    }
    /// The sign to *evaluate* with, for a `+ - * & | ^ <<` or `== !=`: signed and
    /// unsigned agree there, so an untyped operand may take the other side's sign
    /// (or unsigned, which is a literal's natural reading).
    fn eval(self) -> bool {
        matches!(self, Sign::Signed | Sign::NegLiteral)
    }
    /// Whether this is an untyped constant that is not a bare literal.
    fn is_opaque(self) -> bool {
        matches!(self, Sign::Opaque(_))
    }
    /// The complement operand literals' envelope, when it is tracked.
    fn opaque_operand(self) -> Option<(i128, i128)> {
        if let Sign::Opaque(m) = self {
            m
        } else {
            None
        }
    }
    /// Whether the operand's *width* is inferred from the other side rather than
    /// fixed by its own type. A bare literal, a bare negation of one, and an
    /// untyped constant that is not a bare literal (the complement of one, or a
    /// fold of untyped operands -- `!0`, `(!0 + 1)`) all have no type of their own,
    /// so Rust infers their width from the operand they meet. Only a value whose
    /// type is fixed (`1i8`, `i8::MIN`, a cast, a name) has a width of its own, and
    /// a mismatch between it and a typed partner is `E0308`.
    fn adapts(self) -> bool {
        !self.fixes_type()
    }
    /// Whether the operand's type is *fixed* by its own form (`1i8`, `i8::MIN`, a
    /// cast, a name) rather than inferred from context. Such a value cannot meet
    /// an operand of another width or signedness.
    fn fixes_type(self) -> bool {
        matches!(self, Sign::Signed | Sign::Unsigned)
    }
    /// The sign a *typed* operand forces on an untyped partner, if any.
    fn typed(self) -> Option<bool> {
        match self {
            Sign::Signed | Sign::NegLiteral => Some(true),
            Sign::Unsigned => Some(false),
            Sign::Literal | Sign::Opaque(_) => None,
        }
    }
    /// Resolve a pair: the typed operand's sign, or `None` when neither is typed.
    fn resolve(a: Sign, b: Sign) -> Option<bool> {
        a.typed().or_else(|| b.typed())
    }
    /// The sign of `a <op> b`: the typed operand's, or the untyped pair's own.
    ///
    /// A pair with a *fixed* operand takes that operand's sign. With neither fixed
    /// the result keeps the pair's own nature: `Opaque` when a width-dependent
    /// untyped constant is involved (`!0 + 2`), `NegLiteral` when the pair is a
    /// signed but width-adaptive value (`-1 + 1`), and `Literal` otherwise.
    fn combine(a: Sign, b: Sign) -> Sign {
        if a.fixes_type() || b.fixes_type() {
            if a == Sign::Signed || b == Sign::Signed {
                Sign::Signed
            } else {
                Sign::Unsigned
            }
        } else if a.is_opaque() || b.is_opaque() {
            // A fold of complements (`!0 + 2`) has no tracked operand of its own;
            // the operands' literal envelopes are unioned, so a literal anywhere
            // under the fold is still range-checked where the fold is read. `None`
            // only when neither side carried one (the conservative reading).
            Sign::Opaque(Sign::union_env(a.opaque_operand(), b.opaque_operand()))
        } else if a == Sign::NegLiteral || b == Sign::NegLiteral {
            Sign::NegLiteral
        } else {
            Sign::Literal
        }
    }
    /// Is this a sign-*ambiguous* operand: an untyped constant that is not a bare
    /// literal, so signed and unsigned readings of it differ?
    fn ambiguous(self) -> bool {
        self.is_opaque()
    }
    /// The union of two optional envelopes: the min of the mins and the max of the
    /// maxes, or the one that is present when only one is.
    fn union_env(a: Option<(i128, i128)>, b: Option<(i128, i128)>) -> Option<(i128, i128)> {
        match (a, b) {
            (Some((alo, ahi)), Some((blo, bhi))) => Some((alo.min(blo), ahi.max(bhi))),
            (Some(e), None) | (None, Some(e)) => Some(e),
            (None, None) => None,
        }
    }
}

struct Parser<'a> {
    toks: Vec<Tok>,
    pos: usize,
    args: &'a BTreeMap<String, Var>,
    ret: Option<Var>,
    text: String,
    /// Which argument names have a *signed* type. A contract's `<` is the
    /// signed or the unsigned comparison depending on the operand, and the
    /// unsigned one calls `-1` the largest value, so reading it off the type is
    /// the difference between a contract that says what it means and one that
    /// silently says something else.
    signed: &'a BTreeSet<String>,
    /// Whether `ret` is signed.
    ret_signed: bool,
    /// What to say when `ret` has no value to name. It is supplied by the
    /// caller because only the caller knows *why*: outside an `ensures` the name
    /// is meaningless, an aggregate return has no single word, and a scalar
    /// return can be unbound because the value is not known on this path. These
    /// are three different problems and the message must not describe the wrong
    /// one -- a scalar return reported as an aggregate sends the reader looking
    /// for a tuple that is not there.
    ret_absent: &'static str,
    /// `Enum::Variant` → `(discriminant, tag width)`. Empty outside a contract
    /// evaluation, which is what makes `eval_invariant` (which has no enum
    /// layouts in hand) refuse such a name rather than guess a constant.
    variant_consts: BTreeMap<String, (u64, u8)>,
    /// The enum-typed argument names, so a variant name that is *not* in
    /// `variant_consts` can be reported as a bad variant rather than an unknown
    /// constant.
    enum_args: BTreeSet<String>,
    /// Named `const` items, name → the literal the item was defined with, so a
    /// contract can name a constant the way the body does. Empty outside a
    /// contract evaluation that was given the program's table, in which case a
    /// `const` name is refused rather than guessed at -- the same answer the
    /// reader gave before this table existed. See [`FieldEnv::consts`].
    consts: BTreeMap<String, Const>,
    /// The *entry* value of each name a contract may write `old(name)` for.
    ///
    /// A reference argument's name denotes the value it addresses, which the body
    /// may write, so an `ensures` that names it means the value at *return*; the
    /// entry value is reachable only through `old`. Empty outside an `ensures`,
    /// where `old` is refused rather than guessed -- the same discipline as
    /// `ret_absent`.
    old_args: BTreeMap<String, Var>,
    /// `(tag, success discriminant, failure discriminant)` for an enum-returning
    /// function, so `ret.is_ok()` and friends read the tag. `None` when the return
    /// is not an enum, in which case the methods are refused rather than answered
    /// from a tag that does not exist.
    ret_enum_tags: Option<(Var, u64, u64)>,
    /// The `ret.<Variant>` payload bindings, mangled name → `(tag, discriminant)`.
    /// A clause that mentions one of these is guarded on the tag, because the
    /// payload exists only on that variant's paths. See
    /// [`FieldEnv::ret_payload_guards`].
    ret_payload_guards: BTreeMap<String, (Var, u64)>,
    /// The `(min, max)` envelope, as `i128`, of the *literals and folded
    /// intermediate values* in the term a `Var` holds. Rust range-checks every
    /// literal and every constant `+ - *` intermediate against the type the
    /// expression is read at, not only the value that meets the comparison:
    /// `2 & 128` for an `i8` is `literal out of range for i8` although the fold's
    /// value is `0`, and `128 - 63` is rejected although its value `65` fits.
    /// The engine folds the term, so the reader can only see the result; this
    /// map remembers what the result was built from. Terms are hash-consed
    /// (`smt::mk_term`), so keying on the term id is exact.
    ///
    /// A complement (`!128`) is *not* propagated into the envelope through its
    /// value: the complement's own `Opaque` payload already carries the operand
    /// that Rust range-checks (`128`), and the complement's *value* (`127`) is
    /// not a literal. Only a bare literal, a unary `-`, and a `+ - *` fold
    /// contribute.
    range: BTreeMap<u32, (i128, i128)>,
    /// The term ids of *pristine bare literals* (`128`, `1`). A bare literal is
    /// the one thing Rust does *not* check as written when it sits directly under
    /// a unary `-`: `-128` is legal for an `i8` even though `128` alone is not,
    /// because the negated value, not the magnitude, is what meets the type. This
    /// set tells `parse_neg` apart that case from a literal *inside* a fold, whose
    /// magnitude is checked as written (`-(128 - 63)` is rejected for its `128`).
    bare_literals: BTreeSet<u32>,
    /// The `[start, end)` token ranges of *parenthesized predicate groups* whose
    /// inner conjuncts already carry their per-variant payload guards.
    ///
    /// `parse_and` guards each conjunct by scanning the tokens it consumed. A group
    /// re-enters the predicate grammar, so its inner conjuncts are guarded per
    /// variant -- and then the enclosing conjunct's scan would find both payload
    /// names again and add a *combined* guard `tag == 0 && tag == 1`, which is
    /// unsatisfiable and makes the whole group vacuously true:
    /// `(ret.Ok == 9 && ret.Err == 8)` was *verified* on a body returning `Err(7)`.
    /// The scan skips any token inside a recorded range, so the inner guards are the
    /// only ones applied -- each payload restricted to its own variant, which is the
    /// correct reading.
    ///
    /// The range is *not* dropped by a negation, and that is deliberate: a negated
    /// payload clause is guarded by [`Parser::parse_cmp`]'s `!` arm, which applies the
    /// discriminant guard to the whole negated predicate. The range stays recorded so
    /// the enclosing conjunct's scan skips the already-guarded tokens.
    guarded_groups: Vec<(usize, usize)>,
    /// True while [`Parser::parse_cmp`] is parsing the operand of a `!`.
    ///
    /// A negation must not guard its operand's payload clause *inside* the `!`:
    /// `!(ret.Ok == 9)` as `!(tag == 0 => payload == 9)` is false on an `Err` return,
    /// a false refutation, while the equivalent `ret.Ok != 9` reads
    /// `tag == 0 => payload != 9`, true there. A payload clause is *scoped* to its
    /// variant, and the scope wraps the whole clause including the negation, so the
    /// guard is applied by the `!` arm *outside* the `not`, and `guard_ret_payloads`
    /// returns its clause unchanged while this is set.
    in_negation: bool,
    /// The width a shift amount's bare literals are floored at, or `0` outside an
    /// amount.
    ///
    /// A shift amount is a value of its *own* type, not of the shifted operand's:
    /// Rust leaves the amount's type unconstrained, so an unsuffixed amount
    /// expression defaults to `i32` and is folded at 32 bits. Sizing the amount's
    /// bare literals to the scope's width instead made `x >> (2 << 7)` fold the
    /// amount to `0` at an eight-bit scope (the eight-bit `2 << 7` wraps) where
    /// rustc computes `256` and rejects the shift, so the reader *decided* a
    /// comparison on a program rustc rejects. Flooring at 32 bits makes the fold
    /// agree with rustc's `i32` evaluation, so the wrapped value never appears.
    ///
    /// The floor is the amount's *inferred* type, which is [`amount_width`]'s job:
    /// `i32` when nothing in the amount fixes it, or the width of a *typed*
    /// (suffixed) operand when one does -- `1u8 + (2 << 7)` is a `u8` expression,
    /// so its `2 << 7` is `0u8`, not the `256` a blind `i32` floor would build.
    /// The field is set at each shift and restored after the amount is parsed, so a
    /// nested shift's *operand* still sees the enclosing amount's floor.
    ///
    /// [`amount_width`]: Self::amount_width
    amount_floor: u8,
    /// The token indices at which an *identifier the parser was given* (an
    /// argument, `ret`, a local, `old(...)`, `*name`) was consumed, rather than a
    /// written literal, an associated constant (`i8::MIN`) or a `const` item.
    ///
    /// This is *lexical* provenance, and it has to be: a name can be bound to a
    /// constant term -- an invariant is evaluated in the loop-head state, where a
    /// counter like `i` holds the constant it had on entry (`0`) -- so a name and
    /// a written `0` can be the *same* hash-consed term. Keying provenance on the
    /// term id marked a written literal as a name (a written `0 - 1` was accepted
    /// because an argument was pinned to `0` elsewhere in the contract). Rust never
    /// treats a variable's arithmetic as a constant expression, so `i - 1` is a
    /// wrapping subtraction, not the compile error `0u32 - 1u32`; a `const` *item*
    /// and an associated constant, by contrast, Rust really does const-evaluate, so
    /// they stay written constants.
    name_tokens: BTreeSet<usize>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Tok {
    Ident(String),
    /// A numeric literal, with its type suffix's `(width, signed)` if it has one.
    ///
    /// `0u8` is *unsigned* and `0i8` is *signed*: rustc gives the literal that
    /// type, so `-1 <= 0u8` is `E0277` (a `u8` cannot be negated) rather than a
    /// signed comparison. Dropping the suffix left the reader no way to tell
    /// `0u8` from a bare `0`, so a mismatched constant pair was read as signed and
    /// an invalid program was silently decided. The *width* matters just as much:
    /// a suffixed literal has a fixed width, and building it at the scope's width
    /// instead turned `128i16` into `0x80` in an 8-bit scope, which a later
    /// `as i32` sign-extended to `-128` and *verified* a false
    /// `ensures: 128i16 as i32 == -128`. A bare literal has no suffix and stays
    /// untyped (`None`), sized contextually.
    Num(u64, Option<(u8, bool)>),
    /// A numeric literal the tokenizer could not read *exactly* -- a digit that
    /// is invalid for its radix, or a value past `u64`.
    ///
    /// It is a distinct token so the parser refuses it rather than reading it as
    /// `0`. Reading every literal as decimal silently truncated `0xFF` to `0`
    /// (the digit run stopped at `x` and the rest was skipped as a type suffix),
    /// and a mis-read constant in a precondition is a false proof: `requires: x
    /// == 0xFF` became `x == 0`, so `ensures: ret == 0` was "proved" for a
    /// function returning `255`. A refusal is safe; a wrong number is not.
    BadNum,
    /// A character literal, as its Unicode scalar value.
    ///
    /// A `char` is a 32-bit value in this model, so `'0'` is `0x30` at width 32
    /// and is *typed* (it does not adapt to meet a narrower operand): `'0' == 0u8`
    /// is `E0308` in Rust, so it must be refused rather than resized. Its
    /// signedness is `Unsigned`, which is what makes `align_widths` see the width
    /// mismatch.
    Char(u32),
    /// A character literal the tokenizer could not read exactly (an unknown
    /// escape, a missing closing quote, a multi-character literal). Refused for
    /// the same reason as [`Tok::BadNum`]: a wrong constant in a precondition is a
    /// false proof.
    BadChar,
    Op(String),
}

/// Read a Rust character literal starting at `start` (which must be a `'`).
///
/// Returns the scalar value and the index just past the closing quote, or `None`
/// for anything this reader cannot spell exactly: an unterminated literal, a
/// literal with more than one character, or an escape it does not know. A byte
/// escape (`'\n'`, `'\u{1F600}'`, `'\\'`, `'\''`) is read; a raw or multi-char
/// literal is refused, because a guessed value in a contract is a false proof.
fn read_char_literal(b: &[char], start: usize) -> Option<(u32, usize)> {
    let mut i = start + 1;
    let v = if *b.get(i)? == '\\' {
        i += 1;
        let e = *b.get(i)?;
        i += 1;
        match e {
            'n' => 0x0a,
            'r' => 0x0d,
            't' => 0x09,
            '\\' => 0x5c,
            '\'' => 0x27,
            '"' => 0x22,
            '0' => 0x00,
            'x' => {
                // `'\xNN'`: exactly two hex digits.
                let hi = b.get(i)?.to_digit(16)?;
                let lo = b.get(i + 1)?.to_digit(16)?;
                i += 2;
                hi * 16 + lo
            }
            'u' => {
                // `'\u{...}'`: a braced hex scalar value.
                if *b.get(i)? != '{' {
                    return None;
                }
                i += 1;
                let mut n = 0u32;
                let mut any = false;
                while let Some(d) = b.get(i).and_then(|c| c.to_digit(16)) {
                    n = n.checked_mul(16)?.checked_add(d)?;
                    any = true;
                    i += 1;
                }
                if !any || *b.get(i)? != '}' {
                    return None;
                }
                i += 1;
                n
            }
            _ => return None,
        }
    } else {
        let ch = *b.get(i)?;
        // A single character, and not the closing quote (an empty literal `''`).
        if ch == '\'' {
            return None;
        }
        i += 1;
        ch as u32
    };
    // Exactly one closing quote, and no more characters in the literal.
    if *b.get(i)? != '\'' {
        return None;
    }
    // A `char` must be a Unicode scalar value.
    char::from_u32(v)?;
    Some((v, i + 1))
}

fn tokenize(s: &str) -> Vec<Tok> {
    let mut out = Vec::new();
    let b: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < b.len() {
        let c = b[i];
        if c == '\'' {
            // A character literal. Read it exactly or refuse it: a wrong constant
            // in a precondition is a false proof, and `'0'` is the everyday way a
            // contract names a byte.
            match read_char_literal(&b, i) {
                Some((v, next)) => {
                    out.push(Tok::Char(v));
                    i = next;
                }
                None => {
                    out.push(Tok::BadChar);
                    // Consume to the end of the would-be literal so the scan makes
                    // progress and the parser sees one refusal rather than a
                    // cascade of stray tokens.
                    i += 1;
                    while i < b.len() && b[i] != '\'' {
                        i += 1;
                    }
                    i = (i + 1).min(b.len());
                }
            }
            continue;
        }
        if c.is_whitespace() {
            i += 1;
            continue;
        }
        if c.is_ascii_digit() {
            // A radix prefix, or a plain decimal. `0x`/`0b`/`0o` is always a prefix
            // when it starts a literal: `0xg` is a malformed hex literal, not a
            // decimal `0` followed by an identifier, and reading it as the latter
            // would be the same silent truncation this scan exists to avoid.
            let radix = if c == '0' {
                match b.get(i + 1) {
                    Some('x' | 'X') => {
                        i += 2;
                        16
                    }
                    Some('b' | 'B') => {
                        i += 2;
                        2
                    }
                    Some('o' | 'O') => {
                        i += 2;
                        8
                    }
                    _ => 10,
                }
            } else {
                10
            };
            // Take the longest run of digits and `_` separators. A `_` between
            // digits is a separator; the run stops at anything else, which is how a
            // type suffix (`100u32`) is left for the loop below.
            let mut digits = String::new();
            // The signedness and width of the literal's type suffix, if it has one.
            let mut suffix: Option<(u8, bool)> = None;
            while i < b.len() && (b[i].is_digit(radix) || b[i] == '_') {
                if b[i] != '_' {
                    digits.push(b[i]);
                }
                i += 1;
            }
            // Skip a type suffix (`100u32`, `0xFF_i32`) so the literal stays a
            // number. It must be one of the integer type names: `0xFFg` is
            // malformed, and swallowing the `g` as a suffix would read the literal
            // as a well-formed `255` -- the same silent mis-read this scan exists
            // to avoid. A trailing `_` (`100_`) is a separator, not a suffix, and
            // Rust accepts it.
            if b.get(i).is_some_and(|d| d.is_ascii_alphabetic()) {
                let sfx_start = i;
                while i < b.len() && (b[i].is_alphanumeric() || b[i] == '_') {
                    i += 1;
                }
                let sfx: String = b[sfx_start..i].iter().collect();
                if !matches!(
                    sfx.as_str(),
                    "i8" | "i16"
                        | "i32"
                        | "i64"
                        | "i128"
                        | "isize"
                        | "u8"
                        | "u16"
                        | "u32"
                        | "u64"
                        | "u128"
                        | "usize"
                ) {
                    out.push(Tok::BadNum);
                    continue;
                }
                // The suffix is the literal's *type*, so it is what makes `0u8`
                // unsigned and gives it a fixed width. Both are recorded rather
                // than dropped: dropping the sign left a mismatched constant pair
                // (`-1 <= 0u8`) with no unsigned side to see, so it was read as a
                // signed comparison and an invalid program was silently decided;
                // dropping the *width* built `128i16` at the scope's width, which a
                // later widening cast sign-extended to `-128` -- a false proof.
                let ty = Ty::parse(&sfx);
                // The width is recorded as the suffix's *own* width, including
                // `u128`/`i128`'s 128: the reader refuses that width in `parse_atom`
                // (the engine's words stop at 64), and keeping the true number here
                // is what lets the refusal name it. A `usize`/`isize` suffix is 64.
                let (signed, width) = (ty.is_signed(), ty.width().unwrap_or(64));
                suffix = Some((width, signed));
            }
            // Anything the run did not consume is a malformed literal: a digit not
            // valid for the radix (`0b12`, `0o9`), or a value past `u64`. Refuse
            // rather than take a partial value -- a wrong number in a precondition
            // is a false proof, a refusal is not.
            let exact = i == b.len() || (!b[i].is_alphanumeric() && b[i] != '_');
            let val = if digits.is_empty() {
                None
            } else {
                u64::from_str_radix(&digits, radix).ok()
            };
            match (exact, val) {
                (true, Some(v)) => out.push(Tok::Num(v, suffix)),
                _ => out.push(Tok::BadNum),
            }
            continue;
        }
        if c.is_alphabetic() || c == '_' {
            let mut n = String::new();
            while i < b.len() && (b[i].is_alphanumeric() || b[i] == '_') {
                n.push(b[i]);
                i += 1;
            }
            out.push(Tok::Ident(n));
            continue;
        }
        let two: String = b[i..(i + 2).min(b.len())].iter().collect();
        if ["==", "!=", "<=", ">=", "<<", ">>", "&&", "||"].contains(&two.as_str()) {
            out.push(Tok::Op(two));
            i += 2;
            continue;
        }
        out.push(Tok::Op(c.to_string()));
        i += 1;
    }
    out
}

impl<'a> Parser<'a> {
    fn new(
        s: &str,
        args: &'a BTreeMap<String, Var>,
        ret: Option<Var>,
        signed: &'a BTreeSet<String>,
        ret_signed: bool,
    ) -> Parser<'a> {
        Parser {
            toks: tokenize(s),
            pos: 0,
            args,
            ret,
            text: s.to_string(),
            signed,
            ret_signed,
            variant_consts: BTreeMap::new(),
            enum_args: BTreeSet::new(),
            consts: BTreeMap::new(),
            old_args: BTreeMap::new(),
            ret_enum_tags: None,
            ret_payload_guards: BTreeMap::new(),
            range: BTreeMap::new(),
            bare_literals: BTreeSet::new(),
            name_tokens: BTreeSet::new(),
            guarded_groups: Vec::new(),
            in_negation: false,
            amount_floor: 0,
            ret_absent: "`ret` is only meaningful in `ensures`",
        }
    }

    /// Whether the variable named `name` is signed, for choosing the comparison.
    fn is_signed_name(&self, name: &str) -> bool {
        if name == "ret" || name == "result" {
            return self.ret_signed;
        }
        self.signed.contains(name)
    }

    /// Recognize `<name>.is_ok()` / `.is_some()` / `.is_err()` / `.is_none()` as
    /// a whole predicate, where `<name>` is `ret` (an enum-returning function) or
    /// an enum-typed *argument*.
    ///
    /// The four are the *discriminant* predicates: `is_ok`/`is_some` test the
    /// success variant's tag (`Ok` is 0, `Some` is 1) and `is_err`/`is_none` the
    /// failure one. They are total over the tag, so they need no payload guard --
    /// unlike `ret.Ok`, which names a payload that exists on only one variant.
    ///
    /// An argument's tag is bound under `arg__tag`, and the *discriminants* are not
    /// recorded per argument (only `ret`'s are), so for an argument the method is
    /// read against the tag's own domain: `is_ok`/`is_some` test the *success*
    /// discriminant from the enum's layout, which the parser looks up. That lookup
    /// is the one the return case avoids by recording the pair up front; the
    /// argument case resolves it here so the two agree on what `Ok`/`Some` mean.
    ///
    /// Returns `Ok(None)` when the tokens are not this shape (so the caller
    /// continues with the ordinary grammar) and `Err` when they *are* the shape but
    /// the name is not an enum, which is a refusal rather than a silent
    /// fall-through: `ret.is_ok()` on a `u8` return must not be read as some other
    /// comparison.
    fn try_ret_variant_method(&mut self) -> Result<Option<Pred>, SpecError> {
        let Some(Tok::Ident(base)) = self.peek() else { return Ok(None) };
        // `ret . method (` -- four tokens. A bare `ret` (no `.`) is left for the
        // ordinary grammar, which resolves it to the return value.
        if !matches!(self.toks.get(self.pos + 1), Some(Tok::Op(o)) if o == ".") {
            return Ok(None);
        }
        let Some(Tok::Ident(method)) = self.toks.get(self.pos + 2) else { return Ok(None) };
        if !matches!(self.toks.get(self.pos + 3), Some(Tok::Op(o)) if o == "(") {
            return Ok(None);
        }
        if !matches!(self.toks.get(self.pos + 4), Some(Tok::Op(o)) if o == ")") {
            return Ok(None);
        }
        let base = base.clone();
        let method = method.clone();
        // An enum-typed *argument* binds its tag under `arg__tag`, and that is
        // checked first: an argument's own name wins over the `ret`/`result` alias,
        // so a function with an argument called `result` reads the argument rather
        // than the return.
        let arg_tag = self.args.get(&format!("{base}__tag")).copied();
        let (tag, success, failure) = if let Some(tag) = arg_tag {
            let Some(sf) = self.arg_enum_discriminants(&base) else { return Ok(None) };
            (tag, sf.0, sf.1)
        } else if base == "ret" || base == "result" {
            match self.ret_enum_tags {
                Some(t) => t,
                None => {
                    return Err(self.err(
                        "`is_ok`/`is_some`/`is_err`/`is_none` is only meaningful on an enum return",
                    ))
                }
            }
        } else {
            // Not an enum argument and not `ret`: not this shape, so the caller's
            // ordinary grammar reports the `.`.
            return Ok(None);
        };
        let d = match method.as_str() {
            "is_ok" | "is_some" => success,
            "is_err" | "is_none" => failure,
            _ => return Ok(None),
        };
        let p = smt::eq_const(tag, d);
        self.pos += 5;
        Ok(Some(p))
    }

    /// The `(success, failure)` discriminants of an enum-typed *argument*, from the
    /// variant constants the binder recorded (`<arg>::Ok`, `<arg>::Some`, …).
    ///
    /// Returns `None` when the argument is not an enum (no `__tag` binding) or has
    /// neither a success nor a failure variant -- a user enum with neither `Ok` nor
    /// `Some` has no "success" that the type alone names, so `is_ok` on it is
    /// refused rather than guessed.
    fn arg_enum_discriminants(&self, arg: &str) -> Option<(u64, u64)> {
        let find = |v: &str| self.variant_consts.get(&format!("{arg}::{v}")).map(|(d, _)| *d);
        let success = find("Ok").or_else(|| find("Some"))?;
        let failure = find("Err").or_else(|| find("None"))?;
        Some((success, failure))
    }

    fn peek(&self) -> Option<&Tok> {
        self.toks.get(self.pos)
    }

    fn err(&self, reason: impl Into<String>) -> SpecError {
        SpecError { text: self.text.clone(), reason: reason.into() }
    }

    fn eat_op(&mut self, op: &str) -> bool {
        if let Some(Tok::Op(o)) = self.peek() {
            if o == op {
                self.pos += 1;
                return true;
            }
        }
        false
    }

    /// Whether the `(` at the cursor opens a parenthesized *predicate* rather
    /// than arithmetic. Scans to the matching `)` and looks for a comparator or
    /// a boolean operator *anywhere inside* that group. Only a lookahead --
    /// nothing is consumed.
    ///
    /// The scan must not stop at depth one. `((a == 0))` is a predicate wearing a
    /// redundant pair of parentheses, and its comparator sits at depth two; a
    /// depth-one test misses it, the group is then read as arithmetic, the `==`
    /// cannot be consumed, and the whole contract fails to parse. A contract that
    /// fails to parse is a function that never gets verified, so the extra pair
    /// would quietly drop the obligation.
    ///
    /// Looking deeper is safe because the scan stops at the matching close: for
    /// `(a + b) == c` the scan returns at the `)` after `b` and never sees the
    /// `==`, so the group stays arithmetic.
    fn paren_is_predicate(&self) -> bool {
        self.paren_is_predicate_from(self.pos)
    }

    /// [`Self::paren_is_predicate`], starting at an explicit token index.
    ///
    /// The `!` lookahead needs this: to decide whether `!` negates a *predicate* it
    /// must ask about the `(` that follows the `!`, not the one at the cursor.
    fn paren_is_predicate_from(&self, start: usize) -> bool {
        let mut depth = 0usize;
        for (off, t) in self.toks[start..].iter().enumerate() {
            match t {
                Tok::Op(o) if o == "(" => {
                    // A group whose leading predicate is an enum method
                    // (`(ret.is_ok())`, `!(x.is_none())`) is a predicate even though
                    // it carries no comparator. Recognising it here is what makes
                    // grouping and negation of the enum-method predicates parse
                    // instead of falling through to arithmetic.
                    if self.enum_method_is_predicate_from(start + off) {
                        return true;
                    }
                    depth += 1;
                }
                Tok::Op(o) if o == ")" => {
                    depth -= 1;
                    if depth == 0 {
                        return false;
                    }
                }
                Tok::Op(o)
                    if matches!(o.as_str(), "==" | "!=" | "<=" | ">=" | "<" | ">" | "&&" | "||") =>
                {
                    return true
                }
                Tok::Ident(n) if n == "true" || n == "false" => return true,
                _ => {}
            }
        }
        false
    }

    /// Whether the `(` at `start` opens the `base.method()` shape of an enum
    /// discriminant predicate (`ret.is_ok()`, `x.is_none()`).
    ///
    /// This is a *syntactic* lookahead only: whether `base` really names an enum is
    /// decided when the predicate is parsed (and refused if it is not). It exists so
    /// the grouping and negation lookaheads treat `(ret.is_ok())` as a predicate
    /// rather than arithmetic; without it the method reached the arithmetic parser
    /// and the contract was skipped.
    fn enum_method_is_predicate_from(&self, start: usize) -> bool {
        matches!(self.toks.get(start), Some(Tok::Op(o)) if o == "(")
            && self.enum_method_shape(start + 1)
    }

    /// The bare `base.method()` shape of an enum discriminant predicate, with no
    /// enclosing parenthesis: `Ident . is_ok|is_some|is_err|is_none ( )` at `start`.
    /// Used for `!ret.is_some()`, where the `!` is followed by the method directly.
    fn enum_method_shape(&self, start: usize) -> bool {
        if !matches!(self.toks.get(start), Some(Tok::Ident(_))) {
            return false;
        }
        if !matches!(self.toks.get(start + 1), Some(Tok::Op(o)) if o == ".") {
            return false;
        }
        let Some(Tok::Ident(m)) = self.toks.get(start + 2) else { return false };
        if !matches!(m.as_str(), "is_ok" | "is_some" | "is_err" | "is_none") {
            return false;
        }
        matches!(self.toks.get(start + 3), Some(Tok::Op(o)) if o == "(")
            && matches!(self.toks.get(start + 4), Some(Tok::Op(o)) if o == ")")
    }

    /// Whether the `!` at the cursor applies to a *predicate* rather than a value.
    ///
    /// True for `!(a == b)` (a parenthesized predicate) and `!true`/`!false`; false
    /// for `!x`, `!7` and `!x == 5`, where `!` is the unary prefix on a value.
    fn bang_is_predicate(&self) -> bool {
        match self.toks.get(self.pos + 1) {
            Some(Tok::Op(o)) if o == "(" => self.paren_is_predicate_from(self.pos + 1),
            Some(Tok::Ident(n)) if n == "true" || n == "false" => true,
            // `!ret.is_some()`: the `!` is followed by the enum method directly, so
            // the predicate shape is the bare `base.method()` rather than a group.
            Some(Tok::Ident(_)) => self.enum_method_shape(self.pos + 1),
            _ => false,
        }
    }

    fn expect_end(&self) -> Result<(), SpecError> {
        if self.pos == self.toks.len() {
            Ok(())
        } else {
            Err(self.err(format!("trailing tokens from token {}", self.pos)))
        }
    }

    fn parse_or(&mut self) -> Result<Pred, SpecError> {
        let mut left = self.parse_and()?;
        while self.eat_op("||") {
            let right = self.parse_and()?;
            left = smt::or(left, right);
        }
        Ok(left)
    }

    fn parse_and(&mut self) -> Result<Pred, SpecError> {
        let start = self.pos;
        let left = self.parse_cmp()?;
        let mut left = self.guard_ret_payloads(start, self.pos, left);
        while self.eat_op("&&") {
            let start = self.pos;
            let right = self.parse_cmp()?;
            let right = self.guard_ret_payloads(start, self.pos, right);
            left = smt::and(left, right);
        }
        Ok(left)
    }

    /// Guard a clause on the discriminant of any `ret.<Variant>` payload it names.
    ///
    /// A payload exists only on the paths whose tag is that variant, so a clause
    /// naming one is checked as `tag == disc => clause`: on the other variant's
    /// paths it is vacuously true, which is the only meaningful reading. Without
    /// the guard the payload would be compared on *every* path, against a value it
    /// does not have -- a wrong value, not a weaker proof. The guard is applied per
    /// top-level `&&` conjunct (`parse_and`), so `ret.Ok <= n && ret.Err <= m`
    /// checks each payload only on its own variant's paths.
    ///
    /// The names are the *mangled* ones `rewrite_fields` emits (`ret__v_Ok`), and
    /// the scan is over the tokens the conjunct consumed, so the guard is found
    /// wherever in the clause the payload appears -- under a comparison, a cast, or
    /// a nested `+`.
    fn guard_ret_payloads(&self, from: usize, to: usize, p: Pred) -> Pred {
        if self.ret_payload_guards.is_empty() {
            return p;
        }
        // Inside the operand of a `!` the clause is *not* guarded here: the guard
        // belongs outside the negation (`tag == 0 => payload != 9`, not
        // `tag == 0 => payload == 9` negated). `parse_cmp`'s `!` arm applies it to
        // the whole negated predicate once the operand is parsed.
        if self.in_negation {
            return p;
        }
        let mut guard: Option<Pred> = None;
        for (i, t) in self.toks[from..to.min(self.toks.len())].iter().enumerate() {
            // A payload name inside a parenthesized group is already guarded by the
            // group's own inner conjuncts; re-guarding it here would combine two
            // different discriminants into an unsatisfiable guard (see
            // `guarded_groups`).
            let idx = from + i;
            if self
                .guarded_groups
                .iter()
                .any(|(s, e)| idx >= *s && idx < *e)
            {
                continue;
            }
            if let Tok::Ident(name) = t {
                if let Some((tag, disc)) = self.ret_payload_guards.get(name) {
                    let g = smt::eq_const(*tag, *disc);
                    guard = Some(match guard {
                        None => g,
                        Some(prev) => smt::and(prev, g),
                    });
                }
            }
        }
        match guard {
            None => p,
            Some(g) => smt::implies(g, p),
        }
    }

    /// The discriminant guard for the payload names in `[from, to)`, as a bare
    /// predicate, and the number of *distinct* discriminants those names carry.
    ///
    /// The `!` arm of [`Self::parse_cmp`] uses this to re-guard a *negated* payload
    /// clause: the clause's payload names are scoped to their variant, and the scope
    /// wraps the whole clause, so the guard is `tag == disc => !clause` rather than
    /// `!(tag == disc => clause)`. The two differ on the other variant's paths --
    /// the second is false there, a false refutation, and the first is true, the
    /// vacuous reading a payload clause is supposed to have. Multiple names of *one*
    /// discriminant are conjoined (the reading `parse_and` gives the positive
    /// spelling); names of *different* discriminants cannot share one scope, so the
    /// caller refuses that shape rather than conjoining two contradictory guards.
    ///
    /// Unlike [`Self::guard_ret_payloads`] this scans *every* token in the range,
    /// `guarded_groups` included: it runs on the operand of a `!`, whose inner
    /// predicate groups are exactly the clauses the negation scopes, so their
    /// payloads must be re-guarded from outside the negation.
    fn ret_payload_guard_for(&self, from: usize, to: usize) -> (Option<Pred>, usize) {
        if self.ret_payload_guards.is_empty() {
            return (None, 0);
        }
        let mut guard: Option<Pred> = None;
        let mut discs: Vec<u64> = Vec::new();
        for t in &self.toks[from..to.min(self.toks.len())] {
            if let Tok::Ident(name) = t {
                if let Some((tag, disc)) = self.ret_payload_guards.get(name) {
                    if !discs.contains(disc) {
                        discs.push(*disc);
                    }
                    let g = smt::eq_const(*tag, *disc);
                    guard = Some(match guard {
                        None => g,
                        Some(prev) => smt::and(prev, g),
                    });
                }
            }
        }
        (guard, discs.len())
    }

    /// The value of a term that has no free variable, if it is constant.
    ///
    /// `Op::Const` is the common case, but a literal is not always a single node:
    /// `-10` is `0 - 10`, and `1 + 1` is an `Add`. Evaluating the term catches
    /// those too, so a negative or folded literal is resized like any other
    /// rather than treated as an opaque non-constant.
    fn const_value(&self, v: Var) -> Option<u64> {
        smt::evaluate(v, |_| None)
    }

    /// Record the `(min, max)` of the *literals and folded intermediates* a
    /// constant term was built from. Rust range-checks every literal and every
    /// constant `+ - *` intermediate against the type the expression is read at,
    /// so `2 & 128` is an `i8` error although the fold's value is `0`; the engine
    /// folds the term, so this remembers what the value was built from. Terms are
    /// hash-consed, so the id is a faithful key, and the envelope is only ever
    /// widened (never narrowed), so a shared subterm keeps the union of its uses.
    fn record_range(&mut self, v: Var, lo: i128, hi: i128) {
        let e = self.range.entry(v.0 .0).or_insert((lo, hi));
        e.0 = e.0.min(lo);
        e.1 = e.1.max(hi);
    }

    /// The envelope [`record_range`](Self::record_range) recorded for `v`, if any.
    fn range_of(&self, v: Var) -> Option<(i128, i128)> {
        self.range.get(&v.0 .0).copied()
    }

    /// A constant of width `w` that is *not* hash-consed with a plain `word(k, w)`.
    ///
    /// A named bound (`i8::MIN`, `i8::MAX`) and an enum variant are the same bit
    /// pattern as a bare or suffixed literal of that value, so `smt::word` returns
    /// the *one* shared term: `i8::MIN` and `128i8` are both `word(128, 8)`. The
    /// `range` map is keyed by term, so an envelope recorded for the literal --
    /// `128i8` records the written magnitude `128`, which is out of range for an
    /// `i8` -- was read back as the *bound's* envelope and refused a valid
    /// `y == -128i8 && y == i8::MIN`. A bound's fit is known by construction (it is
    /// the type's own extreme), so it must not inherit a literal's envelope.
    ///
    /// The term is built as `truncate(word(k, 64), w)`, which the engine folds to
    /// the same value but which hash-conses separately from `word(k, w)`: no
    /// literal path ever builds a 64-bit word for a value that fits `w`, so this
    /// node is the bound's alone. It carries no `range` entry, so `check_range`
    /// passes it, exactly as the plain bound did before the envelope map existed.
    fn unshared_const(&self, k: u64, w: u8) -> Var {
        smt::truncate(smt::word(k, 64), w)
    }

    /// The value a named `const` item denotes, at the item's own width and sign.
    ///
    /// The dump prints the item's body const-evaluated and typed (`const LIMIT:
    /// u8 = const 10_u8;`), so the width and the sign come from the type suffix
    /// rather than from the operand the constant meets -- a constant has a type of
    /// its own, unlike a bare literal. The term is built through
    /// [`Self::unshared_const`] so it does not hash-cons with a literal of the same
    /// bit pattern, whose recorded envelope would otherwise be read back as the
    /// constant's and could refuse a valid contract.
    ///
    /// A name that is not a literal is refused rather than guessed at: an
    /// expression-bodied item has its value in its own body, not in a declaration
    /// the reader can fold, so nothing here can decide it.
    fn const_item(&self, name: &str, c: &Const) -> Result<(Var, Sign), SpecError> {
        match c {
            Const::UInt(n, ty) => match ty.as_ref().and_then(|t| t.width()) {
                Some(1) => Ok((smt::word(*n as u64 & 1, 1), Sign::Literal)),
                Some(w) if w <= 64 => {
                    let signed = ty.as_ref().map(Ty::is_signed).unwrap_or(false);
                    // A signed item's printed value is two's complement at its width
                    // (`const NEG: i8 = -1` prints `0xff`), and the sign travels with
                    // the term so a later comparison reads it as `-1`; an unsigned
                    // item's is its plain value.
                    Ok((self.unshared_const(*n as u64, w), Sign::from_bool(signed)))
                }
                _ => Err(self.err(format!(
                    "the constant `{name}` has no bit-vector width, so it is not modelled"
                ))),
            },
            Const::Bool(b) => Ok((smt::word(u64::from(*b), 1), Sign::Literal)),
            Const::Unit | Const::Str(_) | Const::Bytes(_) | Const::Other(_) => Err(self.err(format!(
                "the constant `{name}` is not a literal, so its value is not known to the \
                 contract reader"
            ))),
        }
    }

    /// Whether the token span `[lo, hi)` the parser just consumed contains an
    /// identifier that resolved to a *name* rather than a written constant.
    ///
    /// See [`name_tokens`](Self::name_tokens) for why this is lexical. A span with
    /// no name token is a written constant expression -- a literal, a `const` item,
    /// an associated bound (`i8::MIN`), or a fold of those -- and Rust
    /// const-evaluates it, so the fold's overflow refusals apply. A span that
    /// contains a name is a variable's arithmetic, which Rust never const-evaluates.
    fn span_has_name(&self, lo: usize, hi: usize) -> bool {
        self.name_tokens.range(lo..hi).next().is_some()
    }

    /// Record `v`'s envelope as the union of its operands' envelopes, so a
    /// bitwise, shift or `/`/`%` result carries the literals underneath it to the
    /// later range check even though the operation itself adds no literal.
    fn record_range_union(&mut self, v: Var, a: Var, b: Var) {
        let (mut lo, mut hi) = (i128::MAX, i128::MIN);
        let mut any = false;
        for x in [a, b] {
            if let Some((l, h)) = self.range_of(x) {
                lo = lo.min(l);
                hi = hi.max(h);
                any = true;
            }
        }
        if any {
            self.record_range(v, lo, hi);
        }
    }

    /// Record a constant term's own value as its envelope, as the value Rust
    /// range-checks it at: an unsigned constant is its magnitude, a signed one is
    /// its two's-complement value (`128i8` and `i8::MIN` are both `-128`, which is
    /// legal, where the bare `128` is `+128`, which is not).
    fn record_const(&mut self, v: Var, signed: bool) {
        if let Some(val) = self.const_value(v) {
            let w = smt::bits(v);
            let sv: i128 = if signed {
                if w >= 64 {
                    val as i64 as i128
                } else if val & (1u64 << (w - 1)) != 0 {
                    val as i128 - (1i128 << w)
                } else {
                    val as i128
                }
            } else {
                val as i128
            };
            self.record_range(v, sv, sv);
        }
    }

    /// Record a folded `+ - *` result: the union of its operands' envelopes (the
    /// literals underneath) and the result's own value (the intermediate Rust
    /// checks). `2 & 128` keeps the `128`; `100 + 100` adds the `200`.
    ///
    /// An *opaque* result (a fold that touched a complement) records only its
    /// operands. Its own value is a *guess*: the reader evaluates it unsigned
    /// because the fold's type is not known here, so `!1 + 1` records `255` where
    /// the `i8` the fold finally meets makes it `-1`. Range-checking that guess
    /// refused a valid `y == !(!1 + 1)` for an `i8` -- the `255` is out of range
    /// for the signed type, though no `255` is written. The genuine operand
    /// envelopes still carry, so a literal anywhere under the fold is still
    /// checked, and an overflowing intermediate is refused in `fold_const_arith`
    /// before it can reach here.
    fn record_fold_result(&mut self, v: Var, a: Var, b: Var, sgn: Sign) {
        self.record_range_union(v, a, b);
        if !sgn.is_opaque() && self.const_value(v).is_some() {
            self.record_const(v, sgn.eval());
        }
    }

    /// Record the envelope of a unary negation. Rust checks the *negated value*,
    /// so the operand's literals carry over (negated) -- `-(128 - 63)` is rejected
    /// for the inner `128` even though the negated value `-65` fits. The one
    /// exception is a pristine bare literal: `-128` is legal for an `i8` even
    /// though `128` alone is not, because there the negated value *replaces* the
    /// magnitude rather than sitting inside a fold, so its magnitude is not
    /// checked. `bare` says the operand is such a literal.
    fn record_negation(&mut self, nv: Var, operand: Var, bare: bool) {
        if let Some((lo, hi)) = self.range_of(operand) {
            if !bare {
                self.record_range(nv, lo, hi);
            }
            self.record_range(nv, -hi, -lo);
        }
    }

    /// Refuse a constant whose *literals or folded intermediates* do not fit the
    /// type they meet. Rust range-checks every literal and every constant `+ - *`
    /// intermediate against the type the expression is read at -- `2 & 128` is an
    /// `i8` error although the fold's value is `0`, and `128 - 63` is rejected
    /// although its value `65` fits -- so a contract the reader would otherwise
    /// *decide* on a program rustc rejects is refused instead. The envelope is
    /// recorded by [`record_const`](Self::record_const) and friends; a term with
    /// no entry (a name, a cast) has nothing to check.
    fn check_range(&self, v: Var, wide: u8, signed: bool) -> Result<(), SpecError> {
        let Some((lo, hi)) = self.range_of(v) else {
            return Ok(());
        };
        let fits = |x: i128| {
            if signed {
                x >= -(1i128 << (wide - 1)) && x < (1i128 << (wide - 1))
            } else {
                x >= 0 && (x as u128) < (1u128 << wide)
            }
        };
        if !fits(lo) || !fits(hi) {
            let shown = if !fits(lo) { lo } else { hi };
            return Err(self.err(format!(
                "a constant value `{shown}` does not fit the operand's {wide}-bit {} type, so \
                 the shape is refused",
                if signed { "signed" } else { "unsigned" }
            )));
        }
        Ok(())
    }

    /// Refuse a *signed* operand meeting an *unsigned* one, in either order.
    ///
    /// Rust never lets the two sides of a comparison or an arithmetic operator
    /// differ in signedness. A literal takes its type from the operand it meets,
    /// so `x == -1` and `x + -1` for a `u8` are compile errors ("cannot apply
    /// unary operator `-` to type `u8`"). The reader carries a negation as a bit
    /// pattern at the operand's width, which reads `-1` as `255`: a wrong *value*,
    /// and a wrong value in a precondition is a false proof (`requires: x + -1 >= 0`
    /// is trivially true, so any postcondition is proved). So the shape is refused
    /// wherever two operands of one operator can meet, which is the comparison
    /// *and* the arithmetic levels.
    ///
    /// Two *names* of different signedness are the same mistake. `a > b` for an
    /// `i8` and a `u8` is `E0308: mismatched types`, and the reader has to read it
    /// as *some* sign. It picks signed, which is a real reading and not a false
    /// proof, but it is a reading of a program rustc rejects -- so the shape is
    /// refused rather than decided, the same answer as the constant case. It also
    /// closes a semantic hole between this parser and the body: the body reads each
    /// operand at *its own* signedness, so the contract and the body could disagree
    /// about which of `a > b` or `ule(b, a)` is meant.
    ///
    /// The check is narrow. An *untyped* operand (a bare literal, or the complement
    /// of one) is not this shape -- it adopts the typed operand's sign instead, and
    /// is resolved by `Sign::combine`. Two constants are aligned and range-checked
    /// by `align_widths`/`fold_const_arith`. Only a signed *typed* operand against
    /// an unsigned *typed* operand, or a signed constant against an unsigned name,
    /// triggers it -- exactly the pairs rustc rejects.
    fn refuse_mixed_signedness(
        &self,
        l: Var,
        ls: Sign,
        r: Var,
        rs: Sign,
    ) -> Result<(), SpecError> {
        // An untyped operand adopts the other side's sign, so it never clashes.
        let (Some(lb), Some(rb)) = (ls.typed(), rs.typed()) else {
            return Ok(());
        };
        if lb == rb {
            return Ok(());
        }
        let lconst = self.const_value(l).is_some();
        let rconst = self.const_value(r).is_some();
        // Both sides are typed names: `a > b` for an `i8` and a `u8`.
        if !lconst && !rconst {
            return Err(self.err("operands of different signedness cannot be combined"));
        }
        // At least one side is a constant, and the signs differ. rustc rejects the
        // pairing whether the other side is a name (`-1 > x` for a `u8`) or another
        // constant (`-1 > 0u8`, `-1i8 == 0u8`): a signed constant cannot adopt the
        // unsigned operand's type. The both-constants case used to fall through --
        // the earlier check required exactly *one* constant -- and was read as a
        // *signed* comparison, silently deciding an invalid program (`-1 <= 0u8`
        // "verified" as `-1 <= 0`).
        Err(self.err(
            "a signed constant cannot be combined with an unsigned operand",
        ))
    }

    /// The value a constant *denotes*, at its own width.
    ///
    /// A bare literal is non-negative, so its bit pattern is its value. A signed
    /// constant (`i8::MIN`) or a negation (`-1`) is two's-complement, so the top
    /// bit is a sign bit and the value is negative when it is set. `128` and
    /// `i8::MIN` share the bit pattern `0x80` and mean different things, which is
    /// why the flag is passed rather than inferred.
    fn signed_value(&self, v: Var, sgn: bool) -> i128 {
        let w = smt::bits(v);
        let val = self.const_value(v).unwrap_or(0);
        if !sgn {
            return val as i128;
        }
        if w >= 64 {
            val as i64 as i128
        } else if val & (1u64 << (w - 1)) != 0 {
            val as i128 - (1i128 << w)
        } else {
            val as i128
        }
    }

    /// Fold a constant `+`, `-` or `*` *exactly*, widening past the operand width
    /// when the true result does not fit it.
    ///
    /// Rust const-eval rejects a constant expression that overflows its type --
    /// `200u8 + 100u8` is an error, `0u8 - 1u8` too -- and the range check in
    /// [`Self::resize_const`] is what turns that into a refusal. But the check
    /// only sees the value the fold produced, and letting the width-`w` engine
    /// wrap first produced the *wrong* value: `200 + 100` became `44`, so
    /// `x <= 200 + 100` for a `u8` read as `x <= 44` -- a *stronger* precondition
    /// than the author wrote, and `ensures: ret <= 44` was proved for a body that
    /// fails at `x == 100`. That is a false proof, not a refusal.
    ///
    /// Widening keeps the value exact so the later check refuses the shape when
    /// the operand it meets is too narrow, and still reads a result that fits a
    /// wider operand (`x as u16 <= 200 + 100` is `300`, which rustc accepts). An
    /// unsigned expression that goes negative is refused outright: the reader's
    /// own model says such an expression is unsigned, and `0u8 - 1u8` is a
    /// rustc error, so handing the comparison a negative value would only make it
    /// read the wrong predicate.
    ///
    /// Returns `None` when the exact result already fits, in which case the
    /// ordinary wrapping operator produces the same term and nothing changes.
    ///
    /// The two operands are `(value, sign, is-name)` triples plus the operator:
    /// eight scalars in all, each read independently, which is why the grouping
    /// clippy would prefer is not clearer here -- the same shape the other
    /// eight-argument helpers in this crate carry an `allow` for.
    #[allow(clippy::too_many_arguments)]
    fn fold_const_arith(
        &self,
        op: &str,
        a: Var,
        sa: Sign,
        b: Var,
        sb: Sign,
        a_is_name: bool,
        b_is_name: bool,
    ) -> Result<Option<(Var, Sign)>, SpecError> {
        // Only a fold of two constants can be decided here; a symbolic operand
        // leaves the operation to the engine.
        let (Some(_), Some(_)) = (self.const_value(a), self.const_value(b)) else {
            return Ok(None);
        };
        // A *name* that happens to hold a constant (a loop counter bound to its
        // entry value in an invariant) is not a written constant expression, and
        // Rust never range-checks a variable's arithmetic as one: `i - 1` on a
        // `u32` `i` is a wrapping subtraction, not `0u32 - 1u32`. Leave it to the
        // engine rather than refusing it as a written underflow. The flags are
        // lexical (see `name_tokens`), because a name and a written literal can be
        // the *same* hash-consed term.
        if a_is_name || b_is_name {
            return Ok(None);
        }
        let w = smt::bits(a);
        let signed = sa.eval() || sb.eval();
        let (va, vb) = (self.signed_value(a, sa.eval()), self.signed_value(b, sb.eval()));
        // The signed minimum, which is the one value a division can overflow on.
        let min = -(1i128 << (w - 1));
        if matches!(op, "/" | "%") {
            // `i8::MIN / -1` and `i8::MIN % -1` are a rustc *panic*/const-eval
            // error; the engine's divider would wrap them to `MIN` and `0`, a
            // wrong value rather than a refusal.
            if signed && vb == -1 && va == min {
                return Err(self.err(format!(
                    "a constant `{op}` overflows the {w}-bit signed operand width"
                )));
            }
            return Ok(None);
        }
        if !matches!(op, "+" | "-" | "*") {
            return Ok(None);
        }
        let r: i128 = match op {
            "+" => va + vb,
            "-" => va - vb,
            _ => va * vb,
        };
        // An *opaque* operand (a complement, or a fold that touched one) has no
        // signedness of its own: Rust infers it from the type the fold meets, which
        // is not known here. The reader guesses from the other operand, and when
        // *no* operand fixes a sign the guess can disagree with the reading the fold
        // finally gets. Two shapes follow, both of which the reader would otherwise
        // *decide* on a program rustc rejects.
        let untyped_opaque =
            (sa.is_opaque() || sb.is_opaque()) && !sa.fixes_type() && !sb.fixes_type();
        if untyped_opaque && (sa == Sign::NegLiteral || sb == Sign::NegLiteral) {
            // A negated bare literal (`-0`) beside an opaque operand is `E0277`
            // (`cannot apply unary - to type u16`) when the fold meets an unsigned
            // type and legal when it meets a signed one: `!100 * -0` is rejected for
            // a `u16` but accepted for an `i16`. The reader cannot tell which, so
            // the shape is refused rather than decided on the wrong reading.
            return Err(self.err(format!(
                "a constant `{op}` of an untyped operand and a negated literal is \
                 sign-ambiguous: the negation is legal only at a signed type"
            )));
        }
        let fits = if signed {
            let hi = (1i128 << (w - 1)) - 1;
            r >= min && r <= hi
        } else {
            r >= 0 && (r as u128) < (1u128 << w)
        };
        // A fold that *fits* under the reader's guess can still overflow under the
        // other reading: `!127 - 63` is `128 - 63 = 65` unsigned but `i8::MIN - 63`
        // -- a rustc overflow -- signed. The reader decided it (`65`) for a program
        // rustc rejects. The two readings disagree on the overflow, so the shape is
        // refused. (When the guess does *not* fit, the width-dependent refusal below
        // is the answer, and its message is kept.)
        if untyped_opaque && fits {
            let alt = !signed;
            let (av, bv) = (self.signed_value(a, alt), self.signed_value(b, alt));
            let ar: i128 = match op {
                "+" => av + bv,
                "-" => av - bv,
                _ => av * bv,
            };
            let alt_fits = if alt {
                ar >= min && ar < (1i128 << (w - 1))
            } else {
                ar >= 0 && (ar as u128) < (1u128 << w)
            };
            if !alt_fits {
                return Err(self.err(format!(
                    "a constant `{op}` of an untyped operand is sign-ambiguous: it overflows the \
                     {w}-bit operand width under one reading and not the other"
                )));
            }
        }
        if fits {
            return Ok(None);
        }
        if !signed && r < 0 {
            return Err(self.err(format!(
                "a constant expression underflows the {w}-bit unsigned operand width"
            )));
        }
        // The narrowest width that holds the exact result, *at the expression's
        // own signedness*. The signed case matters: `i8::MAX + 1` is `128`, which
        // fits an unsigned `u8` but not a signed one, and an unsigned test here
        // would leave it at eight bits where it reads as `-128` -- a new false
        // proof in place of the one being fixed.
        let mut width = 1u8;
        let mut holds = false;
        while width <= 64 {
            holds = if signed {
                r >= -(1i128 << (width - 1)) && r < (1i128 << (width - 1))
            } else {
                (r as u128) < (1u128 << width)
            };
            if holds {
                break;
            }
            width += 1;
        }
        if !holds {
            // Wider than any engine word: nothing to compare against.
            return Err(self
                .err("a constant expression is wider than the engine's 64-bit words"));
        }
        // The widened result keeps a *typed* operand's sign. With two untyped
        // operands the result is one of two very different things, and conflating
        // them was a false proof:
        //
        // * A fold of *bare literals* (`200 + 100`) is a width-independent
        //   **value**: `300` is `300` at any width that holds it, so it may widen
        //   exactly like a literal. It is `Literal`.
        // * A fold that touches a *complement* (`!0 + 2`) is a width-dependent bit
        //   pattern: `!0` is `-1`/`255`/`65535` according to the width, so
        //   `!0 + 2` is `1` against an `i16` but the reader holds it at the
        //   scope's width. Emitting it at the engine's full width let a later
        //   resize *truncate* it to the operand -- `ensures: (x as i16 + 2) == !0
        //   + 2` was *verified* for `257 == 1`. It is `Opaque`, and `resize_const`
        //   refuses its widening.
        let out = if signed {
            Sign::Signed
        } else if sa == Sign::Unsigned || sb == Sign::Unsigned {
            Sign::Unsigned
        } else if sa.is_opaque() || sb.is_opaque() {
            // An untyped fold whose exact result does not fit the operand width:
            // `!0 + 1` is `256` at the scope's width, `!0 + 2` is `257`. Its value
            // depends on the width Rust infers for it, and the reader learns that
            // width only at the operator that consumes the fold. Carrying the
            // scope-width value and letting `resize_const` truncate it later was a
            // false proof: `(!0 + 1) < 1u8` *verified* (`0 < 1`) and
            // `(!0 + 2) == 1u8` did too (`257` truncated to `1`), though rustc
            // rejects both as an arithmetic overflow.
            //
            // A *signed* partner is no safer, so the refusal cannot be narrowed to
            // the unsigned case: `(!0 + 200) == x` for an `i8` `x` *verified* with
            // `x == -57` (the scope-width `!0` is `255`, `255 + 200` is `455`,
            // truncated to an `i8`'s `-57`), and rustc rejects the fold as `literal
            // out of range for i8`. The value is simply not known until the width
            // is, so it is refused.
            //
            // Only the overflowing branch is reached here, so a fold that fits (a
            // value that is the same at any width holding it, like `200 + 100`) is
            // unaffected -- the control the corpus asserts still reads.
            return Err(self.err(format!(
                "a constant `{op}` of an untyped operand is width-dependent and overflows the \
                 {w}-bit operand width, so its value is not known where it is read"
            )));
        } else {
            Sign::Literal
        };
        // Emit at the narrowest width that holds the exact result, at the
        // expression's own signedness. A fold with a *typed* operand keeps that
        // operand's type, so this is where its exact value lands. (An untyped
        // `Opaque` fold was refused above, so it never reaches here.)
        let mask = if width >= 64 { u64::MAX } else { (1u64 << width) - 1 };
        Ok(Some((smt::word(r as u64 & mask, width), out)))
    }

    /// Resize a constant operand to `wide` bits, refusing one that does not fit.
    ///
    /// Widening is exact: zero-extend unsigned, sign-extend signed. Narrowing is
    /// where a contract can be wrong rather than merely imprecise -- `a <= 300`
    /// for a `u8` would become `a <= 44` if the value were truncated -- so a
    /// value that does not fit is an error and the function is skipped, not a
    /// weaker proof.
    ///
    /// The check runs at *equal* width too, which is what `own_signed` is for. A
    /// bare literal is non-negative, but a signed bound (`i8::MIN`) or a negation
    /// (`-1`) is its two's-complement value; `128` and `i8::MIN` share the bit
    /// pattern `0x80` and mean different things. Without the distinction, `128`
    /// meeting an `i8` was accepted as the bit pattern for `-128`, so `x <= 128`
    /// was read as `x <= -128` -- a wrong value, and a false proof (`ensures: x !=
    /// 127` "held"). The constant's `Sign` tells the two apart: a non-negative
    /// literal is checked as `+val`, a signed one as its two's-complement value, and
    /// an *opaque* one (`!0`) takes the operand's sign, which is the type Rust infers
    /// for it.
    fn resize_const(
        &self,
        v: Var,
        wide: u8,
        signed: bool,
        own: Sign,
    ) -> Result<Var, SpecError> {
        let w = smt::bits(v);
        let val = self.const_value(v).expect("resize_const is only called on a constant");
        // Every literal and every constant `+ - *` intermediate in the term is
        // range-checked against the type it meets here, not only the value that
        // reaches the comparison: `2 & 128` is an `i8` error although its value is
        // `0`. This is what makes a contract the reader would otherwise decide on a
        // rustc-rejected program a refusal instead.
        self.check_range(v, wide, signed)?;
        // An *opaque* constant (`!0`, or a fold that touched a complement) is held
        // at the *scope's* width, and its value depends on the operand width Rust
        // would infer -- `!0` is `-1`/`255`/`65535` by context. A *narrowing* to the
        // operand is exact (the complement at width W is the low W bits of the
        // scope-width complement), so it truncates without a value check. A
        // *widening* cannot be modelled: no fixed extension of the scope-width
        // pattern recovers the operand-width value, and guessing was the false
        // proof (`!0 + 2` read as `257` and truncated into an `i16`).
        //
        // The value check the plain-literal path performs is *not* the one that
        // applies here. A complement's value is always the operand's low `W` bits,
        // so it fits any `W` by construction; what Rust range-checks is the
        // complement's *operand*, against the type the complement meets. `!128`
        // for an `i8` is a `literal out of range for i8` error even though the
        // reader holds `127`, and truncating that to the operand silently turned a
        // rejected program into `y <= 127` -- `i8::MAX` -- which *verified*. So the
        // tracked operand is checked against the operand type here.
        if own.is_opaque() {
            if wide > w {
                return Err(self.err(
                    "a widening of an untyped constant is not modelled: its value depends on the \
                     operand's width, which is not known where it is read",
                ));
            }
            if let Some((lo, hi)) = own.opaque_operand() {
                // The type the complement meets is the operand's: signed up to
                // `2^(W-1) - 1`, unsigned up to `2^W - 1`. A tracked operand
                // literal that exceeds it is a shape rustc rejects, so the contract
                // is refused. The envelope is the operand literals' union, so a
                // literal anywhere under the complement is checked (`!(128 - 63)`
                // is refused for its `128`), and its *low* end is checked too: a
                // negated operand can leave the envelope negative (`!(-7)`).
                let (min, max) = if signed {
                    (-(1i128 << (wide - 1)), (1i128 << (wide - 1)) - 1)
                } else {
                    (0, (1i128 << wide) - 1)
                };
                if lo < min || hi > max {
                    let shown = if lo < min { lo } else { hi };
                    return Err(self.err(format!(
                        "the complement of `{shown}` does not fit the operand's {wide}-bit \
                         {} type, so the shape is refused",
                        if signed { "signed" } else { "unsigned" }
                    )));
                }
            }
            return Ok(if wide < w { smt::truncate(v, wide) } else { v });
        }
        // A *typed* constant -- a bare literal (non-negative) or a signed
        // bound/negation (two's-complement) -- has its own signedness, and that is
        // what decides whether it fills or sign-extends.
        let effective_signed = own.eval();
        // The value the constant denotes, at its own width. A literal written
        // without a type is non-negative; a signed bound or a negation is its
        // two's-complement value.
        let sval: i128 = if effective_signed {
            if w >= 64 {
                val as i64 as i128
            } else if val & (1u64 << (w - 1)) != 0 {
                val as i128 - (1i128 << w)
            } else {
                val as i128
            }
        } else {
            val as i128
        };
        let fits = if signed {
            let lo = -(1i128 << (wide - 1));
            let hi = (1i128 << (wide - 1)) - 1;
            sval >= lo && sval <= hi
        } else {
            sval >= 0 && (sval as u128) < (1u128 << wide)
        };
        if !fits {
            // Report the value as written: a signed constant (`-129`, `i8::MIN`)
            // reads as its negative value, not the two's-complement bit pattern,
            // so the message names the number the contract author wrote.
            let shown: i128 = if effective_signed { sval } else { val as i128 };
            return Err(self.err(format!(
                "literal {shown} does not fit the operand's {wide}-bit width"
            )));
        }
        // Truncate rather than rebuild from `val`. A negative literal is the bit
        // pattern `2^w - 10` at its *source* width, so `word(val, wide)` would be
        // handed a value that does not fit `wide` and would set the engine's
        // ill-formed flag -- turning a valid contract into `Unknown`. Truncation
        // takes the low `wide` bits, which is the same bit pattern the value
        // denotes, and the `fits` check above is what keeps it from being silent.
        //
        // How a *widened* constant fills the new high bits follows the value it
        // *denotes*, which is `effective_signed`. A bare literal is non-negative, so
        // it zero-extends: Rust's `(255u8 as i16) == 255` is *true*, and filling
        // from the operand's sign instead sign-extended the `255` to `65535` and
        // *refuted* a postcondition Rust accepts -- a false refutation, the mirror
        // of a false proof. A typed signed constant (`-1`, a `MIN` bound)
        // sign-extends. An opaque constant never reaches here: it returned above.
        if wide >= w {
            Ok(if effective_signed && wide > w {
                smt::sign_extend(v, wide)
            } else {
                smt::word(val, wide)
            })
        } else {
            Ok(smt::truncate(v, wide))
        }
    }

    /// Make two operands agree in width, by resizing the *constant* one.
    ///
    /// A contract literal is written without a type, so its width has to come
    /// from the operand it meets. Sizing it from the widest name in scope instead
    /// makes `ret <= 255` a 64-bit comparison whenever a slice or array length (a
    /// `usize`) is also in scope, and an 8-bit `ret` against a 64-bit constant is
    /// ill-formed -- which the engine reports as `Unknown` for *every* obligation
    /// in the run, not just that one. So the width is decided here, per use.
    ///
    /// Only a constant is resized: a non-constant operand's width is a property
    /// of its type, and changing it would change what the term means. Two
    /// non-constant operands of different widths cannot arise from Rust that
    /// compiles, so that is refused rather than coerced.
    fn align_widths(
        &self,
        a: Var,
        sa: Sign,
        b: Var,
        sb: Sign,
        signed: Sign,
    ) -> Result<(Var, Var), SpecError> {
        let signed = signed.eval();
        let (wa, wb) = (smt::bits(a), smt::bits(b));
        // Which operand is a *bare* literal, or a bare negation of one, and so
        // has no type of its own: Rust infers its width from the operand it meets,
        // and only such a value may be resized to the other side (`Sign::Literal`).
        //
        // Every other constant carries a type of its own -- a suffix (`1i8`), a
        // named bound (`i8::MIN`), a cast, or a fold with a typed operand -- and a
        // width mismatch between it and a typed partner is a Rust error (`E0308`),
        // not a resize. Resizing it instead let `-1i8 < (x as i16)` and
        // `1i8 == 1i16` *verify* although rustc rejects both: the signedness gate
        // sees two signed operands and passes, so the width was the only remaining
        // evidence, and it was being erased.
        let a_adapts = sa.adapts();
        let b_adapts = sb.adapts();
        let mismatch = || self.err("operands of different widths cannot be combined");
        match (self.const_value(a), self.const_value(b)) {
            // Both constants: give the pair one width. The range check runs on
            // whichever operand is resized: a contract that meets no typed name
            // still has to be one rustc would accept. `128 <= i8::MAX` is a
            // `literal out of range` error in Rust, and without the check here it
            // read as `-128 <= 127` -- always true -- so the shape is refused
            // rather than decided. A bare literal is checked as `+val` and a named
            // bound as its two's-complement value (see `resize_const`), so
            // `i8::MIN <= i8::MAX` still reads while `128 <= i8::MAX` does not.
            //
            // A *bare* literal's width is only a placeholder (it holds its value
            // at the scope's width); it must take the *other* operand's width,
            // whichever side is wider. Aligning to the narrower unconditionally
            // instead resized the *wider* side down -- `128i16 as i32 == 128`,
            // where the cast result is 32 bits and the literal is 8, narrowed the
            // 32-bit `128` to eight bits and refused a valid comparison.
            //
            // With *neither* operand a bare literal the two types are both fixed,
            // so a width mismatch is the Rust error and is refused; at equal width
            // the resize is the identity term but the range check still runs.
            (Some(_), Some(_)) => match (a_adapts, b_adapts) {
                (true, false) => Ok((self.resize_const(a, wb, signed, sa)?, b)),
                (false, true) => Ok((a, self.resize_const(b, wa, signed, sb)?)),
                (false, false) => {
                    if wa == wb {
                        let a = self.resize_const(a, wa, signed, sa)?;
                        let b = self.resize_const(b, wb, signed, sb)?;
                        Ok((a, b))
                    } else {
                        Err(mismatch())
                    }
                }
                (true, true) => {
                    if wa > wb {
                        Ok((self.resize_const(a, wb, signed, sa)?, b))
                    } else if wb > wa {
                        Ok((a, self.resize_const(b, wa, signed, sb)?))
                    } else {
                        let a = self.resize_const(a, wa, signed, sa)?;
                        let b = self.resize_const(b, wb, signed, sb)?;
                        Ok((a, b))
                    }
                }
            },
            // One constant: resize it to the other operand's width. This runs at
            // *equal* width too, where the resize is the identity term but the
            // range check is not: `128` meeting an `i8` must be refused, not read
            // as the bit pattern for `-128`. Skipping the call at equal width is
            // what let `x <= 128` mean `x <= -128` -- a wrong value and a false
            // proof. `sa`/`sb` carry each constant's own signedness, so a bare
            // literal (non-negative) is told apart from a signed bound that
            // happens to share its bit pattern.
            //
            // A constant whose type is *fixed* (not a bare literal) may only meet
            // a name of its own width; a mismatch is refused, as above.
            (Some(_), None) => {
                if a_adapts || wa == wb {
                    Ok((self.resize_const(a, wb, signed, sa)?, b))
                } else {
                    Err(mismatch())
                }
            }
            (None, Some(_)) => {
                if b_adapts || wa == wb {
                    Ok((a, self.resize_const(b, wa, signed, sb)?))
                } else {
                    Err(mismatch())
                }
            }
            (None, None) => {
                if wa == wb {
                    Ok((a, b))
                } else {
                    Err(mismatch())
                }
            }
        }
    }

    fn parse_cmp(&mut self) -> Result<Pred, SpecError> {
        // `true` / `false` as whole predicates, so a contract can say
        // `requires: true` when the function really has no precondition.
        if let Some(Tok::Ident(n)) = self.peek() {
            if n == "true" || n == "false" {
                let v = n == "true";
                self.pos += 1;
                return Ok(smt::truth(v));
            }
        }
        // `ret.is_ok()` / `ret.is_some()` / `ret.is_err()` / `ret.is_none()` as a
        // whole predicate. These are the *discriminant* predicates of an
        // enum-returning function, and they are total over the tag -- there is no
        // path on which they are unreadable -- so they are admitted here rather
        // than through the payload guard a bare `ret.Ok` needs. A contract that
        // writes them on a function whose return is *not* an enum is refused: the
        // tag it would test does not exist.
        if let Some(p) = self.try_ret_variant_method()? {
            return Ok(p);
        }
        if self.bang_is_predicate() && self.eat_op("!") {
            // A payload clause is *scoped* to its variant, and the scope wraps the
            // whole clause, including a negation. So the operand is parsed with the
            // inner guard suppressed (`in_negation`), and the discriminant guard is
            // applied to the *negated* predicate afterwards: `!(ret.Ok == 9)` reads
            // `tag == 0 => payload != 9` (true on an `Err` return, vacuously), not
            // `!(tag == 0 => payload == 9)` (false there -- a false refutation).
            let start = self.pos;
            let saved = self.in_negation;
            self.in_negation = true;
            let inner = self.parse_cmp();
            self.in_negation = saved;
            let inner = inner?;
            let negated = smt::not(inner);
            // The guard is read *before* the group's range is treated as handled, so
            // the scan sees the payload names the negation covers. The group path
            // already recorded the range in `guarded_groups`, so the enclosing
            // conjunct's scan will not apply a *second* guard on top of this one.
            let (guard, distinct) = self.ret_payload_guard_for(start, self.pos);
            // A negation that spans *two* variants (`!(ret.Ok == 9 && ret.Err == 8)`)
            // has no single scope: the conjunction is vacuous per variant, and its
            // negation would have to hold on both, which is not what the source
            // means. Refusing is the honest reading -- a skip, not a verdict against
            // a guard that cannot be stated.
            if distinct > 1 {
                return Err(self.err(
                    "a negated clause names payloads of more than one variant, which \
                     has no single scope",
                ));
            }
            return Ok(match guard {
                Some(g) => smt::implies(g, negated),
                None => negated,
            });
        }
        // A parenthesized *predicate*, as in `!(a == MIN && b == -1)`. Which
        // meaning a `(` has is decided by a lookahead to its matching `)`: if a
        // comparator appears at that level it is a predicate, otherwise it is
        // arithmetic and `parse_expr` below handles it.
        if matches!(self.peek(), Some(Tok::Op(o)) if o == "(") && self.paren_is_predicate() {
            let group_start = self.pos;
            self.pos += 1;
            let inner = self.parse_or()?;
            if !self.eat_op(")") {
                return Err(self.err("missing `)`"));
            }
            // The group's inner conjuncts are already guarded per variant by
            // `parse_and`. Record the group's token range so the enclosing
            // conjunct's scan does not guard the *same* payload names a second time
            // with a combined `tag == a && tag == b`, which is unsatisfiable and
            // makes the group vacuously true (see `guarded_groups`).
            self.guarded_groups.push((group_start, self.pos));
            return Ok(inner);
        }
        let (left, ls) = self.parse_expr()?;
        for op in ["==", "!=", "<=", ">=", "<", ">"] {
            if self.eat_op(op) {
                let (right, rs) = self.parse_expr()?;
                // Both sides of a Rust comparison have the same signedness (the
                // language will not compare an `i8` with a `u8`), so the typed
                // operand decides it and a literal on one side leaves the other to
                // say. With *no* typed operand the reading is a guess, and where
                // the two readings differ the shape is refused.
                //
                // The two readings differ whenever an operand is `Opaque` -- an
                // untyped constant that is not a bare literal (the complement of
                // one, or a fold of untyped operands). Such a constant has no type
                // of its own, and Rust defaults an untyped constant to `i32`, so
                // `!0` is `-1` and `!0 == 255` is `false`; the reader carries the
                // complement as a bit pattern at the scope's width, so it built
                // `255u8 == 255` and *verified* `ensures: !0 == 255` -- a false
                // proof, and one the maintainer's ordering-only refusal left open
                // because `==`/`!=` "compare bit patterns". They do not here: the
                // two readings are different *values* (`-1` vs `255`), not a
                // different ordering of one value. So an opaque operand with no
                // typed partner is refused at *every* comparison, not only the
                // ordering ones. Two bare literals stay unambiguous (`2 == 2`), and
                // any typed operand fixes the reading, so the common cases read.
                let signed = match Sign::resolve(ls, rs) {
                    Some(b) => b,
                    None => {
                        if ls.ambiguous() || rs.ambiguous() {
                            return Err(self.err(
                                "a comparison with no typed operand is sign-ambiguous: an untyped \
                                 constant reads differently as signed and as unsigned",
                            ));
                        }
                        false
                    }
                };
                // A *signed* constant cannot meet an *unsigned* typed operand.
                // Rust infers a literal's type from the operand it is compared
                // with, and `x == -1` for a `u8` does not compile ("cannot apply
                // unary operator `-` to type `u8`"). The reader carries the
                // negation as a bit pattern at the operand's width, so it would
                // read `x == -1` as `x == 255` -- a wrong *value*, and
                // `ensures: ret == 255` was verified for a body returning `x`,
                // which is a false proof. So the shape is refused.
                self.refuse_mixed_signedness(left, ls, right, rs)?;
                // A literal is written without a type, so its width comes from
                // the operand it meets. Sizing it from the widest name in scope
                // makes `ret <= 255` a 64-bit comparison whenever a slice or
                // array length is also in scope, and an 8-bit `ret` against a
                // 64-bit constant is ill-formed -- which poisons *every*
                // obligation in the run, not just this one.
                let (left, right) =
                    self.align_widths(left, ls, right, rs, Sign::from_bool(signed))?;
                return Ok(match op {
                    "==" => smt::eq(left, right),
                    "!=" => smt::not(smt::eq(left, right)),
                    "<=" if signed => smt::sle(left, right),
                    ">=" if signed => smt::sge(left, right),
                    "<" if signed => smt::slt(left, right),
                    ">" if signed => smt::sgt(left, right),
                    "<=" => smt::ule(left, right),
                    ">=" => smt::ule(right, left),
                    "<" => smt::ult(left, right),
                    ">" => smt::ult(right, left),
                    _ => unreachable!(),
                });
            }
        }
        // A bare one-bit value at the predicate position *is* a `bool`: a
        // `bool`-returning function's `ensures: ret`, a bare bool argument, or
        // `!ret` (a one-bit complement). Rust requires a `bool` here, and a
        // one-bit word is exactly what a `bool` is, so reading it as `v != 0` is
        // the value the type means. A word wider than one bit has no such reading
        // and is still refused -- a bare `u32` is not a predicate.
        if smt::bits(left) == 1 {
            return Ok(smt::not(smt::eq_const(left, 0)));
        }
        Err(self.err("expected a comparison operator"))
    }

    /// An arithmetic expression, plus whether it is *signed*.
    ///
    /// The flag is carried alongside the value because a comparison's meaning
    /// depends on it, and the grammar has no casts or type names to recover it
    /// later. An expression is signed when any name in it is, which is exact:
    /// Rust would reject a mixed-sign arithmetic expression.
    ///
    /// The ladder mirrors Rust's precedence, so the entry point is the *loosest*
    /// level and each level's operands are the next tighter one:
    /// `|` < `^` < `&` < `<< >>` < `+ -` < `* / %`. Getting this order wrong is
    /// not a cosmetic matter: `x & 1 + 1` is `x & (1 + 1)` in Rust, and reading it
    /// as `(x & 1) + 1` makes a contract pass or fail against a different number.
    fn parse_expr(&mut self) -> Result<(Var, Sign), SpecError> {
        self.parse_bitor()
    }

    fn parse_bitor(&mut self) -> Result<(Var, Sign), SpecError> {
        let (mut left, mut sgn) = self.parse_bitxor()?;
        while self.eat_op("|") {
            let (r, rs) = self.parse_bitxor()?;
            self.refuse_mixed_signedness(left, sgn, r, rs)?;
            let (pl, pr) = (left, r);
            let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
            left = smt::bor(l, r);
            self.record_range_union(left, pl, pr);
            sgn = Sign::combine(sgn, rs);
        }
        Ok((left, sgn))
    }

    fn parse_bitxor(&mut self) -> Result<(Var, Sign), SpecError> {
        let (mut left, mut sgn) = self.parse_bitand()?;
        while self.eat_op("^") {
            let (r, rs) = self.parse_bitand()?;
            self.refuse_mixed_signedness(left, sgn, r, rs)?;
            let (pl, pr) = (left, r);
            let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
            left = smt::bxor(l, r);
            self.record_range_union(left, pl, pr);
            sgn = Sign::combine(sgn, rs);
        }
        Ok((left, sgn))
    }

    fn parse_bitand(&mut self) -> Result<(Var, Sign), SpecError> {
        let (mut left, mut sgn) = self.parse_shift()?;
        while self.eat_op("&") {
            let (r, rs) = self.parse_shift()?;
            self.refuse_mixed_signedness(left, sgn, r, rs)?;
            let (pl, pr) = (left, r);
            let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
            left = smt::band(l, r);
            self.record_range_union(left, pl, pr);
            sgn = Sign::combine(sgn, rs);
            // `a & mask` is a width-independent *value* when the *whole* result
            // is constant and the mask is width-independent: `&` keeps only the
            // mask's low bits, which are the same at any width, so `(!0 & 1)` is
            // `1` at any width and may widen exactly like a literal. Only that
            // case is marked `Literal` -- carrying it as opaque refused the
            // widening, dropping `(x as u16) == (!0 & 1)`.
            //
            // A *symbolic* masked operand must keep its own sign. Marking it
            // `Literal` would erase a typed argument's type: `x & 128` for a `u8`
            // is still a `u8`, and `Literal` made `refuse_mixed_signedness` accept
            // `(x & 128) == y` for a signed `y`, a pairing rustc rejects (E0308).
            //
            // A *constant* result may be marked `Literal` (a width-independent
            // value that may widen) only when **neither operand carries a type**.
            // A typed operand -- signed *or* unsigned -- fixes the result's type,
            // and `&` cannot erase it: `-1i8 & 1` is an `i8` and `1u8 & 1` is a
            // `u8`, even though both compute the small positive `1`. Marking
            // either `Literal` hid the type, so `(...) == y` against a partner of
            // the *other* signedness -- `E0308` in Rust -- was read as `1 == y`
            // and decided. `(!0 & 1)` has no typed operand (`!0` is `Opaque`, `1`
            // a bare literal), so it still widens exactly.
            if self.const_value(left).is_some()
                && (sgn == Sign::Literal || rs == Sign::Literal)
                && Sign::combine(sgn, rs).typed().is_none()
            {
                // `&` keeps only the mask's low bits, so the *value* is
                // width-independent and may widen like a literal -- but the operand
                // literals are still range-checked by Rust (`!200 & 64` is rejected
                // for its `200`, `!128 & 255` for its `128`). Those literals travel
                // in the operands' `Opaque` envelopes, not the `range` map, so they
                // must be folded into the result *before* the sign is downgraded and
                // the envelopes are lost. The result term is a compound `&` node,
                // never hash-consed with a bare literal, so recording on it cannot
                // pollute an unrelated constant the way the complement's own value
                // term did.
                if let Some((lo, hi)) = Sign::union_env(sgn.opaque_operand(), rs.opaque_operand()) {
                    self.record_range(left, lo, hi);
                }
                sgn = Sign::Literal;
            }
        }
        Ok((left, sgn))
    }

    /// The width Rust infers for the shift amount at the cursor, so the amount's
    /// bare literals are floored at that width instead of a blind `i32`.
    ///
    /// An amount's type is not tied to the shifted operand's, so an unsuffixed
    /// amount defaults to `i32`. A *typed* operand at the amount's own level -- a
    /// suffixed literal (`1u8`), a cast (`n as u8`) -- instead fixes the amount's
    /// type to its width, and every bare literal in the amount takes that width.
    /// Reading `1u8 + (2 << 7)` as `i32` built the inner `2 << 7` as `256` and
    /// refused a shift rustc accepts (`2 << 7` is `0u8` there, so the amount is
    /// `1u8`).
    ///
    /// The scan mirrors the grammar rather than flattening it, because only an
    /// operand at the *amount's own level* fixes its type. In `2 << 7u8` the suffix
    /// is inside the nested shift's *amount*, not an operand of the outer shift, so
    /// it does not make the outer amount `u8`: the outer amount is the `i32`
    /// `2 << 7u8` = `256`, a rustc overflow. A flat scan that took any suffix would
    /// read the outer amount as `u8` and accept a program rustc rejects.
    fn amount_width(&self) -> u8 {
        match self.scan_amount_add(self.pos).0 {
            0 => 32,
            w => w,
        }
    }

    /// Scan an add-level term (the amount's own level) for a typed operand,
    /// returning its width and the index just past the scanned span.
    fn scan_amount_add(&self, mut i: usize) -> (u8, usize) {
        loop {
            let (w, j) = self.scan_amount_mul(i);
            if w != 0 {
                return (w, j);
            }
            i = j;
            match self.toks.get(i) {
                Some(Tok::Op(o)) if o == "+" || o == "-" => i += 1,
                _ => return (0, i),
            }
        }
    }

    /// Scan a mul-level term for a typed operand.
    fn scan_amount_mul(&self, mut i: usize) -> (u8, usize) {
        loop {
            let (w, j) = self.scan_amount_atom(i);
            if w != 0 {
                return (w, j);
            }
            i = j;
            match self.toks.get(i) {
                Some(Tok::Op(o)) if o == "*" || o == "/" || o == "%" => i += 1,
                _ => return (0, i),
            }
        }
    }

    /// Scan one atom (any unary prefixes, and a trailing cast) for a typed width.
    ///
    /// A parenthesized group is scanned at the amount's own level, so a suffix
    /// inside a nested shift's amount is not mistaken for the amount's own type.
    /// A cast fixes the width and *overrides* what it casts -- `(1u8) as u16` is a
    /// `u16` amount, so the inner `1u8` must not win.
    fn scan_amount_atom(&self, i: usize) -> (u8, usize) {
        let mut i = i;
        while matches!(self.toks.get(i), Some(Tok::Op(o)) if o == "-" || o == "!") {
            i += 1;
        }
        let (mut w, mut j) = match self.toks.get(i) {
            Some(Tok::Num(_, Some((w, _)))) => (u8::min(*w, 64), i + 1),
            Some(Tok::Op(o)) if o == "(" => (self.scan_amount_add(i + 1).0, self.after_paren(i)),
            _ => (0, i + 1),
        };
        if matches!(self.toks.get(j), Some(Tok::Ident(n)) if n == "as") {
            if let Some(Tok::Ident(ty)) = self.toks.get(j + 1) {
                if let Some(cw) = Ty::parse(ty).width() {
                    w = cw.min(64);
                    j += 2;
                }
            }
        }
        (w, j)
    }

    /// The index just past the `)` matching the `(` at `i`.
    fn after_paren(&self, i: usize) -> usize {
        let mut depth = 0usize;
        let mut j = i;
        while let Some(t) = self.toks.get(j) {
            match t {
                Tok::Op(o) if o == "(" => depth += 1,
                Tok::Op(o) if o == ")" => {
                    depth -= 1;
                    if depth == 0 {
                        return j + 1;
                    }
                }
                _ => {}
            }
            j += 1;
        }
        j
    }

    /// The shift level: `<<` and `>>`, which bind tighter than `&` but looser
    /// than `+`.
    ///
    /// Two things make a shift unlike the other operators. Its result has the
    /// *left* operand's width, so the amount is a count rather than a value of
    /// that width and the two operands are deliberately *not* width-aligned. And
    /// `>>` means arithmetic or logical according to the left operand's sign, so
    /// a signed operand is the only thing that separates them -- which is why the
    /// signedness carried through decides it.
    ///
    /// The amount must be a *constant*. A symbolic amount is a barrel shifter
    /// (see `smt::shift_var`), and modelling one in a contract would mean
    /// agreeing with the body about what happens when the amount reaches the
    /// width -- a case rustc turns into a panic before the shift. Rather than
    /// guess at that interaction, a symbolic amount is refused, which leaves the
    /// function visibly undecided instead of silently mis-modelled. A constant at
    /// or above the width is a compile error in Rust and is refused here too.
    fn parse_shift(&mut self) -> Result<(Var, Sign), SpecError> {
        let (mut left, sgn) = self.parse_add()?;
        while let Some(op) = self.eat_any(&["<<", ">>"]) {
            // The amount is a value of its *own* type, unconstrained by the
            // operand, so its bare literals are floored at the amount's inferred
            // width (`amount_width`): `i32` when nothing in the amount fixes a
            // type, or a typed operand's width when one does. The *operand* is not
            // floored: rustc reads `(2 << 7)` in an `i8` comparison at eight bits
            // (it accepts `y == (2 << 7)`, which is `y == 0` there).
            //
            // The floor is inherited, not recomputed, when the shift is itself
            // inside an amount: the enclosing type unifies inward through the
            // parentheses, so `x >> (1u8 + (2 << 7))` folds the inner `2 << 7` at
            // eight bits. Recomputing from the inner amount's own tokens would miss
            // the outer `1u8` and build `256`, refusing a shift rustc accepts.
            let saved = self.amount_floor;
            self.amount_floor = if saved == 0 { self.amount_width() } else { saved };
            let amount = self.parse_add();
            self.amount_floor = saved;
            let (r, rs) = amount?;
            // An *opaque* amount (a complement, or a fold that touched one) has no
            // width of its own: `!254` is `-255` at the `i32` Rust infers -- a
            // negative shift amount, and an overflow error -- but `1` at eight bits.
            // Its value, and whether the shift is in range at all, depends on the
            // width the result is read at, so the shape is refused rather than read
            // at the scope's width. A bare literal or a fold of bare literals has
            // one value at any width (`1 + 1` is `2`), and `!0 & 1` is masked to
            // `1` and marked `Literal`, so those still read.
            if rs.is_opaque() {
                return Err(self.err(
                    "a shift amount that is an untyped complement is not modelled: its value \
                     depends on the operand's width",
                ));
            }
            // The amount must be *constant*, but not necessarily a bare literal:
            // `x >> 1 + 1` is `x >> 2` in Rust, and the additive level above has
            // already folded it. `const_value` evaluates a variable-free term, so a
            // folded constant is accepted while a symbolic amount still falls
            // through to the refusal below. Using the raw-literal `const_of` here
            // instead made `x >> 1 + 1` unreadable -- a dropped obligation on a
            // shape rustc accepts, and one the README's own examples use.
            let Some(k) = self.const_value(r) else {
                return Err(self.err("a shift amount in a contract must be a constant"));
            };
            let base = left;
            let w = smt::bits(left);
            if k >= w as u64 {
                return Err(self.err(format!(
                    "shift amount {k} is not below the operand width {w}"
                )));
            }
            // An *untyped* operand has no width of its own: Rust infers it from
            // where the shift result is read, and that is not known here. The width
            // can be as narrow as 8 bits, so a shift of an untyped constant is
            // refused unless it is valid at *every* width it could be read at: the
            // amount below 8, and a literal operand that fits an 8-bit signed
            // value. Without this, the amount was checked against the *scope's*
            // width (32, from the `u32` name in scope), so `255 >> 8` passed and
            // `255 >> 8 <= x` for a `u8` `x` *verified* -- for a program rustc
            // rejects as an overflow (`255` is a `u8`, and a shift by its own width
            // is a compile error). The operand's value was never range-checked
            // either, so `(255 >> 1) >= y` for an `i8` `y` verified although rustc
            // rejects `255` as `literal out of range for i8`.
            //
            // An `Opaque` operand (a complement, or a fitted fold) needs no value
            // check: its value at any width is `-1`/`2^W - 1`, which fits that
            // width by construction.
            if !sgn.fixes_type() {
                if k >= 8 {
                    return Err(self.err(format!(
                        "a shift of an untyped constant by {k} is refused: the operand's width is \
                         inferred from where the result is read, and {k} is not below the \
                         narrowest width"
                    )));
                }
                if matches!(sgn, Sign::Literal | Sign::NegLiteral) {
                    let sval = self.signed_value(left, sgn.eval());
                    if !(-128..=127).contains(&sval) {
                        return Err(self.err(format!(
                            "a shift of an untyped constant {sval} is refused: the operand's width \
                             is inferred from where the result is read, and {sval} does not fit \
                             the narrowest width"
                        )));
                    }
                }
            }
            left = if op == "<<" {
                // A left shift of an untyped constant is sign-insensitive (the bit
                // pattern is the same either way), so it keeps its `Untyped` state.
                smt::shl(left, k as u32)
            } else if k == 0 {
                // A shift by zero is the identity: it preserves the exact bit
                // pattern under *both* readings, so even an opaque constant is
                // unambiguous. `!0 >> 0` is `!0` -- `255` at 8 bits, `-1` at signed
                // -- and its sign stays `Opaque` until the surrounding expression
                // fixes a type. Refusing it before this check dropped a valid
                // postcondition (`ret == (!0 >> 0)`).
                left
            } else {
                match sgn {
                    Sign::Signed | Sign::NegLiteral => smt::ashr(left, k as u32),
                    // An untyped *bare literal* (a small non-negative value) shifts
                    // the same either way, so the unsigned reading is exact.
                    Sign::Unsigned | Sign::Literal => smt::lshr(left, k as u32),
                    // `>>` of an *opaque* untyped constant (the complement of a
                    // literal, or a fold of untyped operands) is the false proof's
                    // shape: with no typed operand the reader has no sign to pick,
                    // and the two readings differ (`!0 >> 1` is `-1` arithmetic,
                    // `127` logical). Refuse rather than guess.
                    Sign::Opaque(_) => {
                        return Err(self.err(
                            "a right shift with no typed operand is sign-ambiguous: it reads \
                             differently as an arithmetic and as a logical shift",
                        ))
                    }
                }
            };
            // The shift's operand literals are still checked by Rust
            // (`128 >> 0` is rejected for its `128`), so they carry through.
            self.record_range_union(left, base, base);
        }
        Ok((left, sgn))
    }

    /// The additive level: `+` and `-`, tighter than the bitwise operators.
    fn parse_add(&mut self) -> Result<(Var, Sign), SpecError> {
        let start = self.pos;
        let (mut left, mut sgn) = self.parse_mul()?;
        let mut left_is_name = self.span_has_name(start, self.pos);
        while let Some(op) = self.eat_any(&["+", "-"]) {
            let op_start = self.pos - 1;
            let (r, rs) = self.parse_mul()?;
            let r_is_name = self.span_has_name(op_start + 1, self.pos);
            // A signed constant added to an unsigned name (`x + -1` for a `u8`) is
            // a rustc error, and reading the negation as `255` would prove
            // `x + -1 >= 0` for every `x` -- a false proof, exactly as at the
            // comparison level. Refused before the operands are aligned.
            self.refuse_mixed_signedness(left, sgn, r, rs)?;
            // Capture the pre-align operands: `align_widths` rebuilds a constant
            // at the common width, and the rebuilt term carries no envelope, so the
            // union must be taken from the terms the literals were recorded on.
            let (pl, pr) = (left, r);
            let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
            // A constant sum or difference is folded *exactly*, so a result that
            // overflows the operand width is refused (as rustc refuses the
            // constant expression) instead of wrapping to a wrong value. A result
            // that fits is left to the ordinary operator. A *name* operand is not a
            // written constant, so the fold's refusals do not apply to it.
            if let Some((v, s)) =
                self.fold_const_arith(op, l, sgn, r, rs, left_is_name, r_is_name)?
            {
                self.record_fold_result(v, pl, pr, s);
                left = v;
                sgn = s;
                left_is_name = left_is_name || r_is_name;
                continue;
            }
            left = if op == "+" { smt::add(l, r) } else { smt::sub(l, r) };
            self.record_fold_result(left, pl, pr, Sign::combine(sgn, rs));
            sgn = Sign::combine(sgn, rs);
            left_is_name = left_is_name || r_is_name;
        }
        Ok((left, sgn))
    }

    /// The multiplicative level: `*`, `/` and `%`, the tightest arithmetic.
    ///
    /// Division and remainder take the *signed* engine when either operand is
    /// signed, the same choice the body makes and for the same reason: the
    /// unsigned divider returns a huge positive quotient for `-7 / 2`, a wrong
    /// value rather than a weaker proof. A *constant* zero divisor is refused, in
    /// whatever form it is written -- `0`, `1 - 1`, `2 - 2` -- because Rust rejects
    /// it at compile time, so a contract carrying one is malformed, not merely
    /// imprecise. A *symbolic* divisor is modelled exactly (the engine's divider is
    /// total), which mirrors the body.
    fn parse_mul(&mut self) -> Result<(Var, Sign), SpecError> {
        let start = self.pos;
        let (mut left, mut sgn) = self.parse_cast()?;
        let mut left_is_name = self.span_has_name(start, self.pos);
        while let Some(op) = self.eat_any(&["*", "/", "%"]) {
            let op_start = self.pos - 1;
            let (r, rs) = self.parse_cast()?;
            let r_is_name = self.span_has_name(op_start + 1, self.pos);
            // The divisor must be checked for *zero*, not for "is a bare zero
            // literal". `x % (1 - 1)` folds to `x % 0` at the additive level, and
            // the raw-literal `const_of` missed it, so the reader built `srem(x, 0)`
            // -- an undefined operation the engine nevertheless evaluates -- and
            // produced a definite verdict from it. A *constant* zero is refused
            // however it is spelled; a symbolic divisor is still modelled exactly.
            if op != "*" && self.const_value(r) == Some(0) {
                return Err(self.err("a division or remainder by a constant zero"));
            }
            // A signed constant divisor with an unsigned name (`x % -1` for a
            // `u8`) is a rustc error, and the negation read as `255` would build
            // `urem(x, 255)` -- a value the author never wrote. Same refusal as the
            // additive and comparison levels.
            self.refuse_mixed_signedness(left, sgn, r, rs)?;
            // A `/` or `%` with no typed operand and an *opaque* constant (the
            // complement of a literal, or a fold) is sign-ambiguous: `!4 / 2` is
            // `125` unsigned and `-2` signed, and the reader would take the unsigned
            // engine. Refuse rather than guess. A bare literal is unambiguous, and a
            // typed operand fixes the reading.
            //
            // The test is `Sign::resolve`, not "does either side evaluate signed":
            // `eval()` is `false` for both `Unsigned` and `Opaque`, so an unsigned
            // name beside `!0` (`x / !0` for a `u8`) was mistaken for a pair with
            // no typed operand and refused, though `resolve` reads the unsigned
            // type off `x` and the division is well-modelled. Only a genuinely
            // untyped pair (`!0 / !1`) is refused.
            if op != "*" && Sign::resolve(sgn, rs).is_none() && (sgn.ambiguous() || rs.ambiguous())
            {
                return Err(self.err(
                    "a `/` or `%` with no typed operand is sign-ambiguous: it reads differently \
                     as signed and as unsigned",
                ));
            }
            // Same width rule as the other operators: a literal product, divisor
            // or mask is sized to the operand it meets.
            let (pl, pr) = (left, r);
            let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
            // A constant `/` or `%` can overflow (`i8::MIN / -1`), which rustc
            // rejects; the fold refuses it rather than wrapping. `*` is folded
            // exactly, so a constant product too wide for the operand is refused
            // instead of wrapping to a wrong value. A *name* operand is not a
            // written constant, so the fold's refusals do not apply to it.
            if let Some((v, s)) =
                self.fold_const_arith(op, l, sgn, r, rs, left_is_name, r_is_name)?
            {
                self.record_fold_result(v, pl, pr, s);
                left = v;
                sgn = s;
                left_is_name = left_is_name || r_is_name;
                continue;
            }
            let signed = sgn.eval() || rs.eval();
            left = match op {
                "*" => smt::mul(l, r),
                "/" if signed => smt::sdiv(l, r),
                "/" => smt::udiv(l, r),
                "%" if signed => smt::srem(l, r),
                _ => smt::urem(l, r),
            };
            self.record_fold_result(left, pl, pr, Sign::combine(sgn, rs));
            sgn = Sign::combine(sgn, rs);
            left_is_name = left_is_name || r_is_name;
        }
        Ok((left, sgn))
    }

    /// Consume whichever of `ops` is at the cursor, returning the one matched.
    fn eat_any<'b>(&mut self, ops: &[&'b str]) -> Option<&'b str> {
        if let Some(Tok::Op(o)) = self.peek() {
            for op in ops {
                if o == op {
                    self.pos += 1;
                    return Some(op);
                }
            }
        }
        None
    }

    /// The cast level: a unary-negated primary, then any `as <type>` chain.
    ///
    /// Rust binds unary `-` *tighter* than `as`, so `-x as u8` is `(-x) as u8`,
    /// not `-(x as u8)`. The two readings agree on the *value* here (negation and
    /// truncation commute) but not on the *type*: Rust's is `u8`, and `-(...)` is
    /// signed. That difference is observable — `-x as u8 > 127` is satisfiable
    /// (`x == 1` gives `255`), where the signed reading is `i8 > 127`, which no
    /// input satisfies, so the function is reported *vacuous* instead of verified.
    /// Hence the negation is applied to the primary first, and the cast chain runs
    /// after it.
    fn parse_cast(&mut self) -> Result<(Var, Sign), SpecError> {
        let (v, sgn) = self.parse_neg()?;
        self.cast_chain(v, sgn)
    }

    /// A unary negation, applied to the primary below it and *before* any cast.
    ///
    /// The result is signed whatever the operand was. Negation is only defined on
    /// a signed type in Rust (`let x: u32 = -1;` does not compile), so a negation
    /// *is* the evidence that the expression is signed. The operand's own flag
    /// cannot be used: `-7` negates the literal `7`, which is unsigned, and
    /// reading the flag through would make `-7 % 3` take the unsigned remainder
    /// (`4294967289 % 3`, i.e. `0`) where Rust says `-1`. Only `% / >>` and the
    /// comparisons consult the flag, so the mistake is a *wrong value* rather than
    /// a refusal -- the one outcome a verifier must not produce silently.
    fn parse_neg(&mut self) -> Result<(Var, Sign), SpecError> {
        // `*c` names the value a reference argument addresses, which is the same
        // word the bare `c` names (the referent *is* the value), so the two are
        // one binding. A contract is this crate's own language rather than a
        // compiled program, so `*NAME` is read as `NAME` for any bound name; the
        // value is the one the name already denotes, so no reading is invented.
        if self.eat_op("*") {
            let Some(Tok::Ident(inner)) = self.peek().cloned() else {
                return Err(self.err("`*` must be applied to a name"));
            };
            self.pos += 1;
            self.name_tokens.insert(self.pos - 1);
            let v = *self
                .args
                .get(&inner)
                .ok_or_else(|| self.err(format!("unknown name `{inner}`")))?;
            return Ok((v, Sign::from_bool(self.is_signed_name(&inner))));
        }
        if self.eat_op("-") {
            let (v, sgn) = self.parse_neg()?;
            // Rust rejects `-x` for an unsigned `x` (`E0600: cannot apply unary
            // operator `-` to type `u8``). The reader models the negation as
            // `0 - x` at the operand's width, which is a *value* Rust never
            // produces, so the shape is refused rather than decided -- the same
            // answer as the mixed-signedness pair. A bare literal is untyped (Rust
            // defaults it to a signed `i32`) and a signed operand is legal, so
            // `-5` and `-x` for an `i8` still read.
            if sgn == Sign::Unsigned {
                return Err(self.err("cannot apply unary `-` to an unsigned operand"));
            }
            let w = smt::bits(v);
            // The negation of a *bare* literal keeps the literal's adaptive width
            // (`-1 < (x as i16)` is well-typed), so it is `NegLiteral`; the
            // negation of a suffixed or bound constant (`-1i8`, `-i8::MIN`) keeps
            // that constant's fixed width, so it is `Signed`. Both are signed.
            let out = if sgn == Sign::Literal { Sign::NegLiteral } else { Sign::Signed };
            // A negated *constant* is widened by one bit when its magnitude does
            // not fit signed at its own width, so the true value survives for the
            // later range check. `-129` for an `i8` is a Rust error ("literal out
            // of range"), but at 8 bits the two's-complement `-129` *is* `127`, so
            // the negation alone would hand the check a value that fits and
            // `x >= -129` would silently mean `x >= 127` -- a false proof, the
            // mirror of the bare-literal wrap. One spare bit keeps `-129` as
            // `-129`, which the check then refuses. `-128` (i8::MIN) still fits at
            // 8 bits, so it is left alone.
            let bare = self.bare_literals.contains(&v.0 .0);
            if let Some(mag) = self.const_value(v) {
                // `-mag` fits signed at `w` bits iff `mag <= 2^(w-1)`.
                let fits = w >= 64 || mag <= (1u64 << (w - 1));
                if !fits {
                    let nv = smt::sub(smt::word(0, w + 1), smt::word(mag, w + 1));
                    self.record_negation(nv, v, true);
                    return Ok((nv, out));
                }
                // A constant that denotes a *value* rather than a written
                // magnitude -- a named bound (`i8::MIN`), an inner negation, or a
                // fold that wrapped to the type's minimum (`3 << 7` at eight bits)
                // -- negates to `-sval`, and that is the value Rust checks.
                // `i8::MIN` is the bit pattern `128` and the value `-128`;
                // negating the *value* is `+128`, out of range, where negating the
                // literal `128i8` is `-128`, which is not. The magnitude check
                // above reads the bit pattern, which is the same `128` for both, so
                // it passed and the negation overflow went unrecorded: the reader
                // *decided* `y == -(i8::MIN)` and `y == -(3 << 7)` on programs
                // rustc rejects. Only a pristine literal (`-128`, `-(128i8)`,
                // `-(128)`) is exempt, because there the negation *is* what makes
                // the magnitude legal.
                if !bare {
                    let sval: i128 = if w >= 64 {
                        mag as i64 as i128
                    } else if mag & (1u64 << (w - 1)) != 0 {
                        mag as i128 - (1i128 << w)
                    } else {
                        mag as i128
                    };
                    // `-sval` fits a signed `w`-bit type iff it is at most
                    // `2^(w-1) - 1`, i.e. `sval > -2^(w-1)`. The negation is
                    // computed at the *operand's* type, so the overflow is a Rust
                    // error wherever the result is read -- `-(i8::MIN) as i16` does
                    // not compile either -- and the shape is refused here rather
                    // than recorded, which a wider target would re-accept.
                    let fits_neg = if w >= 64 {
                        sval != i64::MIN as i128
                    } else {
                        sval > -(1i128 << (w - 1))
                    };
                    if !fits_neg {
                        return Err(self.err(
                            "negating a signed constant at its own type is out of range, so the \
                             shape is refused",
                        ));
                    }
                }
            }
            // A unary `-` is checked as Rust checks the *negated value*: `-(-128)`
            // is `128`, out of range for an `i8`, where `-128` is fine. The one
            // exception is a pristine bare literal (`-128`), whose magnitude is
            // *replaced* by the negation rather than checked, so the operand's own
            // value is not carried through -- but a literal inside a fold is
            // (`-(128 - 63)` is rejected for its `128`).
            let nv = smt::sub(smt::word(0, w), v);
            self.record_negation(nv, v, bare);
            // A negated complement carries the complement's operand envelope
            // forward: the negation is a *value*, so the envelope cannot ride in
            // the sign, and `-!128` for an `i8` is a rustc error for the same `128`
            // that `!128` is. The negation term is a compound `Sub` node, never
            // hash-consed with a bare literal, so recording on it cannot pollute an
            // unrelated constant.
            if let Some((lo, hi)) = sgn.opaque_operand() {
                self.record_range(nv, lo, hi);
            }
            return Ok((nv, out));
        }
        // `!` is a unary prefix on a *value* here, because `bang_is_predicate`
        // ruled out the predicate reading above. On an integer it is bitwise NOT,
        // which is `x ^ all_ones` -- the same term the body builds for `UnOp::Not`
        // in `mir/exec.rs`. Reading it at the predicate level instead made
        // `!x == 5` mean `!(x == 5)` (`x != 5`) where Rust means `(!x) == 5`
        // (`x == 250`): a different predicate, so a wrong verdict, not a refusal.
        if self.eat_op("!") {
            let (v, sgn) = self.parse_neg()?;
            // A *typed* operand keeps its sign and width: `!x` for a `u8` is
            // `x ^ 0xFF`, an 8-bit value.
            if sgn.typed().is_some() {
                let w = smt::bits(v);
                return Ok((smt::bxor(v, smt::all_ones(w)), sgn));
            }
            // The complement of an *untyped* constant (`!0`, `!128`) has no type of
            // its own -- it is `-1`/`255`/`65535` according to the operand it meets,
            // so it is carried as `Opaque` and refused at a sign-sensitive operator
            // rather than guessed. It is built as a *constant word* at the scope's
            // width, not as a `bxor` of `all_ones`: the engine folds a `truncate` of
            // a constant word to a constant, but leaves a `truncate` of a compound
            // term as an opaque node, so `ret == !0` was decided against a free
            // 8-bit variable and *refuted* -- a false refutation.
            if self.const_value(v).is_some() {
                let val = self.const_value(v).expect("checked above");
                let w = smt::bits(v);
                let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
                // The operand's literal envelope is carried so its fit can be
                // checked against the type the complement meets (`!128` is an `i8`
                // range error). A bare literal operand contributes its value; a
                // nested complement (`!!128`) propagates the innermost envelope,
                // because Rust checks those same literals against the type the
                // outermost complement meets. A fold's operand carries the union of
                // its literals (`!(128 - 63)` is `(63, 128)`). It travels in the
                // `Opaque` payload, *not* in the `range` map: the complement's value
                // is a plain constant (`!128` is `word(127, 8)`), so it is
                // hash-consed with an unrelated bare `127`, and recording the
                // operand's envelope on that shared id refused the innocent literal
                // (`x == !128 && y == 127` for a `u8` and an `i8` was skipped).
                let operand = match sgn {
                    Sign::Literal | Sign::NegLiteral => self.range_of(v),
                    // A nested complement's sign carries the envelope it inherited,
                    // but the operand term may *also* have recorded one of its own
                    // (a fold: `!(!1 - 200)` folds `!1` and `200`, and the fold term
                    // carries `200`). Both must survive, so they are unioned -- taking
                    // the inherited envelope alone dropped the fold's `200` and let the
                    // reader decide a contract rustc rejects.
                    Sign::Opaque(env) => Sign::union_env(env, self.range_of(v)),
                    _ => None,
                };
                let cv = smt::word(!val & mask, w);
                return Ok((cv, Sign::Opaque(operand)));
            }
            let w = smt::bits(v);
            let cv = smt::bxor(v, smt::all_ones(w));
            self.record_range_union(cv, v, v);
            return Ok((cv, sgn));
        }
        self.parse_atom()
    }

    fn parse_atom(&mut self) -> Result<(Var, Sign), SpecError> {
        let (v, s) = self.parse_primary()?;
        self.parse_wrapping_postfix(v, s)
    }

    /// A postfix `.wrapping_add(arg)` / `.wrapping_sub(arg)` / `.wrapping_mul(arg)`
    /// / `.wrapping_neg()` on a value -- the method-call spelling of the wrapping
    /// operators the contract language already models.
    ///
    /// The desugaring is exact, and that is the whole reason it can be read: `a + b`
    /// in a contract *is* a bit-vector add, which wraps at the operand width, so
    /// `a.wrapping_add(b)` and `a + b` denote the same term. The one deliberate
    /// difference is the constant-overflow refusal: `200 + 100` is refused because
    /// rustc rejects that constant expression, where `200u8.wrapping_add(100u8)` is
    /// a legal program whose value is `44`, so the sugar must *not* run the fold --
    /// the engine's own wrapping operator is the value Rust computes. The operands'
    /// literals are still range-checked against the type they meet (`x.wrapping_add(300)`
    /// is a rustc error for its `300`), which is what `align_widths` does.
    ///
    /// The receiver's type must be *fixed*. Rust refuses `1.wrapping_add(2)` with
    /// `E0689` (the receiver is an ambiguous `{integer}`), so a receiver that is
    /// only a bare literal is refused rather than silently given the scope's width.
    fn parse_wrapping_postfix(&mut self, v: Var, sgn: Sign) -> Result<(Var, Sign), SpecError> {
        let (mut v, mut sgn) = (v, sgn);
        loop {
            if !matches!(self.peek(), Some(Tok::Op(o)) if o == ".") {
                return Ok((v, sgn));
            }
            let Some(Tok::Ident(name)) = self.toks.get(self.pos + 1).cloned() else {
                return Ok((v, sgn));
            };
            let takes_arg = match name.as_str() {
                "wrapping_add" | "wrapping_sub" | "wrapping_mul" => true,
                "wrapping_neg" => false,
                // Any other method is left in place: the caller reports the
                // trailing token, exactly as before this sugar existed.
                _ => return Ok((v, sgn)),
            };
            if !sgn.fixes_type() {
                return Err(self.err(format!(
                    "`{name}` needs a receiver whose integer type is known; a bare literal is an \
                     ambiguous `{{integer}}` in Rust"
                )));
            }
            self.pos += 2;
            if !self.eat_op("(") {
                return Err(self.err(format!("`{name}` is a call: write `{name}(..)`")));
            }
            let (r, rs) = if takes_arg {
                self.parse_expr()?
            } else {
                (v, sgn)
            };
            if !self.eat_op(")") {
                return Err(self.err(format!("`{name}` is missing its closing `)`")));
            }
            let out = Sign::combine(sgn, rs);
            let (l, r) = self.align_widths(v, sgn, r, rs, out)?;
            v = match name.as_str() {
                "wrapping_add" => smt::add(l, r),
                "wrapping_sub" => smt::sub(l, r),
                "wrapping_mul" => smt::mul(l, r),
                // `wrapping_neg` is `0 - x` at the operand's width, and it is legal
                // for an *unsigned* receiver too -- `(1u8).wrapping_neg()` is `255`,
                // which the unary `-` (signed-only) deliberately refuses.
                _ => smt::sub(smt::word(0, smt::bits(l)), l),
            };
            self.record_fold_result(v, l, r, out);
            sgn = out;
        }
    }

    fn parse_primary(&mut self) -> Result<(Var, Sign), SpecError> {
        match self.peek().cloned() {
            Some(Tok::Num(n, suffix)) => {
                self.pos += 1;
                // A *suffixed* literal has a fixed Rust type: its width and sign
                // come from the suffix, not from the scope. Building it at the
                // scope's width instead lost the value's high bits -- `128i16`
                // became `0x80` in an 8-bit scope, which a later widening cast
                // sign-extended to `-128` and *verified* a false
                // `ensures: 128i16 as i32 == -128`. So it is built at its own
                // width, and the value is range-checked against the suffix.
                if let Some((w, signed)) = suffix {
                    // The engine's words are 1..=64 bits, and `smt::word` refuses a
                    // wider one by flagging the term ill-formed. A `u128`/`i128`
                    // suffix has to be refused *here*, before the range check: the
                    // check computes `1u128 << (w - 1)` and `1u128 << w`, and a
                    // shift of 128 panics in a debug build (it wraps to a wrong
                    // `max` in release). The reader cannot hold a 128-bit literal,
                    // so the contract is refused rather than decided -- the same
                    // answer `cast_chain` gives a cast to `u128`.
                    if w > 64 {
                        return Err(self.err(format!(
                            "a `{w}`-bit type suffix is wider than the engine's 64-bit words, so \
                             a literal of that type is not modelled"
                        )));
                    }
                    // A signed literal is allowed up to `2^(w-1)` because it may
                    // be negated: `-128i8` needs the literal `128i8` to exist
                    // first, and the negation is what makes the min magnitude
                    // legal. A positive use of that magnitude is a Rust error
                    // this check cannot see from here.
                    let max = if signed {
                        1u128 << (w - 1)
                    } else {
                        (1u128 << w) - 1
                    };
                    if u128::from(n) > max {
                        return Err(self.err(format!(
                            "literal `{n}` is out of range for its `{}` type suffix",
                            if signed { "i" } else { "u" }
                        )));
                    }
                    let sign = if signed { Sign::Signed } else { Sign::Unsigned };
                    let v = smt::word(n, w);
                    // Rust range-checks the *written magnitude* of a suffixed
                    // literal, not the two's-complement value it denotes: `128i8`
                    // alone is out of range, and only `-128i8` is legal, because the
                    // negation is what meets the type. Recording the signed value
                    // instead made the negation add `+128` to the envelope and refuse
                    // the valid `-128i8` (and, worse, made the positive `128i8` --
                    // which rustc rejects -- read as the in-range `-128`). Recording
                    // the magnitude, and marking the literal pristine so a direct `-`
                    // *replaces* it, keeps both right: `-128i8` reads, `128i8` is
                    // refused, and `-(-128i8)` (`128`, out of range) is refused too.
                    let mag = i128::from(n);
                    self.record_range(v, mag, mag);
                    self.bare_literals.insert(v.0 .0);
                    return Ok((v, sign));
                }
                // A literal is built wide enough to *hold* its own value, and at
                // least as wide as the widest name in scope. Both halves matter:
                //
                // * Holding the value keeps the number exact, so the width
                //   decision can be made later, per use, by `align_widths`.
                //   Building it at the scope's width instead would mask `300` to
                //   `44` for a `u8` and set the engine's ill-formed flag -- the
                //   term would then decide `Unknown`, with no hint that the
                //   contract, not the body, was at fault.
                // * The scope's width keeps the common case (`a <= 5` for a `u32`)
                //   from building a needlessly wide constant.
                let need = (u64::BITS - n.leading_zeros()).max(1) as u8;
                let scope = self
                    .args
                    .values()
                    .chain(self.ret.iter())
                    .map(|v| smt::bits(*v))
                    .max()
                    .unwrap_or(64);
                // A bare literal inside a shift *amount* is floored at the
                // amount's inferred width (see `amount_floor`): 32 bits when
                // nothing in the amount fixes a type, or a typed operand's width
                // when one does. Outside an amount there is no floor.
                let w = scope.max(need).max(self.amount_floor).min(64);
                // A *bare* literal is untyped and non-negative: its value is
                // unambiguous, but its signedness is not yet known.
                let v = smt::word(n, w);
                self.record_const(v, false);
                self.bare_literals.insert(v.0 .0);
                Ok((v, Sign::Literal))
            }
            Some(Tok::Char(c)) => {
                self.pos += 1;
                // A `char` is a 32-bit value, and it is *typed*: `'0' == 0u8` is
                // `E0308` in Rust, so `Sign::Unsigned` (which does not adapt) makes
                // `align_widths` refuse a mismatch rather than resizing the literal
                // to meet a narrower operand. The value is the Unicode scalar
                // value, exactly as `char as u32` would give it.
                let v = smt::word(u64::from(c), 32);
                self.record_const(v, false);
                Ok((v, Sign::Unsigned))
            }
            Some(Tok::Ident(name)) => {
                self.pos += 1;
                if name == "ret" || name == "result" {
                    self.name_tokens.insert(self.pos - 1);
                    let v = self.ret.ok_or_else(|| self.err(self.ret_absent))?;
                    // A trailing `.field` here means the field was not bound: the
                    // return has no such component or variant payload. `rewrite_fields`
                    // binds the ones that exist, so reaching this point with a `.`
                    // left over is a name that does not exist on the return type --
                    // report *that*, rather than the parser's "expected a comparison
                    // operator" for the stray dot.
                    if matches!(self.peek(), Some(Tok::Op(o)) if o == ".") {
                        let field = match self.toks.get(self.pos + 1) {
                            Some(Tok::Ident(f)) => f.clone(),
                            Some(Tok::Num(n, _)) => n.to_string(),
                            _ => String::new(),
                        };
                        return Err(self.err(format!(
                            "the return type has no component or variant `{field}` to read"
                        )));
                    }
                    return Ok((v, Sign::from_bool(self.ret_signed)));
                }
                if name == "true" || name == "false" {
                    // A boolean literal is a one-bit word, so a `bool`-returning
                    // function can write `ensures: ret == false`. It used to be
                    // an error here, which left such contracts unreadable; the
                    // width check then refuses a literal compared against a
                    // wider operand, which is the right refusal.
                    return Ok((smt::word(u64::from(name == "true"), 1), Sign::Literal));
                }
                // `old(name)` — the value a name held at *entry*. A reference
                // argument's name denotes the value it addresses, which the body
                // may write, so a bare `c` in an `ensures` is the value at
                // *return*; the entry value is reachable only through `old`.
                // Only a name the caller recorded an entry value for is admitted
                // (a reference-to-scalar argument); anything else is refused, so
                // `old` on a by-value argument -- whose entry value is just its
                // value, and which the body cannot change -- is not silently
                // accepted as a second spelling of the same thing.
                //
                // Gated on the `(` so an argument *named* `old` still resolves:
                // `old == 5` is the argument, `old(c)` is the operator.
                if name == "old" && matches!(self.peek(), Some(Tok::Op(o)) if o == "(") {
                    self.name_tokens.insert(self.pos - 1);
                    self.pos += 1;
                    // `old(*c)` and `old(c)` name the same entry value: the deref
                    // is the explicit spelling of the referent the bare name
                    // already denotes.
                    self.eat_op("*");
                    let Some(Tok::Ident(inner)) = self.peek().cloned() else {
                        return Err(self.err("`old(...)` must name a variable"));
                    };
                    self.pos += 1;
                    self.name_tokens.insert(self.pos - 1);
                    if !self.eat_op(")") {
                        return Err(self.err("`old(...)` takes a single name"));
                    }
                    let Some(v) = self.old_args.get(&inner).copied() else {
                        return Err(self.err(format!(
                            "`old({inner})` is not a reference argument, so its entry value \
                             is not tracked"
                        )));
                    };
                    return Ok((v, Sign::from_bool(self.is_signed_name(&inner))));
                }
                // `i16::MIN` and friends: the named bound of an integer type,
                // which is how a contract names the value it must exclude. The
                // tokenizer splits `::` into two single `:` operators, so both
                // spellings are recognized.
                let assoc = if let Some((ty, a)) = name.split_once("::") {
                    Some((ty.to_string(), a.to_string()))
                } else if matches!(self.peek(), Some(Tok::Op(o)) if o == ":") {
                    let mut it = self.toks[self.pos..].iter();
                    match (it.next(), it.next(), it.next()) {
                        (Some(Tok::Op(c1)), Some(Tok::Op(c2)), Some(Tok::Ident(a)))
                            if c1 == ":" && c2 == ":" =>
                        {
                            let a = a.clone();
                            self.pos += 3;
                            Some((name.clone(), a))
                        }
                        _ => None,
                    }
                } else {
                    None
                };
                if let Some((ty, a)) = assoc {
                    // `Mode::Idle` — an enum variant named in a contract, which is
                    // a constant of the tag's width. Checked before `type_bound`
                    // because a variant name is not an integer bound, and the two
                    // spellings (`i8::MIN`, `Mode::Idle`) are distinguished by
                    // which table has the name.
                    let key = format!("{ty}::{a}");
                    if let Some((k, w)) = self.variant_consts.get(&key).copied() {
                        return Ok((self.unshared_const(k, w), Sign::Literal));
                    }
                    if self.enum_args.contains(&ty) {
                        return Err(self.err(format!(
                            "`{ty}` has no variant `{a}` (or its layout was not readable)"
                        )));
                    }
                    // A module-qualified `const` item: `requires: x <= low::K`. The
                    // dump prints both the definition and the use with the same
                    // path (`const low::K`), so the table is keyed by it and this is
                    // an exact lookup -- the same key the executor folds the body's
                    // `low::K` with. A module-nested item is resolved only when the
                    // contract spells the path, which is what keeps it from
                    // colliding with a top-level constant of the same last segment.
                    if let Some(c) = self.consts.get(&format!("{ty}::{a}")) {
                        let key = format!("{ty}::{a}");
                        let c = c.clone();
                        return self.const_item(&key, &c);
                    }
                    if let Some((k, w)) = type_bound(&ty, &a) {
                        // The bound is built at the width of the type it *names*,
                        // not at the widest name in scope. `i8::MIN` is the bit
                        // pattern `0x80`, which is exactly 8 bits; widening it to
                        // a 64-bit `128` and then narrowing it back would test
                        // `128 <= i8::MAX` and refuse the constant as out of range
                        // for a signed 8-bit operand -- a refusal of a bound that
                        // is by definition in range.
                        //
                        // It is built as a term *of its own* rather than the shared
                        // `word(k, w)`: `i8::MIN` and a bare or suffixed `128` are
                        // the same bit pattern and hash-cons to one term, so an
                        // out-of-range envelope recorded for the literal (`128i8`
                        // records `128`) was read back as the bound's and refused a
                        // valid `y == -128i8 && y == i8::MIN`. The bound's fit is
                        // known by construction, so it must not inherit a literal's
                        // envelope. See `unshared_const`.
                        return Ok((self.unshared_const(k, w), Sign::from_bool(ty.starts_with('i'))));
                    }
                    return Err(self.err(format!("unknown constant `{ty}::{a}`")));
                }
                // An argument wins over a constant of the same name, so a contract
                // that names an argument keeps resolving to it and the constant
                // table only ever adds names the reader would otherwise refuse.
                // Rust lets a parameter shadow a `const` of the same name, and
                // reading the constant there would bind the wrong value -- a false
                // proof, not a refusal.
                if let Some(v) = self.args.get(&name).copied() {
                    self.name_tokens.insert(self.pos - 1);
                    let s = self.is_signed_name(&name);
                    return Ok((v, Sign::from_bool(s)));
                }
                // A named `const` item: `requires: x <= LIMIT`, where the body
                // reads `_0 = const LIMIT`. Resolved from the program's own table,
                // the same one the executor folds the use site from, so the
                // contract and the body name one value and cannot disagree. Built
                // at the *item's* own width and sign -- the dump prints the body
                // const-evaluated and typed (`const 10_u8`) -- and as a term of its
                // own, so an envelope recorded for a literal of the same bit pattern
                // is not read back as this constant's.
                //
                // Checked *after* the associated-constant forms (`i8::MIN`), which
                // are recognized above: a name like `i8::MIN` is not in the table,
                // and a table entry is always a plain identifier.
                if let Some(c) = self.consts.get(&name) {
                    let c = c.clone();
                    return self.const_item(&name, &c);
                }
                Err(self.err(format!("unknown name `{name}` (not an argument)")))
            }
            Some(Tok::Op(o)) if o == "(" => {
                // The lookahead must run with the cursor *on* the `(`, so it is
                // taken before the cursor advances.
                let is_pred = self.paren_is_predicate();
                self.pos += 1;
                // A group whose contents are a *predicate* (`(x == 1)`) is a
                // `bool`-typed operand, not arithmetic: `ret == (x == 1)` is the
                // natural way to write a `bool`-returning function's postcondition,
                // and reading the group with `parse_expr` (which cannot consume a
                // comparator) refused it with "missing `)`". The predicate is turned
                // into a one-bit value (`ite(p, 1, 0)`), the width a `bool` has, so
                // the surrounding `==` compares two `bool`s exactly as Rust does.
                // Which meaning a `(` has is decided by the same lookahead the
                // comparison level uses, so a parenthesized *arithmetic* expression
                // (`(x + 1)`) still parses as arithmetic.
                if is_pred {
                    let group_start = self.pos - 1;
                    let p = self.parse_or()?;
                    if !self.eat_op(")") {
                        return Err(self.err("missing `)`"));
                    }
                    // Record the group so an enclosing conjunct's payload-guard scan
                    // does not re-guard its inner payload names (see
                    // `guarded_groups`).
                    self.guarded_groups.push((group_start, self.pos));
                    return Ok((smt::ite(p, smt::word(1, 1), smt::word(0, 1)), Sign::Unsigned));
                }
                let (v, s) = self.parse_expr()?;
                if !self.eat_op(")") {
                    return Err(self.err("missing `)`"));
                }
                Ok((v, s))
            }
            Some(Tok::BadNum) => {
                Err(self.err("a numeric literal that is not an exact integer (bad digit for its radix, or past u64)"))
            }
            Some(Tok::BadChar) => {
                Err(self.err("a character literal that is not an exact Unicode scalar value (an unknown escape, a multi-character literal, or a missing quote)"))
            }
            Some(t) => Err(self.err(format!("unexpected token {t:?}"))),
            None => Err(self.err("unexpected end of contract")),
        }
    }

    /// Apply any `as <type>` casts that immediately follow an atom, returning the
    /// value and its signedness.
    ///
    /// The result of `x as T` has `T`'s width and `T`'s sign, and it *extends*
    /// rather than reinterprets: `-1i8 as i16` is `-1`, not `255`. A widening cast
    /// of a signed source sign-extends; an unsigned one zero-fills, which is
    /// `truncate`; a narrowing cast keeps the low bits, which `sign_extend` and
    /// `truncate` both do when the target is no wider.
    ///
    /// An unknown source sign is a refusal, not a guess, for the same reason the
    /// body refuses one: zero-filling a signed value would prove `-1i8 as i16 ==
    /// 255`, a reachable false proof, and sign-extending an unsigned one would
    /// turn `255u8 as u16` into `65535`. Guessing the sign is exactly the failure
    /// this crate exists to avoid.
    ///
    /// A cast *chain* (`x as u16 as u32`) applies left to right, and each step's
    /// source sign is the previous step's *target* sign -- which the cast just
    /// set, so it is always known. That is what makes the chain well-defined even
    /// when the first source's sign was not.
    fn cast_chain(&mut self, v: Var, sgn: Sign) -> Result<(Var, Sign), SpecError> {
        let (mut v, mut sgn) = (v, sgn);
        while matches!(self.peek(), Some(Tok::Ident(n)) if n == "as") {
            let Some(Tok::Ident(ty_name)) = self.toks.get(self.pos + 1).cloned() else {
                // `as` with no type after it is not a cast; leave it for the
                // caller to report as a trailing token rather than consuming it.
                break;
            };
            let ty = Ty::parse(&ty_name);
            let Some(w) = ty.width() else {
                break;
            };
            // The engine's words are 1..=64 bits, so a cast to `u128`/`i128` has
            // no width to truncate or extend to. Refusing it here is what stops
            // the cast from reaching `truncate`, whose width assertion would take
            // the whole run down with a panic instead of reporting this function
            // as undecided. A `break` would be wrong: it would leave `as` as a
            // trailing token and blame the syntax, when the cast is well-formed
            // Rust and it is the *engine* that cannot hold the result.
            if w > 64 {
                return Err(self.err(format!(
                    "`{ty_name}` is wider than the engine's 64-bit words, so a cast to it is not \
                     modelled"
                )));
            }
            self.pos += 2;
            // A *widening* cast of an untyped operand would have to guess whether
            // to sign-extend or zero-fill, and the two disagree (`!0 as i16` is
            // `-1` or `255`), so an opaque untyped operand is refused. A narrowing
            // cast keeps the low bits either way, so it is exact. A bare literal is
            // non-negative and zero-extends exactly.
            let src_signed = if sgn.ambiguous() {
                if w > smt::bits(v) {
                    return Err(self.err(
                        "a widening cast of a sign-ambiguous constant is not modelled: it would \
                         have to guess whether to sign-extend or zero-fill",
                    ));
                }
                false
            } else {
                sgn.eval()
            };
            v = if src_signed { smt::sign_extend(v, w) } else { smt::truncate(v, w) };
            sgn = Sign::from_bool(ty.is_signed());
        }
        Ok((v, sgn))
    }
}

/// The parsed head of a `struct` declaration.
///
/// Two shapes are recognised, and they are distinct because they carry their
/// fields differently. A *named-field* struct (`pub struct C { lo: u8 }`) may
/// close on its head line or need a cursor to collect the body; that is the
/// `closed_inline` flag, which keeps an open cursor from swallowing every
/// following line as a field and silently dropping the functions after it.
/// A *tuple* struct (`pub struct P(pub u8, pub u8);`) carries its fields in the
/// head itself, numbered by position, and needs no cursor.
///
/// A unit struct is neither: it has no fields to project, so it is recorded as a
/// *zero-field* layout. That is what lets a `Drop` on a unit struct run (the
/// field-glue check finds no fields rather than refusing the type as an unknown
/// container), while a contract naming `.0` on it is still an "unknown field"
/// refusal, because the layout has no field 0.
enum StructHead {
    Named { name: String, closed_inline: bool },
    Tuple { name: String, fields: Vec<(String, String)> },
    /// A unit struct: `struct Guard;` — a layout with no fields.
    Unit { name: String },
}

/// The struct layout for a type name, qualified-first.
///
/// Shared by [`Specs::struct_of`] and the drop-glue check, so the two cannot
/// disagree about which layout a type name names. See `Specs::struct_of` for the
/// lookup order and why the bare fallback is safe.
pub(crate) fn struct_lookup<'a>(
    structs: &'a BTreeMap<String, StructDef>,
    name: &str,
) -> Option<&'a StructDef> {
    if let Some(def) = structs.get(name) {
        return Some(def);
    }
    let no_generics = name.split('<').next().unwrap_or(name);
    if let Some(def) = structs.get(no_generics) {
        return Some(def);
    }
    // A **qualified** name may not fall back to a bare layout. The bare key is
    // only ever back-inserted for a name that is unique crate-wide, so it is
    // sound *as an answer to a bare query* -- the dump prints a name bare exactly
    // when rustc could shorten it that far. A qualified query (`m::Outer`) means
    // rustc could **not** shorten it, so at least two types share that tail, and
    // the bare key is then some *other* type's layout. Falling back would read it
    // and prove a contract about the wrong fields.
    //
    // Measured, and it was a false proof: `pub struct Outer { lo, hi }` at the
    // crate root plus `pub mod m { pub struct Outer { hi, lo } }` -- a one-line
    // module, whose inline struct the line-oriented scanner never sees. The query
    // is `m::Outer` (qualified, because the bare name is ambiguous), the only
    // layout is the crate-root one, and both `requires: o.hi == 5; ensures: ret ==
    // 5` on a body returning `o.lo` and its mirror were **verified** -- the two
    // fields were the same variable. Rustc's own execution gives `ret = 7` for
    // `{ hi: 5, lo: 7 }`. A miss here is a refusal, which the caller reports.
    if no_generics.contains("::") {
        return None;
    }
    structs.get(no_generics)
}

fn struct_head(line: &str) -> Option<StructHead> {
    let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
    let rest = t.strip_prefix("struct ")?;
    let name = rest.split(|c: char| c == '{' || c == '(' || c == '<' || c == ';' || c.is_whitespace()).next()?;
    if name.is_empty() {
        return None;
    }
    // A tuple struct: the parenthesised list is the field list, and its
    // position in the list *is* the MIR field index, exactly as a named
    // struct's declaration order is. `pub u8` and a bare `u8` are the same
    // field, so the `pub` is stripped the way a named field's is.
    if let Some(open) = rest.find('(') {
        // The brace form wins if a `{` precedes the `(`: `struct S { f: fn(u8) }`
        // has a paren inside a field type, not a tuple body.
        let brace = rest.find('{');
        if brace.is_none() || open < brace.unwrap() {
            let close = rest[open + 1..].find(')')? + open + 1;
            let inner = &rest[open + 1..close];
            let fields = split_top_level(inner, ',')
                .into_iter()
                .enumerate()
                .filter_map(|(i, f)| {
                    let f = f.trim();
                    if f.is_empty() {
                        return None;
                    }
                    let f = f.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
                    // A tuple field cannot be empty and has no name of its own,
                    // so its name is its index. A field type with a trailing
                    // attribute is left as-is: `Ty::parse` reads the front of it,
                    // and an unreadable one widens to `Other`, which refuses a
                    // contract on it rather than fabricating a width.
                    Some((i.to_string(), f.to_string()))
                })
                .collect();
            return Some(StructHead::Tuple { name: name.to_string(), fields });
        }
    }
    // Only a brace body on this line is a named-field struct.
    let Some(open) = rest.find('{') else {
        // A `;`-terminated head with no `(` and no `{` is a unit struct
        // (`struct Guard;`) or a generic unit struct (`struct Marker<T>;`). Both
        // are a zero-field layout, which is what the drop-glue check needs.
        //
        // The `;` is required: a head whose brace is on a *later* line (a
        // `where`-clause, say) must not be read as unit here, or its real fields
        // would be lost and a field with its own destructor would look glue-free.
        // That shape stays `None` — an unrecorded layout, which refuses rather
        // than guesses.
        if rest.trim_end().ends_with(';') {
            return Some(StructHead::Unit { name: name.to_string() });
        }
        return None;
    };
    // Closed on the head line iff a `}` follows the `{`.
    let closed_inline = rest[open + 1..].contains('}');
    Some(StructHead::Named { name: name.to_string(), closed_inline })
}

/// Pull `(field, type)` out of one line of a struct body.
///
/// The line looks like `pub lo: u8,` or `lo: u8,`. A line that is not a
/// `name: type` pair (a nested item, a comment, an attribute) is skipped, so an
/// unexpected shape loses a field rather than inventing one — and a lost field
/// makes a contract naming it a refusal, which is the safe direction.
fn struct_field(line: &str) -> Option<(String, String)> {
    let t = line.trim();
    if t.is_empty() || t.starts_with("//") || t.starts_with('#') {
        return None;
    }
    let t = t.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
    let (name, ty) = t.split_once(':')?;
    let name = name.trim();
    if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
        return None;
    }
    // Strip a trailing comma and any `#[...]` attribute tail.
    let ty = ty.split(',').next().unwrap_or(ty).trim();
    if ty.is_empty() {
        return None;
    }
    Some((name.to_string(), ty.to_string()))
}
/// The parsed head of an `enum` declaration.
///
/// The three cases are distinct on purpose. A *one-line* body carries its
/// variants already; a *multi-line* body needs a cursor to collect them; and a
/// body whose explicit discriminant cannot be read is *refused* -- and, because
/// its closing brace has already been seen, that refusal must not be mistaken for
/// "a cursor is needed". Returning the multi-line case for a refused one-line body
/// would leave the cursor open past the brace and swallow every following line,
/// including contracts, so those functions would silently leave the check set.
enum EnumHead {
    /// A one-line body, fully parsed.
    Inline(Vec<(String, Vec<Ty>, u64)>),
    /// A multi-line body whose `{` opens the last thing on the line.
    MultiLine,
    /// A body this reader refuses (an unreadable discriminant). The layout is
    /// dropped, and the enum is *closed*: nothing after it belongs to it.
    Refused,
}

/// Pull the enum name out of a `pub enum Name {` head line.
///
/// Only a *braced* enum is recognised, and only when the body opens on the same
/// line. An enum whose variants are all written inline on the head line
/// (`pub enum E { A, B }`) is not read: the variants would have to be split out of
/// the head text, and getting that wrong would number the variants wrongly, which
/// is the one thing this layout must not do. A missing layout makes a contract
/// naming a variant a refusal, which is the safe direction.
fn enum_head(line: &str) -> Option<(String, EnumHead)> {
    let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
    let rest = t.strip_prefix("enum ")?;
    // A generic enum (`enum E<T>`) is read for its name, but a variant payload
    // naming `T` has no bit width and is skipped downstream.
    let name = rest.split(|c: char| c == '{' || c == '<' || c.is_whitespace()).next()?;
    if name.is_empty() {
        return None;
    }
    let open = rest.find('{')?;
    let after = &rest[open + 1..];
    // A one-line body (`pub enum E { A, B }`): the variants are split out of the
    // head text itself. Splitting on top-level commas is exactly what the
    // multi-line reader does per line, so the two agree on numbering by
    // construction.
    if let Some(close) = after.rfind('}') {
        let inner = &after[..close];
        let mut def = EnumDef::default();
        for v in split_top_level(inner, ',') {
            match enum_variant(&v) {
                VariantLine::Variant { name, payload, explicit } => {
                    push_variant(&mut def, name, payload, explicit);
                }
                VariantLine::NotAVariant => {}
                // An unreadable discriminant on a one-line body refuses the whole
                // enum, the same as the multi-line path. The body is already
                // closed, so this is a *refusal*, not an open cursor.
                VariantLine::UnreadableDiscriminant => {
                    return Some((name.to_string(), EnumHead::Refused))
                }
            }
        }
        return Some((name.to_string(), EnumHead::Inline(def.variants)));
    }
    // A multi-line body: the brace must end the line, so nothing but the brace
    // follows it.
    if !after.trim().is_empty() {
        return None;
    }
    Some((name.to_string(), EnumHead::MultiLine))
}

/// One line of an enum body, as far as the layout reader can tell.
enum VariantLine {
    /// A variant, with the explicit discriminant when the source wrote a literal
    /// one (`B = 3`).
    Variant {
        /// The variant's name.
        name: String,
        /// Its payload types; empty for a unit or struct variant.
        payload: Vec<Ty>,
        /// The explicit discriminant, when the source gave a literal one.
        explicit: Option<u64>,
    },
    /// A line that is not a variant (a comment, an attribute, a nested item).
    NotAVariant,
    /// A variant whose explicit discriminant is not a literal this reader can
    /// evaluate. The *whole* layout is refused: dropping the variant would shift
    /// every later discriminant, and guessing one would put a contract on the
    /// wrong tag. A refused layout makes a contract naming any of its variants a
    /// refusal, which is the safe direction.
    UnreadableDiscriminant,
}

/// Pull one variant out of a line of an enum body.
///
/// The line looks like `Off,`, `Idle,`, `Data(u8),`, `Pair { x: u8, y: u8 },` or
/// `B = 3,`. A unit variant and a tuple variant are both modelled; a *struct*
/// variant records no payload types, so a contract naming one of its fields is
/// refused rather than bound to a wrong index. A line that is not a variant (a
/// nested item, an attribute, a comment) is skipped, which loses a variant rather
/// than inventing one -- and a lost variant shifts every discriminant after it, so
/// the skip is restricted to lines that clearly are not variants.
fn enum_variant(line: &str) -> VariantLine {
    // A trailing line comment is not part of the variant. Stripping it *first*
    // matters because the comma that ends the variant sits before the comment:
    // `B = 3, // tag` would otherwise keep the comma (the line no longer ends in
    // one) and the discriminant reader would reject the whole line, dropping the
    // layout and skipping every contract that names one of its variants.
    let line = strip_line_comment(line);
    let t = line.trim().trim_end_matches(',').trim();
    if t.is_empty() || t.starts_with("//") || t.starts_with('#') || t.starts_with("}") {
        return VariantLine::NotAVariant;
    }
    let t = t.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
    // The variant name is the leading identifier.
    let name: String = t.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
    if name.is_empty() || !name.chars().next().map(|c| c.is_alphabetic() || c == '_').unwrap_or(false)
    {
        return VariantLine::NotAVariant;
    }
    let after = t[name.len()..].trim_start();
    let (payload, rest) = if after.is_empty() {
        // A unit variant: nothing follows the name.
        (Vec::new(), "")
    } else if let Some(inner_rest) = after.strip_prefix('(') {
        // A tuple variant: `Name(u8, u16)`. The payload types are what a `match`
        // arm's downcast reads, so they are recorded even though the tag does not
        // need them.
        let Some(close) = inner_rest.find(')') else { return VariantLine::NotAVariant };
        let inner = inner_rest[..close].trim();
        let tys = if inner.is_empty() {
            Vec::new()
        } else {
            split_top_level(inner, ',').iter().map(|t| Ty::parse(t.trim())).collect()
        };
        (tys, inner_rest[close + 1..].trim_start())
    } else if after.starts_with('{') {
        // A struct variant: the fields are not modelled, but the *variant* is, so
        // it still takes its discriminant.
        let Some(close) = after.rfind('}') else { return VariantLine::NotAVariant };
        (Vec::new(), after[close + 1..].trim_start())
    } else if after.starts_with('=') {
        (Vec::new(), after)
    } else {
        return VariantLine::NotAVariant;
    };
    // An explicit discriminant: `B = 3`. Only a literal is accepted; an
    // expression (`= 1 << 4`) would have to be evaluated, and evaluating it wrongly
    // is exactly the failure this reader exists to avoid, so the layout is refused
    // instead.
    if rest.is_empty() {
        return VariantLine::Variant { name, payload, explicit: None };
    }
    let Some(expr) = rest.strip_prefix('=') else { return VariantLine::NotAVariant };
    match parse_discriminant_literal(expr) {
        Some(d) => VariantLine::Variant { name, payload, explicit: Some(d) },
        None => VariantLine::UnreadableDiscriminant,
    }
}

/// A discriminant literal: decimal, `0x`/`0b`/`0o`, with an optional type suffix.
///
/// Only a literal is accepted. Anything else -- an expression, a `const` path, a
/// negative value under a signed `repr` -- returns `None`, and the caller refuses
/// the whole layout rather than guessing a number.
fn parse_discriminant_literal(s: &str) -> Option<u64> {
    let s = s.trim().trim_end_matches(';').trim();
    if s.is_empty() {
        return None;
    }
    // A negative literal (`= -1` under a signed `repr`) is refused: its value
    // depends on the tag's width, which the reader does not know here.
    if s.starts_with('-') {
        return None;
    }
    let body = strip_int_suffix(s);
    let (radix, digits) = if let Some(r) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
        (16u32, r)
    } else if let Some(r) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
        (2, r)
    } else if let Some(r) = body.strip_prefix("0o").or_else(|| body.strip_prefix("0O")) {
        (8, r)
    } else {
        (10, body)
    };
    // The whole remainder must be digits (underscores allowed), so `1 << 4` is
    // refused rather than silently read as `1`. A partial read is exactly the
    // kind of wrong number this reader exists to avoid.
    let mut seen = false;
    for c in digits.chars() {
        if c == '_' {
            continue;
        }
        if !c.is_digit(radix) {
            return None;
        }
        seen = true;
    }
    if !seen {
        return None;
    }
    let digits: String = digits.chars().filter(|c| *c != '_').collect();
    u64::from_str_radix(&digits, radix).ok()
}

/// Drop a trailing `// …` line comment, respecting string and char literals.
///
/// The enum reader is handed one trimmed source line at a time, and a comment on
/// that line is not part of the variant. A `//` inside a string or character
/// literal is not a comment, so the scan tracks those; a variant line has no such
/// literal in practice, but the scan keeps the rule true by construction rather
/// than by luck.
fn strip_line_comment(line: &str) -> &str {
    let bytes = line.as_bytes();
    let mut i = 0;
    let mut in_str = false;
    let mut in_char = false;
    while i < bytes.len() {
        let c = bytes[i];
        if in_str {
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == b'"' {
                in_str = false;
            }
        } else if in_char {
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == b'\'' {
                in_char = false;
            }
        } else if c == b'"' {
            in_str = true;
        } else if c == b'\'' {
            in_char = true;
        } else if c == b'/' && bytes.get(i + 1) == Some(&b'/') {
            return &line[..i];
        }
        i += 1;
    }
    line
}

/// Drop a trailing integer type suffix (`3u8`, `0x10_i32`) if one is present.
fn strip_int_suffix(s: &str) -> &str {
    for suf in [
        "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
    ] {
        if let Some(head) = s.strip_suffix(suf) {
            return head.trim_end_matches('_');
        }
    }
    s
}

/// Push a variant, computing its discriminant.
///
/// Without an explicit value the discriminant is the previous one plus one,
/// starting at zero -- rustc's rule. The explicit value is stored as written, so
/// a variant after it continues from *that* value and not from its position.
fn push_variant(def: &mut EnumDef, name: String, payload: Vec<Ty>, explicit: Option<u64>) {
    let d = match explicit {
        Some(d) => d,
        None => def.variants.last().map(|(_, _, d)| d + 1).unwrap_or(0),
    };
    def.variants.push((name, payload, d));
}

/// The layout of `Option<T>` or `Result<T, E>`, reconstructed from the type's
/// own generic arguments.
///
/// These are the two enums a real function reads without any source file
/// declaring them: `checked_add` returns `Option<u8>`, and `?` threads a
/// `Result`. `variant_index` already knows their fixed numbering
/// (`None`/`Ok` = 0, `Some`/`Err` = 1) for a *construction*; this gives an
/// *argument* of the same type a tag and payload seeds, so a `match` on it is
/// modelled instead of refused as an unmodelled switch discriminant.
///
/// `Option`'s payload type is the type argument (`Option<u8>` → `Some(u8)`);
/// `Result`'s is its two type arguments in order (`Result<T, E>` → `Ok(T)`,
/// `Err(E)`). The split is top-level, so a nested type (`Result<Option<u8>, u8>`)
/// stays one argument rather than being cut at its own comma.
///
/// A *declared* enum always wins — the caller consults `enums` first — so a user
/// `enum E { Some, None }` is not read as `Option`. An unrecognised spelling
/// yields `None`, which leaves the argument unbound and the function refused, the
/// conservative direction.
pub fn std_enum_def(name: &str) -> Option<EnumDef> {
    let name = name.trim();
    let inner = |head: &str| -> Option<String> {
        let rest = name.strip_prefix(head)?.trim_start();
        if !rest.starts_with('<') {
            return None;
        }
        // The opening `<` is still in `rest`, so the scan starts at depth 0 and
        // the matching `>` is the index where the depth returns to 0.
        let close = {
            let mut d = 0i32;
            let mut end = None;
            for (i, c) in rest.char_indices() {
                match c {
                    '<' => d += 1,
                    '>' => {
                        d -= 1;
                        if d == 0 {
                            end = Some(i);
                            break;
                        }
                    }
                    _ => {}
                }
            }
            end?
        };
        let args = &rest[1..close];
        // Reject anything after the closing `>` that is not whitespace, so a
        // spelling like `Option<u8>X` is not silently read as `Option<u8>`.
        if !rest[close + 1..].trim().is_empty() {
            return None;
        }
        Some(args.to_string())
    };
    let variant = |vname: &str, payload: Vec<Ty>, d: u64| (vname.to_string(), payload, d);
    if let Some(args) = inner("Option") {
        let t = Ty::parse(args.trim());
        return Some(EnumDef {
            variants: vec![variant("None", vec![], 0), variant("Some", vec![t], 1)],
        });
    }
    if let Some(args) = inner("Result") {
        let parts = split_top_level(&args, ',');
        if parts.len() != 2 {
            return None;
        }
        let ok = Ty::parse(parts[0].trim());
        let err = Ty::parse(parts[1].trim());
        return Some(EnumDef {
            variants: vec![variant("Ok", vec![ok], 0), variant("Err", vec![err], 1)],
        });
    }
    None
}

/// The `(success discriminant, failure discriminant)` of an enum-returning
/// function's type, for `ret.is_ok()` and friends.
///
/// `Option` and `Result` are the two standard enums with a fixed numbering
/// (`Some`/`Err` are the success variant at 1, `Ok`/`None` at 0). A *declared* enum
/// resolves through its own layout, which is the map the caller passes in; a
/// standard enum has no declared layout, so it is recognised by name. A return type
/// that is neither is `None`, and the parser refuses the methods rather than testing
/// a tag that does not exist.
pub fn enum_ret_discriminants(
    ret_ty: &Ty,
    enums: &BTreeMap<String, EnumDef>,
) -> Option<(u64, u64)> {
    let def = ret_enum_def(ret_ty, enums)?;
    let find = |n: &str| def.variants.iter().find(|(vn, _, _)| vn == n).map(|(_, _, d)| *d);
    let ok = find("Ok").or_else(|| find("Some"))?;
    let err = find("Err").or_else(|| find("None"))?;
    Some((ok, err))
}

/// The [`EnumDef`] an enum-returning function's type names, whether the enum is
/// declared in the source or is one of the two standard ones.
///
/// This is the layout `enum_ret_discriminants` reads its tag pair from and that
/// [`bind_ret_payloads`] reads its payload types from, so `ret.is_ok()` and
/// `ret.Ok` agree about the numbering and the payload width by construction: there
/// is one lookup.
pub fn ret_enum_def(ret_ty: &Ty, enums: &BTreeMap<String, EnumDef>) -> Option<EnumDef> {
    let Ty::Other(name) = ret_ty else { return None };
    let bare = strip_generics(name);
    let segs: Vec<&str> = bare.split("::").filter(|s| !s.is_empty()).collect();
    let short = segs.last().copied().unwrap_or(&bare);
    if let Some(def) = enums.get(short).or_else(|| enums.get(&bare)) {
        return Some(def.clone());
    }
    // A standard enum is recognised from the *full* type, because its payloads are
    // its generic arguments: `Option<u8>` gives `Some: u8`, and the stripped `short`
    // has no arguments left to read. The declared-layout lookup above keeps a user
    // `enum Option { .. }` winning over the built-in numbering. A turbofished
    // spelling (`Option::<u8>`) is the same type, so the `::` before `<` is dropped.
    std_enum_def(&name.trim().replace("::<", "<"))
}

/// Whether a contract clause names `ret.<vname>` (or `result.<vname>`).
///
/// The same textual scan `named_ret_components` uses for `ret.N`, but matching a
/// variant *name* rather than a component index. It decides which payloads the
/// probe binds; a name that is not a variant is left for the parser to refuse.
fn names_ret_variant(text: &str, vname: &str) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i].is_alphabetic() || chars[i] == '_' {
            let start = i;
            while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            if (ident == "ret" || ident == "result") && chars.get(i) == Some(&'.') {
                let j = i + 1;
                let mut k = j;
                while k < chars.len() && (chars[k].is_alphanumeric() || chars[k] == '_') {
                    k += 1;
                }
                let field: String = chars[j..k].iter().collect();
                if field == vname {
                    return true;
                }
            }
            continue;
        }
        i += 1;
    }
    false
}

/// Bind the return payloads a contract names, for the *run*.
///
/// `projs` is the executor's return-payload list, keyed by discriminant; the
/// payload's own type comes from the enum's layout, so the contract's `ret.Ok`
/// and the body's `((_0 as Ok).0)` name the same variable. A variant the contract
/// names but no path produced stays unbound, so a postcondition about it is
/// refused rather than checked against a fabricated value -- the same rule
/// `ret.N` follows.
pub fn bind_ret_payloads(
    fields: &mut FieldEnv,
    ret_ty: &Ty,
    enums: &BTreeMap<String, EnumDef>,
    tag: Var,
    projs: &[(u64, Var)],
    ensures: &[String],
) {
    let Some(def) = ret_enum_def(ret_ty, enums) else { return };
    for (vname, payload, disc) in &def.variants {
        let Some(first) = payload.first() else { continue };
        if first.width().is_none() {
            continue;
        }
        if !ensures.iter().any(|e| names_ret_variant(e, vname)) {
            continue;
        }
        if let Some((_, v)) = projs.iter().find(|(k, _)| k == disc) {
            fields.bind_ret_payload(vname, *v, tag, *disc, first.is_signed());
        }
    }
}

/// The generics-stripped head of a type name, so `Option::<u8>` and `Option<u8>`
/// both read as `Option`.
fn strip_generics(s: &str) -> String {
    crate::mir::parse::strip_generics(s)
}

/// Bind every field of every struct-typed argument to a symbolic variable.
///
/// A struct argument has no width of its own (`Ty::Other("Config")`), so it gets
/// no variable in [`arg_vars`] and a contract that names it directly is refused.
/// Its *fields* do have widths, and those are what a contract wants to talk
/// about. Each field becomes its own symbolic input, so `c.lo` and `c.hi` are
/// independent — which is the honest model: the frontend has no way to know the
/// caller's invariant relating them, so assuming one would be unsound.
///
/// The struct's layout comes from `structs`, read from the same source as the
/// contract. A struct that is not there yields no bindings, and a contract naming
/// one of its fields is then refused by the parser as an unknown name.
pub fn field_env(
    f: &crate::mir::parse::MirFn,
    structs: &BTreeMap<String, StructDef>,
    enums: &BTreeMap<String, EnumDef>,
) -> FieldEnv {
    field_env_named(f, None, structs, enums)
}

/// [`field_env`], with the contract's own names for the arguments.
///
/// An inherited trait contract names a field `c.lo` where `c` is the
/// *declaration's* name for a parameter the implementation may call something
/// else. The field bindings are keyed by the argument name, so they have to be
/// built under the contract's name or the contract's `c.lo` resolves to nothing --
/// and a contract that resolves to nothing is refused, not guessed at.
pub fn field_env_named(
    f: &crate::mir::parse::MirFn,
    rename: Option<&ArgRename>,
    structs: &BTreeMap<String, StructDef>,
    enums: &BTreeMap<String, EnumDef>,
) -> FieldEnv {
    let contract_name = |l: crate::mir::parse::LocalIdx| -> String {
        rename
            .and_then(|r| r.name_of(l))
            .map(|s| s.to_string())
            .unwrap_or_else(|| f.name_of(l))
    };
    // `base` is one past the highest local the function declares. Every local is
    // seeded at its own index before any field variable is read, so starting here
    // keeps the two index spaces disjoint for any function, not just a small one.
    let mut env =
        FieldEnv { base: f.locals.keys().max().map(|m| m + 1).unwrap_or(0), ..Default::default() };
    // Every source name in scope, recorded before any binding is generated: the
    // mangled names are checked against this set, so a generated binding can
    // never shadow an argument of the same name.
    for &l in &f.arg_locals {
        env.declared.insert(contract_name(l));
    }
    for &l in &f.arg_locals {
        let Some(ty) = f.ty_of(l) else { continue };
        // A reference to a struct is read through: `&Config` and `Config` have the
        // same fields, and the executor treats `*_1` as `_1`.
        let base = match ty {
            Ty::Ref(inner) => inner.as_ref(),
            other => other,
        };
        let arg = contract_name(l);
        // A slice argument: `&[u8]`. Its length is a symbolic input, and its
        // elements are bound on demand (by `bind_index_refs` for the contract and
        // by the executor for the body).
        //
        // A *generic* `&[T]` has no element width (`elem.width()` is `None`), but
        // its length is still a value: `v.len()`/`v.is_empty()` read only the
        // length. Binding it with the `0` sentinel keeps those answerable while
        // every element operation stays refused, which is what lets an ordinary
        // generic slice helper decide instead of being dropped whole.
        if let Ty::Slice(elem) = base {
            match elem.width() {
                Some(w) => {
                    env.bind_indexed_len(l, &arg, w, elem.is_signed());
                }
                None => {
                    env.bind_indexed_len(l, &arg, 0, false);
                }
            }
            continue;
        }
        // An array argument: `[u8; 4]`. Its length is the constant in its type,
        // so unlike a slice there is nothing for the caller to choose; the
        // elements are still distinct inputs per index.
        if let Ty::Array(elem, n) = base {
            if let Some(w) = elem.width() {
                env.bind_array_len(l, &arg, w, elem.is_signed(), *n);
            }
            continue;
        }
        let Ty::Other(name) = base else { continue };
        // An enum argument: its tag is a symbolic input with the enum's arity as
        // its domain, and each variant's payload is its own input. Checked before
        // the struct path because an enum name is an `Other` too, and binding it
        // as a struct with no fields would silently lose the tag.
        //
        // A *declared* layout always wins. `Option` and `Result` are the two the
        // reader knows without a declaration, because `checked_*` and the `?`
        // operator hand them to real functions and no source file declares them;
        // `std_enum_def` reconstructs their layout from the type's generic
        // arguments. `Shadow` is a declared `enum { Some, None }` and is not
        // `Option`, so it must reach `enums` first.
        if let Some(def) = enums.get(name) {
            env.bind_enum(l, &arg, name, def);
            continue;
        }
        if let Some(def) = std_enum_def(name) {
            env.bind_enum(l, &arg, name, &def);
            continue;
        }
        // A `&str` argument: its length is a symbolic input exactly as a slice's
        // is (a `str` is unsized, so the length lives in the fat pointer), and
        // `s.len()`/`s.is_empty()` read only that length. Binding it with the
        // unmodelled-width sentinel keeps those answerable while every element
        // operation stays refused. A `String` is *not* `str`: its own type is
        // `alloc::string::String`, so a `s.len()` on one goes through a deref to
        // a `&str` local the binder never saw and stays a refusal.
        //
        // Rust lets a user type shadow the primitive name (`pub struct str { .. }`,
        // which rustc prints at the crate root as the bare `str`), so the
        // declared layout is consulted *first*: a `str` with a declaration is the
        // user's type and is bound as a struct below, not as the primitive. Only
        // when nothing declares `str` is the primitive meant.
        if name == "str" && struct_lookup(structs, name).is_none() {
            env.bind_indexed_len(l, &arg, 0, false);
            continue;
        }
        // Recorded whether or not a layout was found, so a contract naming a field
        // gets a message about the field even when the struct's definition was not
        // readable.
        env.declare_arg(&arg);
        let Some(def) = struct_lookup(structs, name) else { continue };
        for (i, (fname, fty)) in def.fields.iter().enumerate() {
            env.bind(l, &arg, fname, i as u32, fty);
            // An array-typed field is subscriptable: `o.a[0]`. Recorded so a contract's
            // `o.a[0]` can bind an element variable of the right width, and the executor seeds
            // it under the same `(local, [i], index)` key the body's write lands on.
            if let Ty::Array(elem, n) = fty {
                if let Some(w) = elem.width() {
                    env.path_elem_types.insert(
                        format!("{arg}.{fname}"),
                        PathElem {
                            arg: arg.clone(),
                            local: l,
                            chain: vec![i as u32],
                            elem_w: w,
                            elem_signed: elem.is_signed(),
                            len: *n,
                        },
                    );
                }
            }
        }
        // Nested paths: `o.i.v` and, for a *named-field* struct, `o.i` too (its
        // field names are not numeric, so the single-field pass above skipped them).
        // A tuple struct's `.0` is already bound by `bind`, and `bind_nested` only
        // takes depth >= 2, so the two passes do not overlap.
        env.bind_nested_paths(l, &arg, base, structs);
    }
    env
}

/// The argument names whose declared type is signed, for comparison signedness.
///
/// Alias names are included for the same reason they are in [`arg_vars`]: `k` in
/// `let k = i;` stands for `i`, so a signed `i` makes `k` signed too. Omitting
/// them would make `k < 0` an unsigned comparison — the exact class of bug the
/// `Sign` type was introduced to prevent.
pub fn signed_args(f: &crate::mir::parse::MirFn) -> BTreeSet<String> {
    signed_args_named(f, None)
}

/// [`signed_args`], with the contract's own names for the arguments.
///
/// The sign has to follow the *contract's* name, not the body's: an inherited
/// contract's `a < 0` is a signed comparison exactly when the argument the
/// declaration calls `a` is signed, which is a property of the position.
pub fn signed_args_named(
    f: &crate::mir::parse::MirFn,
    rename: Option<&ArgRename>,
) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for &l in &f.arg_locals {
        // The *referent's* sign: a `&i16` argument is named in a contract as the
        // `i16` it addresses, so `c < 0` on `c: &mut i16` is a signed comparison.
        // Reading the reference's own sign (`Ty::Ref` is neither signed nor
        // unsigned) would make it an unsigned one -- the exact class of bug the
        // `Sign` type exists to prevent.
        if f.ty_of(l).map(|t| t.referent().is_signed()).unwrap_or(false) {
            let name = rename
                .and_then(|r| r.name_of(l))
                .map(|s| s.to_string())
                .unwrap_or_else(|| f.name_of(l));
            out.insert(name);
        }
    }
    if rename.is_some() {
        return out;
    }
    for (name, local) in f.alias_locals() {
        if f.ty_of(local).map(|t| t.is_signed()).unwrap_or(false) {
            out.insert(name);
        }
    }
    out
}

/// `MIN` / `MAX` for an integer type name, as a bit pattern at that type's width.
///
/// A contract says `a != i16::MIN`, and the parser has no way to look the value
/// up except here. Returning `None` for an unknown type keeps an unrecognized
/// name a refusal rather than a zero.
fn type_bound(ty: &str, assoc: &str) -> Option<(u64, u8)> {
    let signed = ty.starts_with('i');
    let unsigned = ty.starts_with('u');
    if !signed && !unsigned {
        return None;
    }
    let bits: u32 = match ty {
        "i8" | "u8" => 8,
        "i16" | "u16" => 16,
        "i32" | "u32" => 32,
        "i64" | "u64" => 64,
        "isize" | "usize" => 64,
        _ => return None,
    };
    // The value is the bit pattern at the named type's own width, which is what
    // lets `i8::MIN` be `0x80` rather than an out-of-range 64-bit `128`.
    let v = match assoc {
        "MAX" if signed => (1u64 << (bits - 1)) - 1,
        "MAX" => {
            if bits == 64 {
                u64::MAX
            } else {
                (1u64 << bits) - 1
            }
        }
        // `MIN` for a signed type is the most negative value, which as a bit
        // pattern is the top bit alone.
        "MIN" if signed => 1u64 << (bits - 1),
        "MIN" => 0,
        _ => return None,
    };
    Some((v, bits as u8))
}

/// The argument names and widths of a function, in declaration order, as they
/// appear in the MIR dump, plus any source name that is a direct alias of an
/// argument.
///
/// The alias names are added here rather than only to the index binder because
/// they are ordinary contract names: `let k = i;` makes `k` usable wherever `i`
/// is, so a `requires: k < 4` has to resolve too. `MirFn::alias_locals` decides
/// which names qualify, and it only ever names an argument that the body never
/// writes, so every entry here stands for the very value the body uses.
pub fn arg_vars(f: &crate::mir::parse::MirFn) -> BTreeMap<String, Var> {
    arg_vars_named(f, None)
}

/// A contract's parameter names, by *position*, when the contract comes from a
/// signature other than the body's.
///
/// An implementation inherits its trait's declaration contract, and the two
/// signatures may name their parameters differently:
///
/// ```text
/// trait T { /// ensures: ret == a
///            fn f(&self, a: u8, b: u8) -> u8; }
/// impl T for S { fn f(&self, b: u8, a: u8) -> u8 { a } }   // `a` is the 2nd arg
/// ```
///
/// Binding the declaration's `a` to whatever the implementation happens to call
/// `a` would check the *second* argument where the trait means the first -- a
/// proof about the wrong value, which is the failure this crate exists to avoid.
/// The two are the same method, so their parameters correspond by position; this
/// map says which source name each argument local must answer to.
pub struct ArgRename(BTreeMap<crate::mir::parse::LocalIdx, String>);

impl ArgRename {
    /// The name the contract uses for this argument local, or `None` when the
    /// body's own name is already the right one.
    fn name_of(&self, l: crate::mir::parse::LocalIdx) -> Option<&str> {
        self.0.get(&l).map(|s| s.as_str())
    }
}

/// [`arg_vars`], with the contract's own names for the arguments.
///
/// The aliases are deliberately *not* included when a rename is in force: they
/// are names the implementation's body introduced (`let k = i;`), and a trait
/// declaration has no body, so its contract cannot mean them. Including them
/// could also collide with a declaration parameter name and shadow the very
/// binding the rename just made.
pub fn arg_vars_named(
    f: &crate::mir::parse::MirFn,
    rename: Option<&ArgRename>,
) -> BTreeMap<String, Var> {
    let mut out: BTreeMap<String, Var> =
        arg_bindings(f, rename).into_iter().map(|(_, n, v)| (n, v)).collect();
    if rename.is_some() {
        return out;
    }
    for (name, local) in f.alias_locals() {
        let ty = f.ty_of(local).cloned().unwrap_or(Ty::Other("?".into()));
        if let Some(w) = ty.width() {
            out.insert(name, smt::var_named(local, w));
        }
    }
    out
}

/// The argument bindings, as `(local, name, variable)`, in argument order.
///
/// The one place the contract's name for an argument is decided, so `arg_vars_named`
/// and [`arg_name_of`] cannot disagree about it. `Ty::Ref` is modelled as its
/// referent, so a `&u16` argument's value *is* the `u16` it addresses, at the
/// referent's width: a contract names it by the argument's own name
/// (`bump(c: &mut u16)` with `ensures: c == 0`), and the body's `*c` and the
/// contract's `c` are the same word. A reference to an aggregate has no single
/// word (`&Config` is bound field by field instead), so only a scalar referent is
/// bound here.
fn arg_bindings(
    f: &crate::mir::parse::MirFn,
    rename: Option<&ArgRename>,
) -> Vec<(crate::mir::parse::LocalIdx, String, Var)> {
    let mut out = Vec::new();
    for &l in &f.arg_locals {
        let ty = f.ty_of(l).cloned().unwrap_or(Ty::Other("?".into()));
        if let Some(w) = ty.referent().width() {
            let name = rename
                .and_then(|r| r.name_of(l))
                .map(|s| s.to_string())
                .unwrap_or_else(|| f.name_of(l));
            out.push((l, name, smt::var_named(l, w)));
        }
    }
    out
}

/// The contract name of one argument local, or `None` when it has no binding.
///
/// The inverse of the argument-binding list, used to key a reference argument's
/// *final* value back onto the name the postcondition will use for it.
pub fn arg_name_of(
    f: &crate::mir::parse::MirFn,
    rename: Option<&ArgRename>,
    local: crate::mir::parse::LocalIdx,
) -> Option<String> {
    arg_bindings(f, rename)
        .into_iter()
        .find(|(l, _, _)| *l == local)
        .map(|(_, name, _)| name)
}

#[cfg(test)]
mod tests {
    /// A contract written as a `spec! { … }` block is read from the source text,
    /// and it must read *exactly* like the `///` spelling.
    ///
    /// The three cases below are the ones that cost a defect each when the block
    /// reader was first written per line:
    ///
    /// * a one-line block (`spec! { requires: …; ensures: … }`) was not seen at all,
    ///   so the function verified with no contract -- a green report for a claim
    ///   nobody made;
    /// * a clause body spanning lines was truncated at the newline, and a truncated
    ///   `ensures` is a *weaker* postcondition, which is a false proof;
    /// * a body containing a comma inside parentheses must not split, because the
    ///   macro's grammar is a top-level comma.
    #[test]
    fn a_spec_block_is_read_like_a_doc_comment() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: n <= 200,
    ensures: ret == n + 1,
}
pub fn inc(n: u8) -> u8 { n + 1 }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("the block's contract must be attached");
        assert_eq!(c.requires, vec!["n <= 200".to_string()]);
        assert_eq!(c.ensures, vec!["ret == n + 1".to_string()]);
    }

    #[test]
    fn a_one_line_spec_block_is_read() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! { requires: n <= 200, ensures: ret == n + 1 }
pub fn inc(n: u8) -> u8 { n + 1 }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("a one-line block must still attach");
        assert_eq!(c.requires, vec!["n <= 200".to_string()]);
        assert_eq!(c.ensures, vec!["ret == n + 1".to_string()]);
    }

    /// A bare `verif! { … }` is **not** a contract block, and the function must be
    /// *refused*, not silently left unverified.
    ///
    /// `verif` is a plausible name for a user's own macro, and a macro this crate
    /// did not define cannot be trusted to expand to nothing. Reading its argument
    /// as clauses let an unrelated macro's token soup pin a precondition and
    /// **prove** a function the user never constrained -- the false-proof direction,
    /// measured before this test existed. Dropping the acceptance without a refusal
    /// would be the other silent-loss shape: a function verified against `true`.
    #[test]
    fn a_bare_verif_block_is_refused_by_name_not_read_as_a_contract() {
        use super::extract;
        let src = "\
macro_rules! verif { ($($t:tt)*) => {}; }

verif! {
    requires: n == 0,
    ensures: ret == 0,
}
pub fn g(n: u8) -> u8 { n }
";
        let specs = extract(src);
        let c = specs.get("g").expect("the function must be recorded so it is refused");
        assert!(
            c.requires.is_empty() && c.ensures.is_empty(),
            "a `verif!` block must not attach a contract: {c:?}"
        );
        assert!(
            c.unknown.iter().any(|(_, m)| m.contains("verif!")),
            "the refusal must name `verif!` and the fix: {c:?}"
        );
    }

    /// A *path-qualified* `verif::spec!` names this crate's macro, so it is still
    /// read. This is the spelling a crate uses when it re-exports the macro.
    ///
    /// The source really does spell `verif::spec!`. An earlier version of this test
    /// claimed the qualified spelling in its name and doc but supplied a bare
    /// `spec!`, so it passed without ever exercising the qualified branch: a
    /// regression that rejected `verif::spec!` would have kept it green. A test
    /// named for a spelling has to *write* that spelling.
    #[test]
    fn a_path_qualified_spec_block_is_still_read() {
        use super::extract;
        let src = "\
verif::spec! {
    requires: n <= 200,
    ensures: ret == n + 1,
}
pub fn inc(n: u8) -> u8 { n + 1 }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("a qualified `::spec!` block must attach");
        assert_eq!(c.requires, vec!["n <= 200".to_string()]);
        assert_eq!(c.ensures, vec!["ret == n + 1".to_string()]);
    }

    /// The edition-2018 absolute form of the same path is accepted too.
    #[test]
    fn an_absolute_path_qualified_spec_block_is_read() {
        use super::extract;
        let src = "\
::verif::spec! {
    requires: n <= 200,
    ensures: ret == n + 1,
}
pub fn inc(n: u8) -> u8 { n + 1 }
";
        let specs = extract(src);
        let c = specs
            .get("inc")
            .expect("an absolute `::verif::spec!` block must attach");
        assert_eq!(c.requires, vec!["n <= 200".to_string()]);
        assert_eq!(c.ensures, vec!["ret == n + 1".to_string()]);
    }

    /// A `*::spec!` block naming a *different* path is refused, not read.
    ///
    /// The frontend reads source text and cannot resolve a macro, so it cannot tell
    /// a re-export of `verif::spec` from an unrelated macro that happens to be called
    /// `spec`. Accepting any head ending in `::spec` read
    /// `my_macros::spec! { requires: …, ensures: … }` as a contract -- the
    /// false-proof shape the bare `verif!` refusal exists to close, one spelling
    /// over. This test fails on that code: it asserted a contract *was* attached.
    #[test]
    fn a_foreign_spec_block_is_refused_by_name_not_read_as_a_contract() {
        use super::extract;
        for head in ["my_macros::spec!", "a::b::spec!", "other::verif::spec!"] {
            let src = format!(
                "{head} {{\n    requires: n == 0,\n    ensures: ret == 0,\n}}\n\
                 pub fn g(n: u8) -> u8 {{ n }}\n"
            );
            let specs = extract(&src);
            let c = specs
                .get("g")
                .unwrap_or_else(|| panic!("`{head}`: the function must be recorded so it is refused"));
            assert!(
                c.requires.is_empty() && c.ensures.is_empty(),
                "`{head}` must not attach a contract, got: {c:?}"
            );
            assert!(
                c.unknown.iter().any(|(_, m)| m.contains("verif::spec!")),
                "`{head}`: the refusal must name the fix, got: {c:?}"
            );
        }
    }

    /// The refusal is *narrow*: a local macro named `spec` written bare, and this
    /// crate's own qualified path, both still read. A guard that refused every
    /// `spec!` would pass the test above and fail this one.
    #[test]
    fn the_foreign_spec_refusal_does_not_catch_this_crates_own_spellings() {
        use super::extract;
        for head in ["spec!", "verif::spec!"] {
            let src = format!(
                "{head} {{\n    requires: n <= 200,\n    ensures: ret == n + 1,\n}}\n\
                 pub fn inc(n: u8) -> u8 {{ n + 1 }}\n"
            );
            let specs = extract(&src);
            let c = specs
                .get("inc")
                .unwrap_or_else(|| panic!("`{head}` must attach a contract"));
            assert!(
                c.unknown.is_empty(),
                "`{head}` must be read without a refusal, got: {c:?}"
            );
            assert_eq!(c.requires, vec!["n <= 200".to_string()], "`{head}`");
        }
    }

    /// The false-proof case. Splitting the block per line read `ensures: ret ==`
    /// and dropped the continuation, so `ret == n + 1` became the predicate `ret`,
    /// which is a different and weaker claim. The clause has to survive whole.
    #[test]
    fn a_clause_body_may_span_lines() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: n <= 200,
    ensures: ret ==
        n + 1,
}
pub fn inc(n: u8) -> u8 { n + 2 }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("a wrapped clause must attach");
        let joined: String = c.ensures.join(" ");
        assert!(
            joined.replace(char::is_whitespace, "").contains("ret==n+1"),
            "the whole clause must survive, not just its first line: {joined:?}"
        );
    }

    /// A block that never closes is a refusal, never a partial contract. Reading
    /// half of one would attach `requires` without its `ensures`, which verifies a
    /// weaker claim than the author wrote.
    #[test]
    fn an_unterminated_spec_block_is_refused() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: n <= 200,

pub fn inc(n: u8) -> u8 { n + 2 }
";
        let specs = extract(src);
        // Either the function carries no contract (so nothing is claimed), or the
        // refusal is recorded. What must never happen is `requires` attaching with
        // no `ensures`, which would be a weaker claim.
        if let Some(c) = specs.get("inc") {
            assert!(
                c.ensures.is_empty() && !c.unknown.is_empty(),
                "an unterminated block must not attach half a contract: {c:?}"
            );
        }
    }

    /// A comment after a clause comma must not be carried into the next clause.
    ///
    /// It was: the split kept the `// …` tail, so the following `ensures:` began
    /// with `//`, `take_clause` saw no keyword, and the clause vanished. A dropped
    /// `ensures:` is a *false proof*, not a lost one -- the function is verified
    /// against a postcondition the author did not write (here, none at all).
    #[test]
    fn a_comment_after_a_clause_comma_is_not_carried_into_the_next_clause() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: true,
    ensures: ret == 0, // a true clause, and a comment
    ensures: ret == 1,
}
pub fn f() -> u8 { 0 }
";
        let specs = extract(src);
        let c = specs.get("f").expect("contract");
        assert_eq!(
            c.ensures,
            vec!["ret == 0".to_string(), "ret == 1".to_string()],
            "both clauses must survive a comment: {c:?}"
        );
    }

    /// A `}` inside a character literal does not close the block, and one inside a
    /// string does not either. The per-line `split_once('}')` truncated the clause
    /// inside the literal, so the expression was malformed and the function was
    /// skipped -- a valid contract refused.
    #[test]
    fn a_brace_inside_a_literal_does_not_close_the_block() {
        use super::extract;
        for body in ["'}'", "'\\u{7d}'", "\"}\"", "r\"}\"", "b'}'"] {
            let src = format!(
                "\
macro_rules! spec {{ ($($c:ident : $b:expr,)*) => {{}}; }}

spec! {{
    requires: true,
    ensures: ret == {body},
}}
pub fn h() -> u8 {{ 0 }}
"
            );
            let specs = extract(&src);
            let c = specs
                .get("h")
                .unwrap_or_else(|| panic!("the block must close past {body}: {:?}", specs));
            assert_eq!(
                c.ensures,
                vec![format!("ret == {body}")],
                "the whole clause must survive a brace inside {body}: {c:?}"
            );
        }
    }

    /// Inside a `spec!` block an unknown keyword is a clause the author wrote, not
    /// prose, so it is refused. `postcondition:` is far from every real keyword, so
    /// the typo heuristic did not fire and the clause was dropped silently: with
    /// `requires: true` and a body returning 0, `postcondition: ret == 1` reported
    /// `Verified` against a postcondition nobody read.
    #[test]
    fn an_unknown_clause_keyword_in_a_block_is_refused() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: true,
    postcondition: ret == 1,
}
pub fn g() -> u8 { 0 }
";
        let specs = extract(src);
        let c = specs.get("g").expect("contract");
        assert!(
            !c.unknown.is_empty(),
            "an unknown keyword in a block must be refused, not dropped: {c:?}"
        );
    }

    /// The doc-comment path keeps its typo heuristic and is *not* strict about
    /// prose: a `///` line is documentation first, and ordinary sentences must not
    /// refuse a function. This is the control for the test above.
    #[test]
    fn a_prose_doc_comment_is_not_refused() {
        use super::extract;
        let src = "\
/// direction: this sentence is prose, not a clause.
/// requires: n <= 200
/// ensures: ret == n
pub fn inc(n: u8) -> u8 { n }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("contract");
        assert!(
            c.unknown.is_empty(),
            "prose in a doc comment must not be refused: {c:?}"
        );
        assert_eq!(c.ensures, vec!["ret == n".to_string()]);
    }

    /// A comma inside a turbofish is not a clause separator either.
    ///
    /// `max::<u8, u8>(1, 2)` holds a comma that is not a clause boundary, and the
    /// splitter counted only `()[]{}`. The clause was cut at the generic comma, so
    /// the postcondition became `ret == core::cmp::max::<u8` -- a truncated (and
    /// malformed) expression. A truncated `ensures` is a weaker claim, which is the
    /// false-proof shape this reader exists to prevent.
    #[test]
    fn a_comma_inside_a_turbofish_does_not_split_a_clause() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: true,
    ensures: ret == core::cmp::max::<u8, u8>(1, 2),
}
pub fn f() -> u8 { 2 }
";
        let specs = extract(src);
        let c = specs.get("f").expect("contract");
        assert_eq!(
            c.ensures,
            vec!["ret == core::cmp::max::<u8, u8>(1, 2)".to_string()],
            "the turbofish comma must not split the clause: {c:?}"
        );
    }

    /// The control for the test above: a *comparison* `<` is an operator, not a
    /// generic opener, so a clause containing one must still split normally at its
    /// top-level comma. A fix that counted every `<` would make `a < b` demand a
    /// closing `>` and swallow the following clause.
    #[test]
    fn a_comparison_does_not_open_a_generic_list() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: n < 200,
    ensures: ret < 200,
}
pub fn f(n: u8) -> u8 { n }
";
        let specs = extract(src);
        let c = specs.get("f").expect("contract");
        assert_eq!(c.requires, vec!["n < 200".to_string()]);
        assert_eq!(c.ensures, vec!["ret < 200".to_string()]);
    }

    /// A comma inside parentheses is not a clause separator: the grammar splits on
    /// *top-level* commas only, so a call-shaped body stays one clause.
    #[test]
    fn a_comma_inside_parentheses_does_not_split_a_clause() {
        use super::extract;
        let src = "\
macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }

spec! {
    requires: n <= 200,
    ensures: ret == max(n, 1),
}
pub fn inc(n: u8) -> u8 { n + 1 }
";
        let specs = extract(src);
        let c = specs.get("inc").expect("the contract must attach");
        assert_eq!(c.ensures.len(), 1, "one clause, not two: {:?}", c.ensures);
        assert_eq!(c.ensures[0], "ret == max(n, 1)");
    }

    /// The signature reader, which is only reached for a callee outside the dump.
    ///
    /// A parameter list the reader cannot make sense of has to come back *empty*,
    /// not partially filled: the caller binds the contract's names positionally, so
    /// a list that is short by one would attach `requires: n <= 10` to the wrong
    /// argument. Each case below is a shape that must produce no list at all.
    #[test]
    fn fn_signature_reads_names_positionally_or_not_at_all() {
        use super::{fn_signature, Ty};
        let (p, r) = fn_signature("pub fn f(n: u32, mut m: i8) -> u16 {");
        assert_eq!(
            p,
            vec![("n".to_string(), Ty::U32), ("m".to_string(), Ty::I8)]
        );
        assert_eq!(r, Some(Ty::U16));
        // A declaration, with no body and so no `{`.
        let (p, r) = fn_signature("    fn ext(a: u32) -> u32;");
        assert_eq!(p, vec![("a".to_string(), Ty::U32)]);
        assert_eq!(r, Some(Ty::U32));
        // No return type is not "no signature": the parameters still bind, and the
        // return is `None` so a postcondition over `ret` is refused.
        let (p, r) = fn_signature("fn g(a: u32) {");
        assert_eq!(p, vec![("a".to_string(), Ty::U32)]);
        assert_eq!(r, None);
        // A parameter list that cannot be read whole is not read in part.
        for bad in [
            "fn h(_: u32) {",
            "fn h(self) {",
            "fn h((a, b): (u32, u32)) {",
            "fn h(a u32) {",
            "fn h(a: u32",
        ] {
            let (p, _) = fn_signature(bad);
            assert!(p.is_empty(), "`{bad}` must yield no parameters, got {p:?}");
        }
        // A nested comma is not a parameter boundary.
        let (p, _) = fn_signature("fn k(a: (u8, u8), b: [u8; 2]) {");
        assert_eq!(p.len(), 2, "a nested comma must not split a parameter: {p:?}");
    }

    use super::*;

    fn def(src: &str) -> EnumDef {
        let specs = extract(src);
        specs.enums.get("E").cloned().unwrap_or_default()
    }

    /// The two standard enums a real function reads are reconstructed from the
    /// type's own generic arguments, with the payloads at their declared widths.
    #[test]
    fn a_standard_enum_argument_gets_a_layout() {
        let o = std_enum_def("Option<u8>").expect("Option<u8> has a layout");
        assert_eq!(o.index_of("None"), Some(0));
        assert_eq!(o.index_of("Some"), Some(1));
        assert_eq!(o.tag_width(), 1);
        assert_eq!(o.variants[1].1, vec![Ty::U8], "`Some` carries the type argument");

        let r = std_enum_def("Result<u8, u16>").expect("Result<u8, u16> has a layout");
        assert_eq!(r.index_of("Ok"), Some(0));
        assert_eq!(r.index_of("Err"), Some(1));
        assert_eq!(r.variants[0].1, vec![Ty::U8], "`Ok` carries the first argument");
        assert_eq!(r.variants[1].1, vec![Ty::U16], "`Err` carries the second");
    }

    /// The argument split is top-level, so a nested type stays one argument.
    #[test]
    fn a_nested_standard_enum_payload_is_one_type() {
        let r = std_enum_def("Result<Option<u8>, u8>").expect("nested Result has a layout");
        assert_eq!(r.variants[0].1, vec![Ty::Other("Option<u8>".into())]);
        assert_eq!(r.variants[1].1, vec![Ty::U8]);
    }

    /// A spelling that is not `Option`/`Result`, or is malformed, is refused
    /// rather than guessed -- an unrecognised type must leave the argument
    /// unbound so the function is refused, not modelled at the wrong width.
    #[test]
    fn a_non_standard_or_malformed_name_is_refused() {
        assert!(std_enum_def("Mode").is_none());
        assert!(std_enum_def("Option").is_none(), "no type argument is not Option<T>");
        assert!(std_enum_def("Option<u8>X").is_none(), "trailing text is not Option<u8>");
        assert!(std_enum_def("Result<u8>").is_none(), "Result needs two arguments");
    }

    /// The two standard enums' return discriminants: `Ok` is 0 and `Err` is 1 for
    /// `Result`, `Some` is 1 and `None` is 0 for `Option`. A declared enum resolves
    /// through its own layout; a non-enum return is `None`, so the methods are
    /// refused rather than tested against a tag that does not exist.
    #[test]
    fn an_enum_return_type_gives_its_discriminants() {
        let none = BTreeMap::new();
        assert_eq!(
            enum_ret_discriminants(&Ty::Other("Result<u8, u8>".into()), &none),
            Some((0, 1)),
            "Result: Ok is 0, Err is 1"
        );
        assert_eq!(
            enum_ret_discriminants(&Ty::Other("Option<u8>".into()), &none),
            Some((1, 0)),
            "Option: Some is 1, None is 0"
        );
        assert_eq!(
            enum_ret_discriminants(&Ty::Other("Option::<u8>".into()), &none),
            Some((1, 0)),
            "a turbofished spelling is the same type"
        );
        assert_eq!(enum_ret_discriminants(&Ty::U8, &none), None, "a scalar has no tag");
        assert_eq!(
            enum_ret_discriminants(&Ty::Other("Mode".into()), &none),
            None,
            "a non-standard name is not a tag"
        );
        // A *declared* enum resolves through its layout, keyed by the short name.
        let mut enums = BTreeMap::new();
        enums.insert("E".to_string(), def("pub enum E { Ok(u8), Err }"));
        assert_eq!(
            enum_ret_discriminants(&Ty::Other("E".into()), &enums),
            Some((0, 1)),
            "a declared enum uses its own discriminants"
        );
    }

    /// `ret.is_ok()` / `ret.is_some()` / `ret.is_err()` / `ret.is_none()` read the
    /// return place's *tag*, and a non-enum return refuses them.
    ///
    /// The values are evaluated on the engine at both discriminants, so a method
    /// that tested the wrong tag (or read the tag as a constant) shows up as a
    /// wrong boolean, not a compile error.
    #[test]
    fn an_enum_return_reads_the_discriminant_methods() {
        let tag = smt::var_named(1, 64);
        let mut fields = FieldEnv::default();
        // Result: Ok is 0, Err is 1.
        fields.bind_ret_enum(tag, 0, 1);
        let args = BTreeMap::new();
        let signed = BTreeSet::new();
        let old = BTreeMap::new();
        let at = |k: u64| move |i: u32| if i == 1 { Some(k) } else { None };
        let read = |text: &str| {
            eval_ensures(
                text,
                &args,
                Some(tag),
                RET_IS_UNKNOWN,
                &signed,
                false,
                &fields,
                &old,
            )
            .unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
        };
        for (text, on_ok, on_err) in [
            ("ret.is_ok()", true, false),
            ("ret.is_err()", false, true),
            ("ret.is_ok() || ret.is_err()", true, true),
            ("ret.is_ok() && ret.is_err()", false, false),
        ] {
            let p = read(text);
            assert_eq!(
                smt::evaluate_pred(p, at(0)),
                Some(on_ok),
                "`{text}` at the Ok tag (0)"
            );
            assert_eq!(
                smt::evaluate_pred(p, at(1)),
                Some(on_err),
                "`{text}` at the Err tag (1)"
            );
        }
        // A non-enum return: the method names a tag that does not exist, so the
        // contract is refused rather than read against a fabricated value.
        let plain = FieldEnv::default();
        let err = eval_ensures(
            "ret.is_ok()",
            &args,
            Some(tag),
            RET_IS_UNKNOWN,
            &signed,
            false,
            &plain,
            &old,
        );
        assert!(err.is_err(), "`ret.is_ok()` on a non-enum return must be refused");
    }

    /// A bare payload read on an enum return (`ret.Ok`, `ret.Some`) is *guarded on
    /// the discriminant*: the clause is `tag == disc => clause`, so it is vacuous on
    /// the other variant.
    ///
    /// The guard is the whole content: a payload exists only on the variant's paths.
    /// Evaluated at the payload's own tag the clause is checked, and at the *other*
    /// tag it is vacuously true -- which a model that bound the payload with no
    /// guard would get wrong (it would check the clause on every path).
    #[test]
    fn an_enum_return_reads_a_payload_guarded_on_the_discriminant() {
        let tag = smt::var_named(1, 1);
        let ok = smt::var_named(2, 8);
        let mut fields = FieldEnv::default();
        fields.bind_ret_enum(tag, 0, 1);
        fields.bind_ret_payload("Ok", ok, tag, 0, false);
        let args = BTreeMap::new();
        let signed = BTreeSet::new();
        let old = BTreeMap::new();
        // `Ok` is the success discriminant (0), so the guard is `tag == 0`.
        let at = |t: u64, o: u64| move |i: u32| match i {
            1 => Some(t),
            2 => Some(o),
            _ => None,
        };
        let read = |text: &str| {
            eval_ensures(text, &args, Some(tag), RET_IS_UNKNOWN, &signed, false, &fields, &old)
                .unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
        };
        let p = read("ret.Ok <= 9");
        // On the `Ok` path the clause is checked: the payload's own bound decides.
        assert_eq!(smt::evaluate_pred(p, at(0, 9)), Some(true), "Ok tag, payload 9");
        assert_eq!(smt::evaluate_pred(p, at(0, 10)), Some(false), "Ok tag, payload 10");
        // On the `Err` path there is no `Ok` payload, so the clause is *vacuously*
        // true whatever the (unconstrained) payload variable holds -- which is the
        // whole reason for the guard.
        assert_eq!(smt::evaluate_pred(p, at(1, 10)), Some(true), "Err tag is vacuous");
        // An unguarded reading would refute the clause on the Err path, so this is
        // the evidence the guard is load-bearing rather than decorative.
        assert_ne!(smt::evaluate_pred(p, at(1, 10)), Some(false), "must not check on Err");
    }

    /// The same discriminant methods on an enum-typed *argument*: `r.is_ok()` reads
    /// the argument's tag, which the binder records under `r__tag`, and the
    /// discriminants come from the variant constants it recorded.
    #[test]
    fn an_enum_argument_reads_the_discriminant_methods() {
        let tag = smt::var_named(7, 1);
        let mut args = BTreeMap::new();
        args.insert("r__tag".to_string(), tag);
        let mut fields = FieldEnv::default();
        fields.variant_consts.insert("r::Ok".to_string(), (0, 1));
        fields.variant_consts.insert("r::Err".to_string(), (1, 1));
        let signed = BTreeSet::new();
        let at = |k: u64| move |i: u32| if i == 7 { Some(k) } else { None };
        let read = |text: &str| {
            eval_requires(text, &args, &signed, &fields)
                .unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
        };
        assert_eq!(smt::evaluate_pred(read("r.is_ok()"), at(0)), Some(true), "Ok tag");
        assert_eq!(smt::evaluate_pred(read("r.is_ok()"), at(1)), Some(false), "Err tag");
        assert_eq!(smt::evaluate_pred(read("r.is_err()"), at(1)), Some(true), "Err tag");
        assert_eq!(
            smt::evaluate_pred(read("r.is_ok() || r.is_err()"), at(1)),
            Some(true),
            "the disjunction is a tautology"
        );
        assert_eq!(
            smt::evaluate_pred(read("r.is_ok() && r.is_err()"), at(0)),
            Some(false),
            "the conjunction is refutable"
        );
    }

    /// Grouping and negation of the enum discriminant methods parse and read the
    /// same predicate.
    ///
    /// `(ret.is_ok())` and `!r.is_err()` carry no comparator, so the grouping and
    /// negation lookaheads -- which recognised only comparators and boolean
    /// literals -- routed them into arithmetic and the contract was skipped. The
    /// lookaheads now know the `base.method()` shape. Evaluated at both
    /// discriminants, so a wrong tree is a wrong boolean rather than a parse error.
    #[test]
    fn a_grouped_or_negated_enum_method_is_a_predicate() {
        let tag = smt::var_named(1, 64);
        let mut fields = FieldEnv::default();
        fields.bind_ret_enum(tag, 0, 1);
        let args = BTreeMap::new();
        let signed = BTreeSet::new();
        let old = BTreeMap::new();
        let at = |k: u64| move |i: u32| if i == 1 { Some(k) } else { None };
        let read = |text: &str| {
            eval_ensures(
                text,
                &args,
                Some(tag),
                RET_IS_UNKNOWN,
                &signed,
                false,
                &fields,
                &old,
            )
            .unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
        };
        for (text, on_ok, on_err) in [
            ("(ret.is_ok())", true, false),
            ("!(ret.is_ok())", false, true),
            ("!ret.is_ok()", false, true),
            ("((ret.is_err()))", false, true),
            ("!(ret.is_ok() && ret.is_err())", true, true),
        ] {
            let p = read(text);
            assert_eq!(
                smt::evaluate_pred(p, at(0)),
                Some(on_ok),
                "`{text}` at the Ok tag (0)"
            );
            assert_eq!(
                smt::evaluate_pred(p, at(1)),
                Some(on_err),
                "`{text}` at the Err tag (1)"
            );
        }
    }

    /// A parenthesized comparison used as an *operand* is a `bool` value, not
    /// arithmetic: `ret == (x == 1)` is the natural spelling of a
    /// `bool`-returning function's postcondition, and reading the group with the
    /// arithmetic parser refused it with "missing `)`". The group's predicate is
    /// turned into a one-bit value, so the surrounding `==` compares two `bool`s
    /// exactly as Rust does. A parenthesized *arithmetic* group still parses as
    /// arithmetic, and a bare one-bit name at the predicate position (`ret`) reads
    /// as `ret != 0` -- the value a `bool` means. A wider bare name is still
    /// refused, because a `u32` is not a predicate.
    #[test]
    fn a_parenthesized_comparison_is_a_bool_operand() {
        // `ret` is a one-bit word (as a `bool` return is bound), and `x` is an
        // 8-bit variable. `ret` is index 0, `x` index 1.
        let ret = smt::var_named(0, 1);
        let x = smt::var_named(1, 8);
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), x);
        let unsigned = BTreeSet::new();
        let old = BTreeMap::new();
        let fields = FieldEnv::default();
        let read = |text: &str| {
            eval_ensures(
                text,
                &args,
                Some(ret),
                RET_IS_UNKNOWN,
                &unsigned,
                false,
                &fields,
                &old,
            )
            .unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
        };
        // Evaluate with `ret = r` and `x = xv`.
        let eval = |p, r: u64, xv: u64| {
            smt::evaluate_pred(p, move |i| match i {
                0 => Some(r),
                _ => Some(xv),
            })
        };

        // Every true spelling of "`ret` is `x == 1`" reads and holds exactly when
        // `ret` equals the comparison's truth value -- so the group is read as a
        // `bool` value, not dropped and not a constant.
        for text in [
            "ret == (x == 1)",
            "ret == ((x) == 1)",
            "ret == (x + 1 == 2)",
            "ret == ((x + 1) == 2)",
            "!ret == !(x == 1)",
        ] {
            let p = read(text);
            for xv in [0u64, 1, 2, 255] {
                let truth = xv == 1;
                assert_eq!(eval(p, 1, xv), Some(truth), "`{text}` ret=1 x={xv}");
                assert_eq!(eval(p, 0, xv), Some(!truth), "`{text}` ret=0 x={xv}");
            }
        }

        // A parenthesized *arithmetic* group still parses as arithmetic, and a
        // bare one-bit name at the predicate position reads as `v != 0`.
        let mut p = Parser::new("(x + 1) == 2", &args, None, &unsigned, false);
        let pred = p.parse_cmp().expect("`(x + 1) == 2` parses");
        assert_eq!(smt::evaluate_pred(pred, |i| Some(if i == 1 { 1 } else { 0 })), Some(true));
        assert_eq!(eval(read("ret"), 1, 0), Some(true), "a bare `ret` reads as `ret != 0`");
        assert_eq!(eval(read("!ret"), 1, 0), Some(false), "`!ret` negates the bit");

        // A bare *wider* name has no predicate reading and is refused.
        let err = eval_ensures(
            "x",
            &args,
            Some(ret),
            RET_IS_UNKNOWN,
            &unsigned,
            false,
            &fields,
            &old,
        );
        assert!(err.is_err(), "a bare `u32` is not a predicate");
    }

    /// A name that *holds* a constant is not a written constant expression.
    ///
    /// An invariant is evaluated in the loop-head state, where a counter like `i`
    /// is bound to the value it holds on entry (`0`). `i - 1` is then two constant
    /// operands, and the fold treated it as the written expression `0 - 1` and
    /// refused it as an unsigned underflow -- even though `i` is a variable, and
    /// Rust never range-checks a variable's arithmetic as a constant expression.
    /// Pinned here, not only in the nightly-gated MIR tests.
    #[test]
    fn a_name_holding_a_constant_is_not_a_written_constant_expression() {
        let mut names = BTreeMap::new();
        names.insert("i".to_string(), smt::word(0, 32));
        let signed = BTreeSet::new();
        let consts = BTreeMap::new();
        assert!(
            eval_invariant("i - 1 <= 5", &names, &signed, &consts).is_ok(),
            "a name holding `0` must not be read as the written constant `0`"
        );
        // The *written* form is still refused: rustc rejects `0u32 - 1u32`.
        assert!(
            eval_invariant("0 - 1 <= 5", &names, &signed, &consts).is_err(),
            "the written `0 - 1` is still a rustc const-eval error"
        );
    }

    /// A contract cast sets the target's width *and* sign, and a chain applies
    /// left to right. Pinned here, not only in the nightly-gated MIR tests, so
    /// the parse rule has a guard that runs without a toolchain.
    #[test]
    fn a_contract_cast_sets_the_target_width_and_sign() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::word(0, 8));
        let unsigned = BTreeSet::new();
        let signed: BTreeSet<String> = ["x".to_string()].into_iter().collect();

        // `x as u32` from an unsigned source: 32 bits, unsigned.
        let mut p = Parser::new("x as u32", &args, None, &unsigned, false);
        let (v, s) = p.parse_expr().expect("`x as u32` parses");
        assert_eq!(smt::bits(v), 32);
        assert!(!s.eval());

        // `x as i32` from a *signed* source: 32 bits, signed.
        let mut p = Parser::new("x as i32", &args, None, &signed, false);
        let (v, s) = p.parse_expr().expect("`x as i32` parses");
        assert_eq!(smt::bits(v), 32);
        assert!(s.eval());

        // A chain applies left to right: the last cast decides width and sign.
        let mut p = Parser::new("x as u16 as i32", &args, None, &unsigned, false);
        let (v, s) = p.parse_expr().expect("the chain parses");
        assert_eq!(smt::bits(v), 32);
        assert!(s.eval());
    }

    /// The operator precedence must match Rust's, because a contract is Rust
    /// syntax. The earlier reader put `|`/`^` with `+`/`-` and `&` with `*`, so
    /// `x & 1 + 1` was read as `(x & 1) + 1` where Rust means `x & (1 + 1)` -- a
    /// different *value*, not a different proof. The values below are evaluated
    /// on the engine, so a wrong tree shows up as a wrong number.
    #[test]
    fn a_contract_expression_uses_rust_precedence() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::word(1, 8));
        let unsigned = BTreeSet::new();
        let eval = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| None).expect("a constant")
        };
        // `1 & (1 + 1)` is `1 & 2` is `0`; `(1 & 1) + 1` would be `2`.
        assert_eq!(eval("x & 1 + 1"), 0, "`&` must bind looser than `+`");
        // `(1 + 1) << 1` is `4`; `1 + (1 << 1)` would be `3`, so `+` binds
        // tighter than `<<`.
        assert_eq!(eval("x + 1 << 1"), 4, "`+` must bind tighter than `<<`");
        // `1 | 1 ^ 1` is `1 | (1 ^ 1)` is `1`; `(1 | 1) ^ 1` would be `0`.
        assert_eq!(eval("x | 1 ^ 1"), 1, "`^` must bind tighter than `|`");
        // `8 / 4 / 2` is left-associative: `(8 / 4) / 2` is `1`.
        assert_eq!(eval("8 / 4 / 2"), 1, "`/` is left-associative");
    }

    /// A negated literal is *signed*, and the flag has to say so or `%`, `/` and
    /// `>>` pick the unsigned engine and return a different number.
    ///
    /// This is the shape the precedence test cannot reach: signedness is read from
    /// the *names* in an expression, and `-7 % 3` has no name. The operand of the
    /// negation is the literal `7`, which is unsigned, so passing the operand's own
    /// flag through made the whole expression unsigned. Only `%`, `/` and `>>`
    /// consult the flag, so the mistake produced a *wrong value* rather than a
    /// refusal: `4294967289 % 3` is `0`, where Rust says `-1`. The flag is asserted
    /// directly here, because the values are what the corpus entries cover.
    #[test]
    fn a_negated_literal_is_signed() {
        // An 8-bit name in scope, so a bare literal is built 8 bits wide and the
        // value below is the readable `0xF9` rather than a 64-bit pattern.
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::word(1, 8));
        let unsigned = BTreeSet::new();
        let parse = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, sgn) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            (v, sgn)
        };
        // A negation is only defined on a signed type, so `-7` is signed even
        // though the `7` it negates is not.
        let (_, sgn) = parse("-7");
        assert!(sgn.eval(), "a negated literal is signed");
        let (_, sgn) = parse("-7 % 3");
        assert!(sgn.eval(), "a remainder of a negated literal is signed");
        // A bare literal stays unsigned, or `x % 3` for an unsigned `x` would
        // take the signed engine -- the mirror of the same mistake.
        let (_, sgn) = parse("7 % 3");
        assert!(!sgn.eval(), "a bare literal is unsigned");
        // The value is still a *value* negation: `-7` is the two's-complement
        // `7` subtracted from `0`, so it evaluates to `-1` at 8 bits.
        let (v, _) = parse("-7");
        assert_eq!(smt::evaluate(v, |_| None).expect("a constant"), 0xF9);
    }

    /// A bare literal widened to meet a *signed* operand zero-fills, not
    /// sign-extends.
    ///
    /// The fill is a property of the *constant's* own signedness, not the operand
    /// it meets. A bare literal is non-negative, so `(x as i16) == 255` for a `u8`
    /// `x` is true in Rust; filling from the operand's signed `i16` sign-extended
    /// the `255` to `65535` and *refuted* a postcondition Rust accepts — a false
    /// refutation, the mirror of a false proof. A signed constant keeps
    /// sign-extending, which the last assertion pins.
    #[test]
    fn a_literal_widened_to_a_signed_operand_zero_fills() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        let eval_const = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| None).expect("a constant")
        };
        // The comparison as a whole, so the widened literal is what is decided.
        let pred = |text: &str, x: u64| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let pr = p.parse_or().expect("parses as a predicate");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate_pred(pr, |_| Some(x)).expect("decides")
        };
        // `(x as i16)` at `x == 255` is `255`, so the equality is *true*. Sign-
        // extending the literal to `65535` would make it false.
        assert!(pred("(x as i16) == 255", 255), "`255` widened to i16 is `255`");
        // The widened literal itself, at 32 bits, is still `255`.
        assert_eq!(eval_const("255 as i32"), 255, "a bare literal zero-fills");
        // A *signed* constant must still sign-extend: `-1 as i32` is all ones.
        assert_eq!(eval_const("-1 as i32"), u32::MAX as u64, "a signed constant sign-extends");
    }

    /// An *opaque* constant is refused where a widening would have to guess its
    /// value, and a *fold* is not, so the refusal is not over-broad.
    ///
    /// A complement's value is the complement of a literal at the *operand's*
    /// width, but the reader holds it at the *scope's* width. `!0` against a `u16`
    /// is `65535`; the reader held `255` and zero-extended it, and *verified*
    /// `ensures: (x as u16 + !0) == 255` -- a false proof. The signed case fails
    /// the same way when the literal's top bit is clear: `!128` against an `i16` is
    /// `-129`, but `0x7F` sign-extends to `127`, *verifying* `== 127`. Both are
    /// refused. A *fold* (`200 + 100`) is a value, not a bit pattern, and is emitted
    /// at full width so it *truncates* to the operand exactly -- it must still read.
    #[test]
    fn an_opaque_constant_widening_is_refused_but_a_fold_is_not() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            p.parse_or().is_ok()
        };
        // A widening that would have to guess a complement's operand-width value.
        assert!(!parses("(x as u16 + !0) == 255"), "`!0` against a `u16` is `65535`");
        assert!(!parses("(x as u16 + !0) == 65535"), "the reader cannot model it either way");
        assert!(!parses("(x as i16 + !128) == 127"), "`!128` against an `i16` is `-129`");
        // A fold is a value and still reads, even into a wider operand.
        assert!(parses("x as u16 <= 200 + 100"), "`300` is a value, not a bit pattern");
        assert!(parses("x <= 100 + 44"), "a fold that fits its operand still reads");
        // The complement at its *own* width is fine, and the literal zero-extends.
        assert!(parses("(x as i16) == 255"), "a bare literal zero-extends");
        // A *suffixed* literal keeps its own width, so the pair is not narrowed to
        // the literal's placeholder width. `128i16 as i32` is a 32-bit `128`, and
        // the bare `128` beside it must widen to meet it, not the other way round.
        assert!(parses("128i16 as i32 == 128"), "the bare literal widens to the cast width");
    }

    /// A *suffixed* literal is built at its own width, and a bare literal beside it
    /// takes that width rather than forcing the suffixed one down to the scope's.
    ///
    /// `128i16` is a sixteen-bit `128`; the reader sized it from the scope's names
    /// (eight bits here) instead, so `0x80` was read as `-128` and a widening cast
    /// sign-extended it -- *verifying* `ensures: 128i16 as i32 == -128`, which Rust
    /// calls false. The true `== 128` must read, which is what fails if the pair is
    /// narrowed to the literal's placeholder width.
    #[test]
    fn a_suffixed_literal_is_sized_from_its_suffix_not_the_scope() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        let pred = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let pr = p.parse_or().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate_pred(pr, |_| Some(0)).expect("decides")
        };
        assert!(pred("128i16 as i32 == 128"), "`128i16 as i32` is `128`");
        assert!(pred("128i16 == 128"), "the suffixed literal is its own value");
        // The false reading must not verify. It is refused rather than refuted --
        // the reader cannot model the untyped `-128` beside a 32-bit cast -- which
        // is the sound direction, so assert the *predicate* is not proved, not that
        // it parses.
        let mut p = Parser::new("128i16 as i32 == -128", &args, None, &unsigned, false);
        if let Ok(pr) = p.parse_or() {
            assert!(!smt::prove(pr).is_proved(), "`128i16 as i32` is `128`, never `-128`");
        }
    }

    /// A `u128`/`i128` suffix is *refused* before the range check, which would
    /// otherwise shift `1u128` by 128 and panic in a debug build.
    ///
    /// The suffix records the type's true width (128), so the range check's
    /// `1u128 << w` overflows; in release the shift wraps and hands a 128-bit
    /// value to `smt::word`, itself an assertion. Both literals here are small, so
    /// the refusal must come from the *type*, not the value.
    #[test]
    fn a_u128_suffix_is_refused_before_the_range_shift() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        for text in ["0u128 == 0u128", "0i128 == 0i128", "1u128 == 1"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let err = p.parse_or().expect_err("a 128-bit suffix must be refused");
            let msg = format!("{err}");
            assert!(msg.contains("128") && msg.contains("64-bit"), "`{text}`: got {msg}");
        }
        // A 64-bit suffix beside a 128-bit one is still fine on its own.
        let mut p = Parser::new("1u64 == 1", &args, None, &unsigned, false);
        assert!(p.parse_or().is_ok(), "a `u64` suffix is modelled");
    }

    /// A *typed* constant mask keeps its type, so a pairing of the other
    /// signedness is refused rather than decided -- in **both** directions.
    ///
    /// `-1i8 & 1` is an `i8` and `1u8 & 1` is a `u8`, even though both compute the
    /// small positive `1`: the mask takes the typed operand's type, and `==` never
    /// coerces, so `(...) == y` against a partner of the other signedness is
    /// `E0308`. Marking the constant result `Literal` hid the type and read the
    /// comparison as `1 == y`. The first fix excluded only a *signed* typed operand,
    /// which left the unsigned half open; both must be refused now, while the same
    /// mask against a partner of its *own* signedness still reads.
    #[test]
    fn a_typed_constant_mask_keeps_its_type() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        // `y` is unsigned: a signed typed mask cannot be compared with it.
        let unsigned = BTreeSet::new();
        for text in ["(-1i8 & 1) == y", "(1i8 & 1) == y", "(-1i8 & 1) < y"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let err = p.parse_or().expect_err("a signed mask vs an unsigned name must be refused");
            let msg = format!("{err}");
            assert!(msg.contains("signed constant"), "`{text}`: got {msg}");
        }
        // `y` is signed: an unsigned typed mask cannot be compared with it either.
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        for text in ["(1u8 & 1) == y", "(1u8 & 1) < y"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("an unsigned mask vs a signed name must be refused");
            let msg = format!("{err}");
            assert!(msg.contains("signed constant"), "`{text}`: got {msg}");
        }
        // A mask with no *typed* operand stays untyped and may widen.
        let mut p = Parser::new("(!0 & 1) == y", &args, None, &unsigned, false);
        assert!(p.parse_or().is_ok(), "an untyped constant mask still reads");
    }

    /// A constant whose *type is fixed* may not meet a partner of another width,
    /// while a bare literal (and a bare negation) infers its width and may.
    ///
    /// `1i8`, `i8::MIN` and a cast carry a width of their own, so a comparison with
    /// a differently-sized operand is `E0308` in Rust, and `refuse_mixed_signedness`
    /// does not catch it because both operands are signed. `align_widths` used to
    /// *resize* the constant instead, which erased the only evidence and let
    /// `-1i8 < (x as i16)` and `1i8 == 1i16` verify. A bare literal (and `-1`, a
    /// negation of one) has no width of its own -- Rust infers it -- so those must
    /// still align to the other operand.
    #[test]
    fn a_fixed_width_constant_may_not_meet_a_partner_of_another_width() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("x".to_string());
        // A fixed-width constant (suffix or bound) against a name of another width
        // is refused, whatever the comparison.
        for text in [
            "(x as i16) == 1i8",
            "-1i8 < (x as i16)",
            "(x as i16) < i8::MIN",
            "1i8 == 1i16",
        ] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("a fixed-width mismatch must be refused");
            let msg = format!("{err}");
            assert!(msg.contains("different widths"), "`{text}`: got {msg}");
        }
        // A bare literal, and a bare negation, have no width of their own and take
        // the other operand's -- these are well-typed and must read. So does a
        // width-independent untyped constant (`!0 & 1`, which is `1` at any width).
        for text in ["(x as i16) == 1", "-1 < (x as i16)", "-1 < x", "(!0 & 1) == x"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(p.parse_or().is_ok(), "`{text}` infers its width and reads");
        }
    }

    /// An untyped fold whose exact result *overflows* the operand width is refused,
    /// while a fold that fits still reads.
    ///
    /// `!0 + 1` is `256` at the scope's width. Against an unsigned partner rustc
    /// rejects it (`!0` is `255`, so `255 + 1` overflows), but the reader carried
    /// the scope-width value and let a later resize truncate it, reading
    /// `(!0 + 1) < 1u8` as `0 < 1` -- a *verified* contract for a program rustc
    /// rejects. The fold's value depends on the width it is read at, so it is
    /// refused. `200 + 100` is `300` at any width holding it, so it is
    /// width-independent and still reads -- the control the refusal must not catch.
    #[test]
    fn an_untyped_fold_that_overflows_the_operand_width_is_refused() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        args.insert("a".to_string(), smt::var(16));
        let unsigned = BTreeSet::new();
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        for text in ["(!0 + 1) < 1u8", "(!0 + 2) == 1u8", "(!0 + 1) <= y"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("an overflowing untyped fold must be refused");
            assert!(
                format!("{err}").contains("width-dependent"),
                "`{text}`: got {err}"
            );
        }
        // A fold that *fits* the partner's width is a value, not a width-dependent
        // bit pattern, and must still read.
        for text in ["(200 + 100) <= a", "(200 + 100) == 300"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            assert!(p.parse_or().is_ok(), "`{text}` fits and reads");
        }
    }

    /// The complement of an untyped literal is range-checked against the type it
    /// meets, not merely held at the scope's width.
    ///
    /// `!128` for an `i8` is a rustc `literal out of range for i8` error -- `128`
    /// does not fit a signed eight-bit type -- even though the *complement's*
    /// value `127` does. The reader built `!128` as the constant `127` and marked
    /// it `Opaque`, then let the resize truncate it with no check, so `y <= !128`
    /// read as `y <= 127` (`i8::MAX`) and *verified* for a program rustc rejects.
    /// The operand is now checked against the type the complement meets, so this
    /// is refused while `!127` (which does fit) still reads. A complement against
    /// a wide enough partner (`!128` for an `i16`) is untouched.
    #[test]
    fn the_complement_of_an_out_of_range_literal_is_refused() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        args.insert("b".to_string(), smt::var(16));
        // The parser is told which names are *signed*; a name it does not know is
        // unsigned. So `x` is a `u8`, `y` an `i8`, `b` an `i16`.
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        signed.insert("b".to_string());
        // `128`, `255` and a nested complement's `128` do not fit an `i8`; rustc
        // rejects each, so the reader must refuse rather than decide.
        for text in ["y <= (!128)", "y <= (!255)", "y <= (!!128)", "y <= (!(64 + 64))"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("an out-of-range complement must be refused");
            let msg = format!("{err}");
            // Either the complement's own operand check or the per-literal range
            // check may be the one that fires (the fold `64 + 64` is refused for
            // its own `128`); both are the refusal this test is about.
            assert!(
                msg.contains("complement") || msg.contains("does not fit"),
                "`{text}`: got {msg}"
            );
        }
        // A complement whose operand *fits* the type it meets still reads, so the
        // refusal is drawn at the range, not at `!`.
        for text in ["y <= (!127)", "x <= (!255)", "x <= (!0)", "b <= (!128)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(
                r.is_ok(),
                "`{text}` fits the operand type and reads: {:?}",
                r.err().map(|e| format!("{e}"))
            );
        }
    }

    /// Every literal and every constant `+ - *` intermediate is range-checked
    /// against the type the expression meets, not only the fold's value.
    ///
    /// The reader folds a constant expression to a single value, and used to
    /// range-check only that value. So `2 & 128` for an `i8` -- a rustc `literal
    /// out of range` error, since the `128` does not fit -- was read as `0` and
    /// *decided*, and `128 - 63` -- also rejected for its `128`, although its value
    /// `65` fits -- likewise. The envelope of the literals underneath the fold is
    /// what closes this, so both are refused.
    #[test]
    fn a_literal_inside_a_constant_fold_is_range_checked_too() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        args.insert("x".to_string(), smt::var(8));
        args.insert("a".to_string(), smt::var(16));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        // Each is a rustc `literal out of range` error for the type it meets, so
        // the reader refuses rather than decides on a program rustc rejects.
        for text in [
            "y == (200 & 200)",
            "y == (2 & 128)",
            "y == (100 + 100)",
            "y == ((100 + 100) & 0)",
            "y == (128 - 63)",
            "y == (200 | 0)",
            "y <= (2 & 128)",
        ] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("an out-of-range literal must be refused");
            assert!(
                format!("{err}").contains("does not fit"),
                "`{text}`: got {err}"
            );
        }
        // The same value is fine where the literal *does* fit: `200 & 200` is a
        // `u8` expression, and `-128` is the one bare literal a unary `-` may
        // rescue for an `i8` (the negated value is checked, not the magnitude).
        for text in ["x == (200 & 200)", "x == (255 & 255)", "y == -128", "y == (-128)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(
                p.parse_or().is_ok(),
                "`{text}` fits the type it meets and reads"
            );
        }
        // A literal inside a fold is *not* rescued by a surrounding `-`:
        // `-(128 - 63)` is rejected for its inner `128`, unlike `-(128)`.
        for text in ["y == -(128 - 63)", "y == -(-128)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(
                p.parse_or().is_err(),
                "`{text}` has an out-of-range literal and must be refused"
            );
        }
    }

    /// A constant fold that mixes an *untyped* complement with a plain operand is
    /// refused when its value depends on the signedness Rust infers for it.
    ///
    /// A complement has no signedness of its own -- it takes the one the type it
    /// meets gives it -- and the reader guesses it from the other operand. When no
    /// operand fixes a sign, the guess can disagree with the reading the fold
    /// finally gets, and the value, and whether it overflows at all, change with
    /// it. `!127 - 63` is `128 - 63 = 65` unsigned but `i8::MIN - 63`, a rustc
    /// overflow, signed: the reader decided `65` for a program rustc rejects.
    /// `!127 * 2` is the same shape, and `!100 * -0` is `E0277` for a `u16` (the
    /// negation is legal only at a signed type). Each is refused.
    #[test]
    fn a_sign_ambiguous_untyped_fold_is_refused() {
        // The scope holds only eight-bit names, so a complement is held at eight
        // bits too and the fold `!127 - 63` is the signed-overflow shape.
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        for text in ["y == ((!127) - 63)", "x == ((!127) - 63)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("a sign-ambiguous fold must be refused");
            assert!(
                format!("{err}").contains("sign-ambiguous"),
                "`{text}`: got {err}"
            );
        }
        // At eight bits the two readings of `(!0) - 1` (`254` unsigned, `-2` signed)
        // both fit, so it is *not* ambiguous and still reads against a `u8`.
        {
            let text = "x == ((!0) - 1)";
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(
                r.is_ok(),
                "`{text}` agrees under both readings and reads: {:?}",
                r.err().map(|e| format!("{e}"))
            );
        }
        // A negated bare literal beside an untyped complement is `E0277` when the
        // fold meets an unsigned type, so it is refused. The scope has a sixteen-bit
        // name to give the fold that width.
        let mut args = BTreeMap::new();
        args.insert("a".to_string(), smt::var(16));
        let unsigned = BTreeSet::new();
        let mut p = Parser::new("a == ((!100) * (-0))", &args, None, &unsigned, false);
        let err = p.parse_or().expect_err("a negated literal beside a complement is refused");
        assert!(
            format!("{err}").contains("sign-ambiguous"),
            "`a == ((!100) * (-0))`: got {err}"
        );
        // The controls at sixteen bits: the same fold where neither reading
        // overflows still reads.
        for text in ["a == ((!127) - 63)", "a == ((!0) * 0)"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let r = p.parse_or();
            assert!(
                r.is_ok(),
                "`{text}` agrees under both readings and reads: {:?}",
                r.err().map(|e| format!("{e}"))
            );
        }
    }

    /// The written magnitude of a suffixed literal is what Rust range-checks, not
    /// the two's-complement value it denotes.
    ///
    /// `128i8` alone is a `literal out of range for i8` error, and only `-128i8`
    /// is legal, because the negation is what meets the type. Recording the signed
    /// value (`-128`) made the negation add `+128` to the envelope and refuse the
    /// valid `-128i8`; it also made the positive `128i8`, which rustc rejects, read
    /// as the in-range `-128`. Both are pinned here, with the same shape at sixteen
    /// bits.
    #[test]
    fn a_suffixed_minimum_literal_is_checked_as_written() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        // `-128i8` is legal (`i8::MIN`) and must read.
        for text in ["y == -128i8", "y == -(128i8)", "y == i8::MIN"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
        }
        // A positive use of the magnitude, and a double negation, are errors.
        for text in ["y == 128i8", "y == -(-128i8)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("an out-of-range magnitude is refused");
            let msg = format!("{err}");
            assert!(
                msg.contains("does not fit") || msg.contains("out of range"),
                "`{text}`: got {msg}"
            );
        }
        // The same at sixteen bits, where the minimum is `-32768i16`.
        let mut args = BTreeMap::new();
        args.insert("b".to_string(), smt::var(16));
        let mut signed = BTreeSet::new();
        signed.insert("b".to_string());
        for text in ["b == -32768i16", "b == -(32768i16)", "b == i16::MIN"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
        }
        let mut p = Parser::new("b == 32768i16", &args, None, &signed, false);
        assert!(p.parse_or().is_err(), "`32768i16` alone is out of range for an `i16`");
    }

    /// A complement's operand literals are range-checked where the complement is
    /// read, but they must not leak onto an unrelated literal that shares the
    /// complement's *value* term.
    ///
    /// At eight bits `!128` is the constant `127`, so it is hash-consed with a
    /// separately written bare `127`. Recording the operand's envelope (`128`) in
    /// the global term-keyed map attached it to that innocent `127`, and
    /// `x == !128 && y == 127` for a `u8` and an `i8` -- both valid Rust -- was
    /// skipped. The envelope now travels in the `Opaque` payload, so the bare
    /// literal is untouched while `!128` against an `i8` is still refused.
    #[test]
    fn a_complement_operand_does_not_pollute_a_bare_literal() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        // Both conjuncts are valid Rust; the reader must read the whole contract.
        for text in [
            "x == !128 && y == 127",
            "y == 127 && x == !128",
            "x == !0 && y == 127",
        ] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(r.is_ok(), "`{text}` is valid Rust and must read: {:?}", r.err().map(|e| format!("{e}")));
        }
        // The complement against an `i8` is still a `literal out of range` error.
        for text in ["y == !128", "y <= (!128)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let err = p.parse_or().expect_err("`!128` for an `i8` is out of range");
            let msg = format!("{err}");
            assert!(
                msg.contains("complement") || msg.contains("does not fit"),
                "`{text}`: got {msg}"
            );
        }
        // The refusal survives a unary `-` around the complement: the envelope must
        // travel through the negation, which is a *value* and cannot carry it in the
        // sign. `-!128` for an `i8` is a rustc error for the same operand `128`.
        let mut p = Parser::new("y <= (-(!128))", &args, None, &signed, false);
        let err = p.parse_or().expect_err("`-!128` for an `i8` is out of range");
        let msg = format!("{err}");
        assert!(
            msg.contains("complement") || msg.contains("does not fit"),
            "`y <= (-(!128))`: got {msg}"
        );
    }

    /// A nested complement whose operand is a *fold* keeps every literal underneath
    /// it, and a named bound does not inherit a literal's envelope.
    ///
    /// Two follow-ups to the envelope work. First, `!(!1 - 200)` for an `i8` is a
    /// rustc error for the `200`: the inner complement `!1` carries `(1, 1)` in its
    /// sign and the fold `!1 - 200` records `200` on its own term, so the outer
    /// complement must *union* the two -- taking the inherited envelope alone
    /// dropped the `200` and the reader decided a contract rustc rejects. Second,
    /// `i8::MIN` and a bare or suffixed `128` are the same eight-bit constant and
    /// hash-cons to one term, so a term-keyed envelope recorded for the literal
    /// (`128i8` records the out-of-range `128`) was read back as the *bound's* and
    /// skipped a valid `y == -128i8 && y == i8::MIN`; the bound is now its own term.
    #[test]
    fn a_nested_complement_keeps_the_fold_and_a_bound_keeps_its_own_fit() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        // The fold's `200` survives the outer complement, so the shape is refused
        // (the exact wording varies: an out-of-range complement operand, or an
        // unsigned fold that underflows -- both are rustc rejections).
        for text in ["y == !(!1 - 200)", "y == !(200 - !1)", "y == !(128 - 63)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(
                p.parse_or().is_err(),
                "`{text}` is a rustc range error and must be refused"
            );
        }
        // The named bound is valid in either conjunct order, and beside a bare
        // `128` on an unsigned name it does not inherit the literal's envelope.
        for text in [
            "y == -128i8 && y == i8::MIN",
            "y == i8::MIN && y == -128i8",
            "x == 128 && y == i8::MIN",
            "y == i8::MIN && x == 128",
            "y == i8::MIN && y == 127",
        ] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(r.is_ok(), "`{text}` is valid Rust and must read: {:?}", r.err().map(|e| format!("{e}")));
        }
    }

    /// A shift of an *untyped* constant is refused when it is only valid at the
    /// scope's width, not at every width the result could be read at.
    ///
    /// `255 >> 8` looks fine at the scope's width (32, from the `u32` name in
    /// scope), but the operand has no type of its own: Rust infers its width from
    /// where the shift is read, and against a `u8` partner `255` is a `u8` and a
    /// shift by its own width is a compile error. The reader verified
    /// `255 >> 8 <= x` for a `u8` `x` on a program rustc rejects. `(255 >> 1) >= y`
    /// for an `i8` `y` failed the same way, with `255` a rustc `literal out of
    /// range`. The amount must be below the *narrowest* width, and a literal
    /// operand must fit an 8-bit signed value, or the shift is refused. A shift of
    /// a *typed* name (`x >> 1`) is unaffected: its width is known.
    #[test]
    fn a_shift_of_an_untyped_constant_is_refused_when_it_needs_a_wider_operand() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        args.insert("a".to_string(), smt::var(16));
        args.insert("c".to_string(), smt::var(32));
        let mut unsigned = BTreeSet::new();
        unsigned.insert("x".to_string());
        unsigned.insert("a".to_string());
        unsigned.insert("c".to_string());
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        // The scope's width is 32, so the amount passes the old scope-width check
        // and the operand passes the old (absent) range check; both are refused.
        for text in ["(255 >> 8) <= x", "(255 >> 16) <= a", "(!0 << 8) <= x",
                     "(1 >> 16) <= a", "(255 >> 1) >= y"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(
                p.parse_or().is_err(),
                "`{text}` is only valid at the scope's width and must be refused"
            );
        }
        // A shift of a *typed* name has a known width and still reads; so does a
        // constant shift whose amount is below the narrowest width and whose
        // operand fits an 8-bit signed value (`1 << 4` is `16` at any width).
        for text in ["(x >> 1) == 0", "(a << 2) <= a", "(1 << 4) <= x", "(1 >> 1) <= x",
                     "(2 << 2) <= a"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(p.parse_or().is_ok(), "`{text}` has a known width and reads");
        }
    }

    /// A shift *amount* is a value of its own type, so its bare literals are
    /// evaluated at Rust's `i32` (32 bits), not at the shifted operand's width.
    ///
    /// `x >> (2 << 7)` for a `u8` `x` is a rustc error: the amount `2 << 7` is an
    /// `i32` and is `256`, and a shift by 256 overflows. Sizing the amount's
    /// literals to the eight-bit scope instead made `2 << 7` wrap to `0`, so the
    /// shift read as `x >> 0` and the reader *decided* `x >> (2 << 7) == 0` --
    /// false at `x == 0` -- on a program rustc rejects. The floor makes the fold
    /// agree with rustc, so the wrapped amount never appears and the shift is
    /// refused for the amount it really is.
    #[test]
    fn a_shift_amount_is_evaluated_at_its_own_width_not_the_operands() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut unsigned = BTreeSet::new();
        unsigned.insert("x".to_string());
        // Each amount is `256` (or wraps through one) at `i32`; every one is a
        // rustc overflow and must be refused rather than folded to a small count.
        for text in ["x >> (2 << 7) == 0", "x >> (2 << 6) == 0"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            assert!(
                p.parse_or().is_err(),
                "`{text}` overflows at the amount's own `i32` width and must be refused"
            );
        }
        // Amounts that fit `i32` and are below the operand width still read.
        for text in ["(x >> (1 + 1)) == 0", "(x >> (2 * 2)) == 0", "(x >> (8 - 1)) == 0",
                     "(x >> 7) == 0"] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            assert!(p.parse_or().is_ok(), "`{text}` has an in-range amount and reads");
        }
    }

    /// A typed operand *inside* the amount fixes the amount's type, so the
    /// amount's bare literals must be built at that width, not at a blind `i32`.
    ///
    /// `x >> (1u8 + (2 << 7))` for a `u8` `x` is valid Rust: the suffixed `1u8`
    /// makes the amount a `u8`, so `2 << 7` is `0u8` and the amount is `1u8`. The
    /// earlier reader floored the amount's literals at a flat 32 bits, built
    /// `2 << 7` as `256`, and *refused* the shift -- a false refusal on a program
    /// rustc accepts. The floor now comes from the amount's own inferred width.
    ///
    /// The negative cases pin the other direction, because the fix must not accept
    /// a program rustc rejects: an amount with *no* typed operand is still `i32`
    /// (`2 << 7` is `256`, an overflow), a nested shift's amount suffix does not fix
    /// the outer amount's type (`2 << 7u8` is still the `i32` `256`), a typed
    /// operand outside the amount cannot narrow it (`x >> 300`), and two typed
    /// operands of different widths are a type error.
    #[test]
    fn a_typed_amount_operand_fixes_the_amounts_width() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut unsigned = BTreeSet::new();
        unsigned.insert("x".to_string());

        let mut p = Parser::new("(x >> (1u8 + (2 << 7))) == 0", &args, None, &unsigned, false);
        let pred = p.parse_or().expect("`x >> (1u8 + (2 << 7))` is valid Rust and must read");
        assert!(smt::evaluate_pred(pred, |_| Some(0)).unwrap(), "0 >> 1 == 0");
        assert!(!smt::evaluate_pred(pred, |_| Some(2)).unwrap(), "2 >> 1 == 1 != 0");

        for text in [
            // No typed operand: the amount is `i32` `2 << 7` = `256`, an overflow.
            "x >> (2 << 7) == 0",
            // `1u16 + (2 << 7)` is `257` at `u16`, an overflow.
            "x >> (1u16 + (2 << 7)) == 0",
            // `1 + (2 << 7)` is `257` at `i32`, an overflow.
            "x >> (1 + (2 << 7)) == 0",
            // The `u8` suffix is in the *nested* shift's amount, so the outer amount
            // stays the `i32` `2 << 7u8` = `256`, an overflow.
            "x >> (2 << 7u8) == 0",
            // A typed operand outside the amount cannot narrow it: `300` stays `300`.
            "(x >> 300) == 2u8",
            "(x >> 300) == 2",
            // Two typed operands of different widths are a type error.
            "(x >> (1u8 + 1u16)) == 0",
            "(x >> (1u8 + 1i8)) == 0",
            // A cast fixes the amount's type and overrides what it casts:
            // `(1u8) as u16 + (2 << 7)` is `1u16 + 128u16` = `257u16`, an overflow.
            "x >> ((1u8) as u16 + (2 << 7)) == 0",
            "x >> (1u8 as u16 + (2 << 7)) == 0",
            // The width-dependent untyped folds were already refused and must stay so.
            "(!0 + 1) < 1u8",
            "(!0 + 2) == 1u8",
        ] {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            assert!(p.parse_or().is_err(), "`{text}` is a rustc error and must be refused");
        }
    }

    /// The provisional unsigned value of a fold that touched a complement must not
    /// be range-checked as if it were a written literal.
    ///
    /// `y == !(!1 + 1)` for an `i8` `y` is valid Rust: `!1 + 1` is `-1` at `i8`, and
    /// `!(-1)` is `0`, so the contract is `y == 0`. The reader evaluates the fold
    /// unsigned (`255`) because its type is not known until it meets the `i8`, and
    /// range-checking that *guess* refused the contract though no `255` is written.
    /// An `Opaque` fold now records only its operands' envelopes, so the guess is
    /// not checked -- while a genuine literal under the fold still is.
    #[test]
    fn an_opaque_folds_provisional_value_is_not_range_checked() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());

        let mut p = Parser::new("y == !(!1 + 1)", &args, None, &signed, true);
        let pred = p.parse_or().expect("`y == !(!1 + 1)` is valid Rust and must read");
        assert!(smt::evaluate_pred(pred, |_| Some(0)).unwrap(), "y == 0 reads true at 0");
        assert!(!smt::evaluate_pred(pred, |_| Some(1)).unwrap(), "y == 0 reads false at 1");

        // A literal *under* the fold is still range-checked against the type the
        // complement meets: `!128` is an `i8` range error even though `!128` is
        // `127`, so `y == !128` must be refused.
        let mut p = Parser::new("y == !128", &args, None, &signed, true);
        assert!(p.parse_or().is_err(), "`!128` meets an `i8` and must be refused");
    }

    /// A deeply nested amount must not exhaust the stack, because the parser
    /// recurses once per level and calls `smt::evaluate` (via `const_value`) at
    /// every level.
    ///
    /// `evaluate` owns a 12 KiB [`EvalMemo`] as a stack local. When the optimiser
    /// inlined it into the recursive parser, every level cost 12 KiB of stack and a
    /// two-level amount already aborted on the 2 MiB a test thread gets. The fix is
    /// `#[inline(never)]` on `evaluate`; this test is the gate on it, because it runs
    /// on the *default* stack and reverting the attribute re-inflates the frames.
    ///
    /// The nesting is far deeper than the corpus needs (40 levels against the
    /// corpus's 2), so the test fails on a regression by a wide margin rather than
    /// by a hair -- a frame that is merely large should be caught here, not at the
    /// exact depth some other test happens to use. The amounts stay small enough to
    /// fit the operand so the *only* thing under test is the stack cost.
    #[test]
    fn a_deeply_nested_amount_does_not_exhaust_the_stack() {
        let mut args = BTreeMap::new();
        // A 64-bit operand, so the nested amount (which sums to 40) is below the
        // operand width and the *only* thing the test exercises is the stack cost.
        args.insert("x".to_string(), smt::var(64));
        let mut unsigned = BTreeSet::new();
        unsigned.insert("x".to_string());
        // `(1 + (1 + (1 + ... )))`, 40 deep, as a shift amount.
        let mut amount = String::from("1");
        for _ in 0..40 {
            amount = format!("(1 + {amount})");
        }
        let text = format!("(x >> {amount}) == 0");
        let mut p = Parser::new(&text, &args, None, &unsigned, false);
        assert!(
            p.parse_or().is_ok(),
            "a 40-level nested amount fits the operand and must read without exhausting the stack"
        );
    }

    /// Negating a signed constant at its own type is checked against the *value*,
    /// not the written magnitude, so `-(i8::MIN)` and `-(3 << 7)` are refused.
    ///
    /// `i8::MIN` is the bit pattern `128` and the value `-128`. The reader's
    /// magnitude check reads the bit pattern, which is the same `128` that the
    /// legal literal `128i8` has, so it passed and the negation was recorded as
    /// the in-range `-128` -- and the reader *decided* `y == -(i8::MIN)` on a
    /// program rustc rejects with `attempt to negate i8::MIN, which would
    /// overflow`. `3 << 7` at eight bits wraps to the same bit pattern, so
    /// `-(3 << 7)` was decided too. Only a pristine literal is exempt, because
    /// there the negation is what makes the magnitude legal (`-128i8` reads).
    #[test]
    fn negating_a_signed_constant_is_checked_as_its_value() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        for text in [
            "y == -(i8::MIN)",
            "y == -(3 << 7)",
            "y == -(1 << 7)",
            "y <= (-(i8::MIN))",
            "y == -(-128i8)",
        ] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            assert!(
                p.parse_or().is_err(),
                "`{text}` negates a constant out of range at its own type and must be refused"
            );
        }
        // A pristine literal, the bound's maximum, and a plain negation read.
        for text in ["y == -128i8", "y == -(128i8)", "y == i8::MIN", "y == -(i8::MAX)",
                     "y == -(127)"] {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let r = p.parse_or();
            assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
        }
    }

    /// A typed constant mask against a partner of its *own* signedness reads.
    #[test]

    fn a_typed_constant_mask_with_a_same_signedness_partner_reads() {
        let mut args = BTreeMap::new();
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        let mut p = Parser::new("(-1i8 & 1) == y", &args, None, &signed, false);
        let pr = p.parse_or().expect("a signed mask vs a signed name reads");
        p.expect_end().expect("no trailing tokens");
        // `-1i8 & 1` is `1`, so the predicate holds only at `y == 1`.
        assert!(smt::evaluate_pred(pr, |_| Some(1)).expect("decides"), "`1 == 1`");
        assert!(!smt::evaluate_pred(pr, |_| Some(0)).expect("decides"), "`1 == 0` is false");
        // The unsigned direction reads against an unsigned name.
        let unsigned = BTreeSet::new();
        let mut p = Parser::new("(1u8 & 1) == y", &args, None, &unsigned, false);
        let pr = p.parse_or().expect("an unsigned mask vs an unsigned name reads");
        p.expect_end().expect("no trailing tokens");
        assert!(smt::evaluate_pred(pr, |_| Some(1)).expect("decides"), "`1 == 1`");
        assert!(!smt::evaluate_pred(pr, |_| Some(0)).expect("decides"), "`1 == 0` is false");
    }

    /// Unary `-` binds *tighter* than `as`, so `-x as u8` is `(-x) as u8` and its
    /// type is `u8` — unsigned — not the signed `-(x as u8)`.
    ///
    /// The values agree (negation and truncation commute), so the flag is what
    /// separates the readings, and the flag is what the operators and comparisons
    /// read. Getting it backwards made `-x as u8 > 127` unsatisfiable — an `i8` is
    /// never `> 127` — which reported a verifiable function as *vacuous*. Rust
    /// rejects `-x as u8` for an unsigned `x` with "cannot apply unary operator
    /// `-`", which is the language telling you the negation happens on `x` before
    /// the cast, not on the cast's result. So the operand here is a *signed* `x`
    /// (the only spelling rustc accepts for a negation), and the unsigned `x` case
    /// is asserted as a refusal below.
    #[test]
    fn a_negation_binds_tighter_than_a_cast() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::word(0, 8));
        let mut signed = BTreeSet::new();
        signed.insert("x".to_string());
        let parse = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let (v, sgn) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            (v, sgn)
        };
        // `(-x) as u8` is unsigned; `-(x as u8)` would be signed.
        let (_, sgn) = parse("-x as u8");
        assert!(!sgn.eval(), "`-x as u8` is `(-x) as u8`, an unsigned type");
        // The cast target decides the width, whichever way the negation is read,
        // so the value of the negation is not where the two readings differ.
        let (v, _) = parse("-x as u8");
        assert_eq!(smt::bits(v), 8, "the cast target is the width");
        // A cast *after* a parenthesized negation is the same thing, and is what
        // the explicit spelling looks like.
        let (_, sgn) = parse("(-x) as u8");
        assert!(!sgn.eval(), "`(-x) as u8` is unsigned too");
        // A negation with no cast is still signed, or the fix above would have
        // undone the previous one.
        let (_, sgn) = parse("-x");
        assert!(sgn.eval(), "a negation with no cast is signed");
        // A negation of an *unsigned* name is a rustc error (`E0600`), so it is
        // refused rather than decided.
        let unsigned = BTreeSet::new();
        let mut p = Parser::new("-x", &args, None, &unsigned, false);
        assert!(p.parse_expr().is_err(), "`-x` for a `u8` does not compile");
    }

    /// Unary `!` on a value is *bitwise* NOT and binds *tighter* than `==`, so
    /// `!x == 5` is `(!x) == 5`, not `!(x == 5)`.
    ///
    /// The parser handled `!` only at the *predicate* level, so `!x == 5` was read
    /// as the predicate `!(x == 5)` — `x != 5` — where Rust means `x == 250` for a
    /// `u8`. That is a different predicate, so it is a *wrong verdict*, not a
    /// refusal, and a bare `!x` was not readable at all. The fix splits the two:
    /// `bang_is_predicate` decides which reading applies, a predicate `!` stays at
    /// `parse_cmp`, and a value `!` is a prefix at `parse_neg` (bitwise NOT, the
    /// same term `mir/exec.rs` builds for `UnOp::Not`).
    #[test]
    fn a_bang_on_a_value_is_bitwise_not_and_binds_tight() {
        let mut args = BTreeMap::new();
        // A real variable, so the assignment below is what `x` reads.
        args.insert("x".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        let eval_const = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| None).expect("a constant")
        };
        // The value of an expression under an assignment to `x`.
        let eval_at = |text: &str, x: u64| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| Some(x)).expect("decides")
        };
        // The expression as a *predicate*, so a comparison is decided as a whole.
        let pred = |text: &str, x: u64| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let pr = p.parse_or().expect("parses as a predicate");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate_pred(pr, |_| Some(x)).expect("decides")
        };
        // `!0` is `255` at 8 bits: bitwise NOT, not a boolean.
        assert_eq!(eval_const("!0"), 0xFF, "`!` on a value is bitwise NOT");
        // `!!0` is `0`: the complement of the complement.
        assert_eq!(eval_const("!!0"), 0, "a double `!` is the identity");
        // `!1 + 1` is `(!1) + 1` = `254 + 1` = `255`. Read at the predicate level
        // it would not even parse as arithmetic.
        assert_eq!(eval_const("!1 + 1"), 0xFF, "`!` binds tighter than `+`");
        // `0 & !1` is `0 & 254` = `0`; the prefix applies to the literal `1`.
        assert_eq!(eval_const("0 & !1"), 0, "`!` applies to the operand, not the `&`");
        assert_eq!(eval_at("!x", 0), 0xFF, "a bare `!x` reads, and is bitwise");
        assert_eq!(eval_at("!x", 250), 5, "`!250` is `5` at 8 bits");
        // `!x & 1` is `(!x) & 1`; at `x == 0` that is `255 & 1 == 1`. If `&` bound
        // first the value would be `!(0 & 1) == 254`, so this separates the two.
        assert_eq!(eval_at("!x & 1", 0), 1, "`!` binds tighter than `&`");

        // `!x == 5` is decided at the *predicate* level, so assert the predicate
        // itself: `(!x) == 5` holds at `x == 250` and not at `x == 5`, which is the
        // opposite of what `!(x == 5)` would say.
        assert!(pred("!x == 5", 250), "`!x == 5` is `(!x) == 5`: true at 250");
        assert!(!pred("!x == 5", 5), "`!x == 5` is `(!x) == 5`: false at 5");
        // `!(x == 5)` is the predicate reading, and must still negate: false at 5
        // (the comparison holds, so its negation does not), true at 250.
        assert!(!pred("!(x == 5)", 5), "`!(x == 5)` is `x != 5`: false at 5");
        assert!(pred("!(x == 5)", 250), "`!(x == 5)` is `x != 5`: true at 250");
        // `!(x + 1)` holds *arithmetic*, so `!` is the value form here even though a
        // `(` follows: `!` is bitwise NOT, and `!(x + 1) == 5` is `(!(x + 1)) == 5`,
        // which holds at `x == 249` and not at `x == 5`. This is the case that
        // separates `bang_is_predicate`'s lookahead from "a `(` follows".
        assert!(pred("!(x + 1) == 5", 249), "`!(x + 1)` is `(!(x + 1))`, a value");
        assert!(!pred("!(x + 1) == 5", 5), "`!(x + 1)` is not a predicate negation");
    }

    /// A shift amount or a divisor may be a *constant expression*, and the reader
    /// must fold it before asking whether it is constant or zero.
    ///
    /// `const_of` answers "is this node a literal", which is the wrong question for
    /// both: `x >> 1 + 1` folds to `x >> 2` (constant, so the shift is fine), and
    /// `x % (1 - 1)` folds to `x % 0` (zero, so it must be refused). Asking the
    /// literal question misclassified the first as symbolic -- a barrel shifter in
    /// the body, an undecided query -- and let the second past the zero guard, so
    /// the reader built `srem(x, 0)` and returned a *definite verdict* from an
    /// undefined operation. `const_value` folds instead, which is what both want.
    #[test]
    fn a_constant_expression_is_folded_before_it_is_classified() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        let unsigned = BTreeSet::new();
        let parse = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            v
        };
        // A folded shift amount is a constant shift: `x >> 1 + 1` is `x >> 2`.
        let folded = parse("x >> 1 + 1");
        let literal = parse("x >> 2");
        assert_eq!(smt::evaluate(folded, |_| Some(8)), Some(2));
        assert_eq!(
            smt::evaluate(folded, |_| Some(8)),
            smt::evaluate(literal, |_| Some(8)),
            "`x >> 1 + 1` must read as `x >> 2`"
        );
        // A *symbolic* amount is still refused, not modelled as a barrel shifter.
        let mut p = Parser::new("x >> y", &args, None, &unsigned, false);
        assert!(p.parse_expr().is_err(), "a symbolic shift amount is refused");
        // A divisor of constant zero is refused however it is spelled.
        let mut p = Parser::new("x % (1 - 1)", &args, None, &unsigned, false);
        assert!(p.parse_expr().is_err(), "a folded zero divisor is refused");
        // A constant, non-zero divisor folds and reads: `4 / (1 + 1)` is `2`.
        assert_eq!(smt::evaluate(parse("x / (1 + 1)"), |_| Some(4)), Some(2));
    }

    /// A character literal is read as its Unicode scalar value, and one that is not
    /// an exact scalar value is refused.
    ///
    /// `'0'` is the everyday way a contract names a byte, and it must read as `0x30`
    /// at width 32. The escapes (`'\n'`, `'\u{...}'`, `'\\'`, `'\''`, `'\xNN'`) are
    /// read; a multi-character literal, an unknown escape and an unterminated
    /// literal are refused, because a guessed value in a contract is a false proof.
    #[test]
    fn a_char_literal_is_read_as_its_scalar_value_or_refused() {
        let mut args = BTreeMap::new();
        args.insert("c".to_string(), smt::var(32));
        let unsigned = BTreeSet::new();
        let val = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| None).expect("a constant")
        };
        let refuses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            p.parse_expr().is_err() || p.expect_end().is_err()
        };
        assert_eq!(val("'0'"), 0x30, "`'0'` is 48");
        assert_eq!(val("'A'"), 65);
        assert_eq!(val("'\\n'"), 0x0a, "a newline escape");
        assert_eq!(val("'\\t'"), 0x09);
        assert_eq!(val("'\\\\'"), 0x5c, "a backslash escape");
        assert_eq!(val("'\\''"), 0x27, "an escaped quote");
        assert_eq!(val("'\\x41'"), 0x41, "a byte escape");
        assert_eq!(val("'\\u{1F600}'"), 0x1F600, "a Unicode escape");
        assert_eq!(val("'\u{130}'"), 0x130, "a literal non-ASCII char");
        // Refusals, never a guessed value.
        assert!(refuses("'ab'"), "a multi-character literal is refused");
        assert!(refuses("'\\q'"), "an unknown escape is refused");
        assert!(refuses("'a"), "an unterminated literal is refused");
        assert!(refuses("''"), "an empty literal is refused");
        assert!(refuses("'\\u{110000}'"), "past the Unicode range is refused");
    }

    /// A `char` literal is *typed*: it does not resize to meet a narrower operand,
    /// so `'0' == 0u8` is refused exactly as rustc's `E0308` rejects it.
    ///
    /// The literal is built at width 32, and `Sign::Unsigned` does not adapt, so
    /// `align_widths` sees a width mismatch and refuses. A `char` compared against a
    /// `char` (both 32 bits) still reads, so the refusal is about the *mismatch*, not
    /// about `char` itself.
    #[test]
    fn a_char_literal_does_not_resize_to_a_narrower_operand() {
        let mut args = BTreeMap::new();
        args.insert("b".to_string(), smt::var(8));
        args.insert("c".to_string(), smt::var(32));
        let unsigned = BTreeSet::new();
        // A comparison is a *predicate*, so the entry point is `parse_cmp`.
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            p.parse_cmp().is_ok() && p.expect_end().is_ok()
        };
        assert!(parses("c == '0'"), "two `char`s compare");
        assert!(!parses("b == '0'"), "`'0' == 0u8` is `E0308`, so it is refused");
    }

    /// A radix literal is read at its *radix*, and one that is not an exact
    /// integer is refused rather than truncated.
    ///
    /// Every literal used to be read as decimal: the digit run stopped at the `x`
    /// of `0xFF` and the rest was skipped as a type suffix, so the value was `0`.
    /// That is a wrong *value*, and a wrong value in a precondition is a false
    /// proof -- `requires: x == 0xFF` became `x == 0`, and `ensures: ret == 0` was
    /// "proved" for a function returning `255`. Reading at the radix fixes the
    /// value; refusing the malformed shapes (`0b12`, `0o9`, `0xg`, `0xFFg`, past
    /// `u64`) keeps the fix from trading one silent number for another.
    #[test]
    fn a_radix_literal_is_read_at_its_radix_or_refused() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(16));
        let unsigned = BTreeSet::new();
        let val = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            let (v, _) = p.parse_expr().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate(v, |_| None).expect("a constant")
        };
        let refuses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &unsigned, false);
            p.parse_expr().is_err() || p.expect_end().is_err()
        };
        // Each radix reads at its own radix, not decimal.
        assert_eq!(val("0xFF"), 255, "`0xFF` is 255, not 0");
        assert_eq!(val("0x10"), 16, "`0x10` is 16, not 0");
        assert_eq!(val("0b1010"), 10, "`0b1010` is 10, not 0");
        assert_eq!(val("0o17"), 15, "`0o17` is 15, not 0");
        assert_eq!(val("0xFFFF"), 65535);
        // Underscores are separators in any radix, and a type suffix is dropped.
        assert_eq!(val("0xFF_FF"), 65535);
        assert_eq!(val("1_000"), 1000);
        assert_eq!(val("0xFFu8"), 255);
        assert_eq!(val("100_"), 100, "a trailing `_` is a separator");
        // A malformed literal is refused, never partially read.
        assert!(refuses("0b12"), "`0b12` has a non-binary digit");
        assert!(refuses("0o9"), "`0o9` has a non-octal digit");
        assert!(refuses("0xg"), "`0xg` has no hex digits");
        assert!(refuses("0xFFg"), "`0xFFg` has an unknown suffix");
        assert!(refuses("18446744073709551616"), "past `u64` is refused");
    }

    /// A literal that does not fit the operand's *signed* width is refused, even
    /// though its bit pattern does.
    ///
    /// `128` for an `i8` is `0x80`, which is exactly the bit pattern of `-128`, so
    /// a reader that only asks "does this fit in eight *unsigned* bits?" accepts it
    /// and reads `x <= 128` as `x <= -128`. rustc rejects `x <= 128` for an `i8`
    /// ("literal out of range for `i8`"), and the wrong reading is a false proof:
    /// `requires: x <= 128` with `ensures: x != 127` *held*. The `i8::MIN` bound
    /// shares the bit pattern and must still be accepted, which is why the fix
    /// distinguishes a non-negative literal from a signed constant rather than
    /// refusing every `0x80`.
    #[test]
    fn an_out_of_range_literal_is_refused_at_the_operand_width() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("x".to_string());
        // A whole *predicate*, so the comparison and its width alignment run.
        let reads = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            let pr = p.parse_or().expect("parses");
            p.expect_end().expect("no trailing tokens");
            smt::evaluate_pred(pr, |_| Some(0))
        };
        // `x <= 128` and `x >= -129` are both Rust errors for an `i8`, so they are
        // refused, not read as `x <= -128` / `x >= 127`.
        let mut p = Parser::new("x <= 128", &args, None, &signed, false);
        assert!(p.parse_or().is_err(), "`x <= 128` must be refused for an `i8`");
        let mut p = Parser::new("x >= -129", &args, None, &signed, false);
        assert!(p.parse_or().is_err(), "`x >= -129` must be refused for an `i8`");
        // The boundaries that *do* fit still read, and mean what they say.
        assert_eq!(reads("x <= 127"), Some(true), "127 is i8::MAX");
        assert_eq!(reads("x >= -128"), Some(true), "-128 is i8::MIN");
        let mut p = Parser::new("x == 128", &args, None, &signed, false);
        assert!(p.parse_or().is_err(), "`x == 128` is refused too");
        // Two *constants* have no typed name to take a width from, but the fit
        // check still runs: `128 <= i8::MAX` is a `literal out of range` error, and
        // reading `128` as `0x80` made it `-128 <= 127` -- always true. The in-range
        // counterpart and the named bound both still read.
        let mut p = Parser::new("128 <= i8::MAX", &args, None, &signed, false);
        assert!(
            p.parse_or().is_err(),
            "`128 <= i8::MAX` must be refused (literal out of range for `i8`)"
        );
        let mut p = Parser::new("127 <= i8::MAX", &args, None, &signed, false);
        assert!(p.parse_or().is_ok(), "`127 <= i8::MAX` is well-typed and must read");
        let mut p = Parser::new("i8::MIN <= i8::MAX", &args, None, &signed, false);
        assert!(p.parse_or().is_ok(), "`i8::MIN <= i8::MAX` must read");
    }

    /// A constant *arithmetic* expression is folded exactly, so one that overflows
    /// its operand width is refused rather than wrapping to a wrong value.
    ///
    /// `200u8 + 100u8` is a rustc const-eval error. Folding it mod 256 gave `44`,
    /// so `x <= 200 + 100` read as `x <= 44` -- a *stronger* precondition than the
    /// author wrote (`x <= 300`, which admits every `u8`) -- and `ensures: ret <= 44`
    /// was proved for a body that fails at `x == 100`. The check has to see the
    /// exact value, so the fold widens past the operand width instead of wrapping;
    /// the ordinary range check then refuses the shape when the operand it meets is
    /// too narrow, while a result that fits a wider operand still reads.
    #[test]
    fn an_overflowing_constant_expression_is_refused_not_wrapped() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let signed: BTreeSet<String> = BTreeSet::new();
        // A whole predicate, so the comparison's width alignment runs too.
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        // Overflowing sums, differences and products are all rustc errors, so
        // they are refused rather than folded to `44`, `255` and `1`.
        assert!(!parses("x <= 200 + 100"), "`200 + 100` overflows a `u8`");
        assert!(!parses("x >= 0 - 1"), "`0 - 1` underflows a `u8`");
        assert!(!parses("x == 255 + 1"), "`255 + 1` overflows a `u8`");
        assert!(!parses("x <= 200 * 2"), "`200 * 2` overflows a `u8`");
        // A sum that *does* fit reads as written, and a sum whose overflow is
        // legal because a wider operand types it still reads.
        assert!(parses("x <= 100 + 44"), "`100 + 44` fits a `u8` and must read");
        assert!(parses("x as u16 <= 200 + 100"), "`300` fits a `u16` and must read");
        assert!(parses("x <= 2 * 3 % 4"), "a fold that fits must still read");
        // The signed case is the trap: `i8::MAX + 1` is `128`, which fits an
        // unsigned byte but not a signed one. Widening at the *expression's*
        // signedness is what refuses it; an unsigned widening left it at eight bits
        // where it read as `-128` -- a new false proof in place of the old one.
        let mut sargs = BTreeMap::new();
        sargs.insert("y".to_string(), smt::var(8));
        let mut sset = BTreeSet::new();
        sset.insert("y".to_string());
        let sparses = |text: &str| {
            let mut p = Parser::new(text, &sargs, None, &sset, false);
            p.parse_or().is_ok()
        };
        assert!(!sparses("y <= i8::MAX + 1"), "`i8::MAX + 1` overflows an `i8`");
        assert!(!sparses("y <= 127 + 1"), "`127 + 1` overflows an `i8`");
        assert!(sparses("y <= i8::MAX"), "`i8::MAX` must read");
        assert!(sparses("y >= i8::MIN"), "`i8::MIN` must read");
    }

    /// A constant `/` or `%` that overflows the signed operand is refused.
    ///
    /// `i8::MIN / -1` is `128`, which does not fit an `i8`; rustc rejects it at
    /// compile time (and panics at runtime). The engine's divider wraps it to
    /// `MIN`, a wrong value, so the fold refuses the shape instead of handing the
    /// comparison a number the author never wrote.
    #[test]
    fn an_overflowing_constant_division_is_refused() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("x".to_string());
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        assert!(!parses("x == i8::MIN / -1"), "`i8::MIN / -1` overflows an `i8`");
        assert!(!parses("x == i8::MIN % -1"), "`i8::MIN % -1` overflows an `i8`");
        // In-range constant division still reads.
        assert!(parses("x == 100 / 2"), "`100 / 2` is `50` and must read");
        assert!(parses("x == -100 / 2"), "`-100 / 2` is `-50` and must read");
    }

    /// A signed constant compared with an unsigned operand is refused.
    ///
    /// Rust infers a literal's type from the operand it meets, so `x == -1` for a
    /// `u8` does not compile. The reader carries the negation as a bit pattern at
    /// the operand's width, which made `x == -1` read as `x == 255` -- a wrong
    /// value, and `ensures: ret == 255` was *proved* for a body returning `x`. The
    /// shape is refused rather than read, because the wrong reading is a proof and
    /// a proof cannot be a warning.
    ///
    /// The refusal is narrow on purpose: a bare literal is unsigned (`x <= 0xFF`
    /// for a `u8` is `255`, not a signed constant), and a signed *name* against an
    /// unsigned constant is not this shape.
    #[test]
    fn a_signed_constant_against_an_unsigned_operand_is_refused() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        args.insert("y".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("y".to_string());
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        // `x` is unsigned, the right-hand constant is signed: refused.
        assert!(!parses("x == -1"), "`-1` against a `u8` does not compile");
        assert!(!parses("x >= -1"), "`-1` against a `u8` does not compile");
        assert!(!parses("x <= -1"), "`-1` against a `u8` does not compile");
        // The same shape at the *arithmetic* levels, where it is equally a rustc
        // error and equally a false proof if read: `x + -1 >= 0` is trivially true
        // when `-1` is read as `255`.
        assert!(!parses("x + -1 >= 0"), "`x + -1` for a `u8` does not compile");
        assert!(!parses("x - -1 <= 0"), "`x - -1` for a `u8` does not compile");
        assert!(!parses("x % -1 == 0"), "`x % -1` for a `u8` does not compile");
        assert!(!parses("x * -1 == 255"), "`x * -1` for a `u8` does not compile");
        // And at the bitwise levels, where the same negation is the same rustc error.
        assert!(!parses("x & -1 == 255"), "`x & -1` for a `u8` does not compile");
        assert!(!parses("x | -1 == 0"), "`x | -1` for a `u8` does not compile");
        assert!(!parses("x ^ -1 == 0"), "`x ^ -1` for a `u8` does not compile");
        // The legal cases must still read.
        assert!(parses("x <= 0xFF"), "a bare literal is unsigned and must read");
        assert!(parses("x <= 255"), "a bare literal is unsigned and must read");
        assert!(parses("x + 255 >= 0"), "an unsigned constant still adds and reads");
        assert!(parses("x - 1 <= 255"), "an unsigned difference still reads");
        assert!(parses("x & 255 == x"), "an unsigned mask still reads");
        assert!(parses("x ^ 255 == 0"), "an unsigned xor still reads");
        assert!(parses("y <= -1"), "a signed name against a signed literal reads");
        assert!(parses("y >= i8::MIN"), "a signed bound against a signed name reads");
        assert!(parses("y + -1 <= 0"), "a signed name with a signed constant reads");
        assert!(parses("y ^ -1 == 0"), "a signed name with a signed mask reads");
        // Enumerate *every* operator, because the hole this test closes was found
        // one level at a time: a fix written at the comparison level left the
        // additive level reading `x + -1` as `x + 255`, and a fix written there
        // left the bitwise level reading `x ^ -1` as `x ^ 255`. The reader meets
        // two operands at all of these, so each is asserted rather than reasoned
        // safe. rustc rejects `x <op> -1` for a `u8` for all sixteen.
        //
        // A comparison *is* a predicate, so it stands alone; a value operator is
        // wrapped in `== 0` to make one. The wrap respects the crate's precedence
        // for every wrapped operator, so the inner term is parsed (and refused)
        // before the outer comparison runs.
        for op in ["==", "!=", "<", "<=", ">", ">="] {
            assert!(
                !parses(&format!("x {op} -1")),
                "`x {op} -1` for a `u8` does not compile and must be refused"
            );
            assert!(
                parses(&format!("x {op} 1")),
                "`x {op} 1` for a `u8` is legal and must still read"
            );
        }
        for op in ["+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"] {
            assert!(
                !parses(&format!("(x {op} -1) == 0")),
                "`x {op} -1` for a `u8` does not compile and must be refused"
            );
            assert!(
                parses(&format!("(x {op} 1) == 0")),
                "`x {op} 1` for a `u8` is legal and must still read"
            );
        }
    }

    /// A *suffixed* literal carries its type's signedness, so a mismatched
    /// constant pair is refused instead of silently read as signed.
    ///
    /// `0u8` is unsigned, so `-1 <= 0u8` is `E0277` (a `u8` cannot be negated).
    /// The tokenizer used to *drop* the suffix, leaving the reader no way to tell
    /// `0u8` from a bare `0`; the pair then had no unsigned side to see, the
    /// both-constant branch of `refuse_mixed_signedness` was not reached (it
    /// required exactly *one* constant), and the comparison was read as *signed*
    /// and silently decided -- `ensures: -1 <= 0u8` "verified" as `-1 <= 0`. The
    /// suffix is now kept, so the unsigned side is visible and the shape is refused.
    #[test]
    fn a_suffixed_literal_carries_its_type_signedness() {
        let args = BTreeMap::new();
        let signed = BTreeSet::new();
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        // Two constants of different signedness: each is an error, not a decision.
        assert!(!parses("-1 == 0u8"), "`-1 == 0u8` is `E0277` and must be refused");
        assert!(!parses("-1 <= 0u8"), "`-1 <= 0u8` is `E0277` and must be refused");
        assert!(!parses("-1 < 0u8"), "`-1 < 0u8` is `E0277` and must be refused");
        assert!(!parses("0u8 > -1"), "`0u8 > -1` is `E0277` and must be refused");
        assert!(!parses("-1i8 == 0u8"), "`-1i8 == 0u8` is `E0308` and must be refused");
        assert!(!parses("-1i16 == 65535u16"), "`-1i16 == 65535u16` must be refused");
        // The valid pairs still read: two constants of the *same* signedness, a
        // bare literal (untyped) against either, and a signed pair.
        assert!(parses("-1 <= 0"), "`-1 <= 0` is legal and must read");
        assert!(parses("-1i8 <= 0i8"), "`-1i8 <= 0i8` is legal and must read");
        assert!(parses("0u8 <= 255u8"), "`0u8 <= 255u8` is legal and must read");
        assert!(parses("-1 <= 255"), "a bare literal adopts the signed side and reads");
        assert!(parses("255u8 == 255"), "a bare literal adopts the unsigned side");
    }

    /// A `!`-complement of a literal is refused where its sign would change the
    /// meaning.
    ///
    /// `!0 >> 1` is `127` read unsigned and `-1` read signed, and the reader's old
    /// default (a literal is unsigned) *discharged* `ensures: ret <= (!0 >> 1)`
    /// for an `i8` though Rust reads it `ret <= -1`. With no typed operand to fix
    /// the signedness the shape is refused, not guessed; a typed operand reads it
    /// exactly, and the operators where the two signs agree still read.
    #[test]
    fn a_bang_literal_is_refused_where_its_sign_would_change_the_meaning() {
        let mut args = BTreeMap::new();
        args.insert("x".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("x".to_string());
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        // A `!`-complement of a literal has no type of its own: refused at a
        // shift, a `/`/`%`, and an ordering comparison.
        assert!(!parses("(!0 >> 1) == 0"), "`!0 >> 1` has no typed operand");
        assert!(!parses("(!4 >> 2) == 0"), "`!4 >> 2` has no typed operand");
        assert!(!parses("(!4 / 2) == 0"), "`!4 / 2` has no typed operand");
        assert!(!parses("(!4 % 3) == 0"), "`!4 % 3` has no typed operand");
        assert!(!parses("(!0) < 0"), "`!0 < 0` has no typed operand");
        assert!(!parses("(!7) >= 0"), "`!7 >= 0` has no typed operand");
        // Equality too. `==`/`!=` were left readable at first ("they compare bit
        // patterns"), but the two readings of an untyped constant are different
        // *values*, not a different ordering of one: Rust types an untyped constant
        // as `i32`, so `!0` is `-1` and `!0 == 255` is `false`, while the reader
        // built `255u8 == 255` and *verified* `ensures: !0 == 255` -- a false
        // proof. So the ambiguous operand is refused at `==`/`!=` as well.
        assert!(!parses("(!0) == 255"), "`!0 == 255` is `false` in Rust, not provable");
        assert!(!parses("(!0) != 255"), "`!0 != 255` has no typed operand");
        assert!(!parses("(!4) == 251"), "`!4 == 251` is `false` in Rust, not provable");
        assert!(!parses("(!0) == (!0)"), "both operands untyped and ambiguous");
        // Two *bare* literals are unambiguous, so equality still reads.
        assert!(parses("2 == 2"), "two bare literals compare exactly");
        assert!(parses("x == 0"), "a typed operand fixes the reading");
        assert!(parses("x == !x"), "`!x` carries `x`'s type, so the pair is typed");
        // The refusal is narrow. A typed operand fixes the signedness, and a bare
        // literal is non-negative, so both still read.
        assert!(parses("x >> 1 < 0"), "a shift of a name is exact");
        assert!(parses("(!x >> 1) < 0"), "a shift of `!x` is exact");
        assert!(parses("x <= 5"), "a small literal is unambiguous");
        // (`x & !1` and `x == !4` are refused too, but for the unrelated reason
        // that `!1`/`!4` are large non-negative values that do not fit a signed
        // 8-bit operand -- a completeness gap, not a sign guess.)
    }

    #[test]
    fn two_names_of_different_signedness_are_refused() {
        let mut args = BTreeMap::new();
        args.insert("s".to_string(), smt::var(8));
        args.insert("u".to_string(), smt::var(8));
        let mut signed = BTreeSet::new();
        signed.insert("s".to_string());
        let parses = |text: &str| {
            let mut p = Parser::new(text, &args, None, &signed, false);
            p.parse_or().is_ok()
        };
        // Every operator where two operands meet, both orders. A comparison is a
        // predicate and stands alone; a value operator is wrapped to make one.
        for op in ["==", "!=", "<=", ">=", "<", ">"] {
            assert!(
                !parses(&format!("s {op} u")),
                "`s {op} u` for an `i8` and a `u8` does not compile and must be refused"
            );
            assert!(
                !parses(&format!("u {op} s")),
                "`u {op} s` is the same mismatched comparison and must be refused"
            );
        }
        for op in ["+", "-", "*", "/", "%", "&", "|", "^"] {
            assert!(
                !parses(&format!("(s {op} u) == 0")),
                "`s {op} u` for an `i8` and a `u8` does not compile and must be refused"
            );
            assert!(
                !parses(&format!("(u {op} s) == 0")),
                "`u {op} s` is the same mismatched operation and must be refused"
            );
        }
        // The legal cases must still read: two names of the *same* signedness, and
        // a name with a literal of either value.
        assert!(parses("s <= s"), "two signed names read");
        assert!(parses("u <= u"), "two unsigned names read");
        assert!(parses("s < 0"), "a signed name against a bare literal reads");
        assert!(parses("u < 255"), "an unsigned name against a bare literal reads");
        assert!(parses("s < 0 && u > 0"), "both halves legal, the conjunction reads");
        // A shift is exempt: Rust lets the amount have its own type, so `s << u`
        // is legal (the amount must be constant in a contract, but its
        // *signedness* is free).
        assert!(parses("(s >> 1) == 0"), "a signed shift by a constant reads");
    }

    /// An explicit discriminant sets the variant's value and the next continues
    /// from it, not from the variant's position.
    #[test]
    fn an_explicit_discriminant_renumbers_the_rest() {
        let d = def("pub enum E { A, B = 3, C }\n");
        assert_eq!(d.index_of("A"), Some(0));
        assert_eq!(d.index_of("B"), Some(3));
        assert_eq!(d.index_of("C"), Some(4));
        // The tag has to hold `4`, which needs three bits, not the two a count of
        // three would give.
        assert_eq!(d.tag_width(), 3);
    }

    /// A hex, binary or octal literal is read at its own radix.
    #[test]
    fn a_radix_prefixed_discriminant_is_read() {
        let d = def("pub enum E { A = 0x10, B = 0b101, C = 0o7, D }\n");
        assert_eq!(d.index_of("A"), Some(16));
        assert_eq!(d.index_of("B"), Some(5));
        assert_eq!(d.index_of("C"), Some(7));
        assert_eq!(d.index_of("D"), Some(8));
    }

    /// A non-literal discriminant refuses the whole layout, so a contract naming
    /// any variant of the enum is a refusal rather than a guess.
    #[test]
    fn an_unreadable_discriminant_refuses_the_whole_layout() {
        let specs = extract("pub enum E { A, B = 1 << 4, C }\n");
        assert!(!specs.enums.contains_key("E"), "the layout must not be recorded at all");
    }

    /// A struct variant still takes its discriminant, so a later variant's value
    /// is right.
    #[test]
    fn a_struct_variant_still_takes_a_discriminant() {
        let d = def("pub enum E {\n    A,\n    Pair { x: u8 },\n    C,\n}\n");
        assert_eq!(d.index_of("A"), Some(0));
        assert_eq!(d.index_of("Pair"), Some(1));
        assert_eq!(d.index_of("C"), Some(2));
    }

    /// The domain assumed for a tag is the set of discriminants, so a gap is not
    /// excluded.
    #[test]
    fn the_tag_domain_is_the_discriminants() {
        let d = def("pub enum E { A, B = 3, C }\n");
        assert_eq!(d.variants.iter().map(|(_, _, d)| *d).collect::<Vec<_>>(), vec![0, 3, 4]);
    }

    /// An unreadable discriminant on a *one-line* enum must not leave the enum
    /// cursor open.
    ///
    /// The one-line reader returns the variants when it can read them and, for an
    /// unreadable discriminant, used to answer "a multi-line body follows". That
    /// answer opened a cursor *after* the closing brace had already been seen, so
    /// every following line -- including `///` contracts and the `fn` items they
    /// belong to -- was consumed as enum contents. Those functions then had no
    /// contract at all, so they were neither verified nor reported as skipped:
    /// they silently left the check set.
    #[test]
    fn an_unreadable_one_line_enum_does_not_swallow_the_next_contract() {
        let src = "pub enum E { A, B = 1 << 4 }\n\n\
                   /// ensures: ret == 1\n\
                   pub fn f() -> u8 { 0 }\n";
        let specs = extract(src);
        assert!(!specs.enums.contains_key("E"), "the refused layout must not be recorded");
        assert!(
            specs.by_fn.contains_key("f"),
            "the contract after a refused enum must still be read, got: {:?}",
            specs.by_fn.keys().collect::<Vec<_>>()
        );
    }

    /// A `decreases:` line is read as a contract clause, and it is enough on its
    /// own to make a function "carry a claim".
    ///
    /// Both halves matter. If the extractor dropped `decreases:`, a recursive
    /// function would silently lose its induction principle and fall back to
    /// inlining, which reads as "incomplete" rather than as a parse bug. And if a
    /// bare `decreases:` did not count as a claim, the function would not be in
    /// `by_fn` at all, so it would neither be verified nor reported skipped.
    #[test]
    fn a_decreases_clause_is_read_and_counts_as_a_claim() {
        let src = "/// decreases: n\n\
                   pub fn f(n: u8) -> u8 { n }\n";
        let specs = extract(src);
        let c = specs.by_fn.get("f").expect("a `decreases:` alone is a claim");
        assert_eq!(c.decreases, vec!["n".to_string()], "the measure text must be kept");
        assert!(c.requires.is_empty() && c.ensures.is_empty());
    }

    /// `unwind: <n>` is read as a number and counts as a claim, so a function that
    /// carries only an `unwind:` is not silently dropped.
    #[test]
    fn an_unwind_clause_is_read_and_counts_as_a_claim() {
        let src = "/// unwind: 40\n\
                   pub fn f(n: u8) -> u8 { n }\n";
        let specs = extract(src);
        let c = specs.by_fn.get("f").expect("an `unwind:` alone is a claim");
        assert_eq!(c.unwind, Some(40), "the bound must be read as a number");
        assert!(c.requires.is_empty() && c.ensures.is_empty());
    }

    /// A non-numeric, zero or negative `unwind:` is refused rather than defaulted.
    ///
    /// A guessed bound is a guessed proof, and a bound of zero would make every
    /// loop an immediate cutoff while reading as an ordinary clause. `unwind:`
    /// must therefore name a positive integer or the function is `Skipped`.
    #[test]
    fn a_non_numeric_or_zero_unwind_is_refused() {
        for bad in ["unwind: 0", "unwind: abc", "unwind: -1", "unwind: 1.5"] {
            let src = format!("/// {bad}\npub fn f(n: u8) -> u8 {{ n }}\n");
            let specs = extract(&src);
            let c = specs.by_fn.get("f").expect("the item is still read");
            assert!(
                c.unwind.is_none(),
                "`{bad}` must not become a bound; got {:?}",
                c.unwind
            );
        }
    }

    /// The measure is evaluated against the arguments, and its signedness travels
    /// with the value. A signed argument must give a *signed* measure, because the
    /// decrease test is `slt` rather than `ult` for a signed one -- reading `i8`
    /// as unsigned would prove `n - 1 < n` for a measure that actually runs
    /// negative, which is exactly the well-foundedness the check exists to keep.
    #[test]
    fn a_measure_takes_its_sign_from_its_arguments() {
        let mut args = BTreeMap::new();
        args.insert("n".to_string(), smt::var_named(1, 8));
        let consts = BTreeMap::new();

        let unsigned = BTreeSet::new();
        let (_, u_signed) = eval_measure("n", &args, &unsigned, &consts).expect("`n` parses");
        assert!(!u_signed, "an unsigned argument gives an unsigned measure");

        let signed: BTreeSet<String> = ["n".to_string()].into_iter().collect();
        let (_, s_signed) = eval_measure("n", &args, &signed, &consts).expect("`n` parses");
        assert!(s_signed, "a signed argument gives a signed measure");

        // A compound measure keeps the argument's sign through the arithmetic.
        let (_, sum_signed) =
            eval_measure("n + 1", &args, &signed, &consts).expect("`n + 1` parses");
        assert!(sum_signed, "the sign must survive the addition");
    }

    /// A measure that does not parse is an error, not a silently absent measure.
    ///
    /// This is the same rule the other clauses follow: an unreadable clause must
    /// never become `true` (or here, `None`), because then a function would be
    /// verified against a contract the reader never understood.
    #[test]
    fn an_unreadable_measure_is_an_error() {
        let mut args = BTreeMap::new();
        args.insert("n".to_string(), smt::var_named(1, 8));
        let consts = BTreeMap::new();
        let signed = BTreeSet::new();
        assert!(eval_measure("n +", &args, &signed, &consts).is_err(), "a dangling `+`");
        assert!(eval_measure("nope", &args, &signed, &consts).is_err(), "an unknown name");
        assert!(eval_measure("", &args, &signed, &consts).is_err(), "an empty measure");
    }

    /// A one-line *struct* body must not swallow the functions after it either.
    ///
    /// `struct_head` accepted any line containing `{` and opened a multi-line field
    /// cursor, so `pub struct B { pub lo: u8 }` left the cursor open with the brace
    /// already closed: every following line -- the `///` contracts and the `fn`
    /// items -- was consumed as struct fields. Those functions then had no contract
    /// at all, so they were neither verified nor reported as skipped; they silently
    /// left the check set. The enum reader has distinguished an inline body from a
    /// multi-line one all along; the struct reader did not.
    #[test]
    fn a_one_line_struct_does_not_swallow_the_next_contract() {
        let src = "pub struct B { pub lo: u8 }\n\n\
                   /// ensures: ret == 1\n\
                   pub fn f() -> u8 { 0 }\n";
        let specs = extract(src);
        assert!(
            specs.structs.contains_key("B"),
            "a one-line struct body must still be recorded, got: {:?}",
            specs.structs.keys().collect::<Vec<_>>()
        );
        assert_eq!(
            specs.structs["B"].fields.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(),
            vec!["lo"],
            "the one-line body's field must be read out of the head line"
        );
        assert!(
            specs.by_fn.contains_key("f"),
            "the contract after a one-line struct must still be read, got: {:?}",
            specs.by_fn.keys().collect::<Vec<_>>()
        );
    }

    /// The same for the multi-line path: the refusal must close the cursor at the
    /// brace, not at whatever `}` comes next.
    #[test]
    fn a_refused_multi_line_enum_does_not_swallow_the_next_contract() {
        let src = "pub enum E {\n    A,\n    B = 1 << 4,\n}\n\n\
                   /// ensures: ret == 1\n\
                   pub fn f() -> u8 { 0 }\n";
        let specs = extract(src);
        assert!(!specs.enums.contains_key("E"), "the refused layout must not be recorded");
        assert!(
            specs.by_fn.contains_key("f"),
            "the contract after a refused multi-line enum must still be read, got: {:?}",
            specs.by_fn.keys().collect::<Vec<_>>()
        );
    }

    /// A contract written above a struct must not attach to the next function.
    ///
    /// `struct_head` and `enum_head` matched their line and `continue`d without
    /// clearing the pending contract, so a doc comment above a struct -- which is
    /// the struct's documentation, not a function's contract -- carried over to
    /// the next `fn`. A leaked `requires` is a false proof when it is satisfiable:
    /// `requires: x == 0` above a struct makes `ensures: ret == 0` for a body
    /// returning `x` *verify*, because the check is only made for `x == 0`. The
    /// same contract with no struct above it is correctly refuted.
    #[test]
    fn a_contract_above_a_struct_does_not_attach_to_the_next_function() {
        let src = "/// requires: x == 0\n\
                   pub struct S { pub v: u8 }\n\
                   /// ensures: ret == 0\n\
                   pub fn f(x: u8) -> u8 { x }\n";
        let specs = extract(src);
        let c = specs.by_fn.get("f").expect("`f` must carry a contract");
        assert!(
            c.requires.is_empty(),
            "the struct's doc comment leaked into `f`: {:?}",
            c.requires
        );
        assert_eq!(c.ensures, vec!["ret == 0"], "the function's own `ensures` must survive");
    }

    /// The same leak through an enum head, which had the identical shape.
    #[test]
    fn a_contract_above_an_enum_does_not_attach_to_the_next_function() {
        let src = "/// requires: x == 0\n\
                   pub enum E { A, B }\n\
                   /// ensures: ret == 0\n\
                   pub fn f(x: u8) -> u8 { x }\n";
        let specs = extract(src);
        let c = specs.by_fn.get("f").expect("`f` must carry a contract");
        assert!(c.requires.is_empty(), "the enum's doc comment leaked into `f`: {:?}", c.requires);
        assert_eq!(c.ensures, vec!["ret == 0"]);
    }

    /// A trailing line comment on a variant line is not part of the variant.
    ///
    /// `B = 3, // special` puts the comma *before* the comment, so trimming a
    /// trailing comma off the raw line leaves `B = 3, // special` -- the comma is
    /// no longer last. The discriminant reader then rejected the whole line and
    /// the layout was dropped, taking every contract that named a variant with it.
    #[test]
    fn a_trailing_comment_on_a_variant_is_not_part_of_it() {
        let src = "pub enum E {\n    A,\n    B = 3, // special\n    C,\n}\n";
        let d = def(src);
        assert_eq!(d.index_of("A"), Some(0));
        assert_eq!(d.index_of("B"), Some(3));
        assert_eq!(d.index_of("C"), Some(4), "C follows B's explicit value, not its position");
    }

    /// A comment after an implicit variant must not change its numbering either.
    #[test]
    fn a_trailing_comment_on_an_implicit_variant_is_ignored() {
        let src = "pub enum E {\n    A, // first\n    B,\n}\n";
        let d = def(src);
        assert_eq!(d.index_of("A"), Some(0));
        assert_eq!(d.index_of("B"), Some(1));
    }

    fn field_env_with(consts: &[(&str, Const)]) -> FieldEnv {
        let mut e = FieldEnv::default();
        for (k, v) in consts {
            e.consts.insert((*k).to_string(), v.clone());
        }
        e
    }

    /// A contract resolves a named `const` to its literal value, at the item's own
    /// width and sign.
    #[test]
    fn a_contract_reads_a_const_name_as_its_value() {
        let args = BTreeMap::new();
        let env = field_env_with(&[
            ("LIMIT", Const::UInt(10, Some(Ty::U8))),
            ("NEG", Const::UInt(0xff, Some(Ty::I8))),
            ("B", Const::Bool(true)),
        ]);
        // `LIMIT` is `10`; a precondition demanding `<= 9` is refutable, and one
        // demanding `<= 10` holds. This pins the value, not just that it parsed.
        let p = eval_requires("LIMIT <= 10", &args, &BTreeSet::new(), &env).unwrap();
        assert_eq!(smt::prove(p), smt::Verdict::Valid);
        let p = eval_requires("LIMIT <= 9", &args, &BTreeSet::new(), &env).unwrap();
        assert_ne!(smt::prove(p), smt::Verdict::Valid, "LIMIT is 10, so `<= 9` must not hold");
        // A negative constant keeps its sign: `NEG <= -1` holds, `NEG >= 0` does not.
        let p = eval_requires("NEG <= -1", &args, &BTreeSet::new(), &env).unwrap();
        assert_eq!(smt::prove(p), smt::Verdict::Valid);
        let p = eval_requires("NEG >= 0", &args, &BTreeSet::new(), &env).unwrap();
        assert_ne!(smt::prove(p), smt::Verdict::Valid, "NEG is -1, so `>= 0` must not hold");
        // A boolean constant compared against a boolean literal.
        let p = eval_requires("B == true", &args, &BTreeSet::new(), &env).unwrap();
        assert_eq!(smt::prove(p), smt::Verdict::Valid);
    }

    /// An argument shadows a constant of the same name, so a contract naming an
    /// argument keeps resolving to it. Reading the constant there would bind the
    /// wrong value -- a false proof, not a refusal.
    #[test]
    fn an_argument_shadows_a_const_of_the_same_name() {
        let mut args = BTreeMap::new();
        args.insert("LIMIT".to_string(), smt::var_named(1, 8));
        let env = field_env_with(&[("LIMIT", Const::UInt(10, Some(Ty::U8)))]);
        // The argument is symbolic, so `LIMIT <= 10` cannot be proved even though
        // the constant would make it true -- proof that the argument won.
        let p = eval_requires("LIMIT <= 10", &args, &BTreeSet::new(), &env).unwrap();
        assert_ne!(smt::prove(p), smt::Verdict::Valid);
    }

    /// A name that is not a literal constant is refused, not guessed at.
    #[test]
    fn a_non_literal_const_name_is_refused() {
        let args = BTreeMap::new();
        let env = field_env_with(&[("EXPR", Const::Other("_".into()))]);
        assert!(eval_requires("EXPR <= 1", &args, &BTreeSet::new(), &env).is_err());
        // A misspelled name is still refused as an unknown name.
        assert!(eval_requires("LIMITT <= 1", &args, &BTreeSet::new(), &env).is_err());
    }

    /// The crate-level `const` scanner reads items at brace depth zero and only
    /// those.
    ///
    /// The dump cannot tell a crate-level `const` from a function-local one, so the
    /// source's brace depth is the second tell -- the one that catches a
    /// crate-level constant a contract names but no body uses. Reading too much
    /// would re-open the local-leak false proof, so the negative cases matter as
    /// much as the positive one: a local item, an associated constant in an `impl`,
    /// a `const` generic parameter, and a `const` inside a string or comment must
    /// all be left out.
    #[test]
    fn crate_level_consts_reads_only_module_scope_items() {
        let src = r#"
// const COMMENTED: u8 = 1;
const LIMIT: u8 = 10;
pub const PUB_LIMIT: u8 = 11;
const TYPO: u8 = 12;

/// const DOC: u8 = 13;
pub fn f() -> u8 {
    const LOCAL: u8 = 3;
    let s = "const IN_STRING: u8 = 4";
    let _ = s;
    LOCAL
}

impl Foo {
    const ASSOC: u8 = 5;
}

fn g<const N: usize>() -> usize { N }

fn h<
    const SPLIT: usize,
>() -> usize {
    SPLIT
}
"#;
        let names = crate_level_consts(src);
        assert!(names.contains("LIMIT"), "a crate-level const is read: {names:?}");
        assert!(names.contains("PUB_LIMIT"), "a `pub const` is read: {names:?}");
        assert!(names.contains("TYPO"), "a plain crate-level const is read: {names:?}");
        assert!(!names.contains("COMMENTED"), "a commented-out item is not read: {names:?}");
        assert!(!names.contains("DOC"), "a doc-comment line is not read: {names:?}");
        assert!(!names.contains("LOCAL"), "a function-local const is not read: {names:?}");
        assert!(!names.contains("IN_STRING"), "a const inside a string is not read: {names:?}");
        assert!(!names.contains("ASSOC"), "an associated const is not read: {names:?}");
        assert!(
            !names.contains("N"),
            "a `const` generic parameter is not a module-scope item: {names:?}"
        );
        // The parameter list split across lines is the shape the scan actually
        // meets: the `const` opens a line, so only the *preceding* line's last
        // character (`<`) says it is a parameter rather than an item.
        assert!(
            !names.contains("SPLIT"),
            "a `const` generic parameter on its own line is not an item: {names:?}"
        );
    }

    /// `const_generic_params` reads parameters and only parameters.
    ///
    /// A parameter is written `const NAME:` after a `<` or `,`; an item never is.
    /// The tell has to survive the parameter list being split across lines, and it
    /// must not fire on a `const` item, an associated constant, or a `const` in a
    /// comment or string.
    #[test]
    fn const_generic_params_reads_only_parameters() {
        let names = const_generic_params(
            "fn f<const N: usize>() -> usize { N }\n\
             fn g<\n    const M: usize,\n>(x: usize) -> usize { x + M }\n\
             const ITEM: u8 = 1;\n\
             struct S<const K: usize>([u8; K]);\n\
             // const COMMENT: u8 = 2;\n\
             fn h() { let s = \"const STR: u8 = 3\"; let _ = s; }\n",
        );
        assert!(names.contains("N"), "an inline parameter is read: {names:?}");
        assert!(names.contains("M"), "a parameter after a line break is read: {names:?}");
        assert!(names.contains("K"), "a parameter in a type's list is read: {names:?}");
        assert!(!names.contains("ITEM"), "a `const` item is not a parameter: {names:?}");
        assert!(!names.contains("COMMENT"), "a commented-out parameter is not read: {names:?}");
        assert!(!names.contains("STR"), "a parameter inside a string is not read: {names:?}");
    }

    /// Whitespace and comments between `const` and the parameter name are legal
    /// Rust, and the name must still be read.
    ///
    /// The scanner once required a literal `"const "`, so `const\n    N: usize`
    /// and `const/*c*/N: usize` slipped through. The parameter name then stayed
    /// out of `const_generics`, and a function-local `const N` in some other
    /// function kept a bare program-wide key -- which an unrelated contract
    /// naming `N` resolved to, a false proof.
    #[test]
    fn const_generic_params_survives_whitespace_and_comments() {
        for source in [
            "fn f<const\n    N: usize>() -> usize { N }\n",
            "fn f<const\tN: usize>() -> usize { N }\n",
            "fn f<const/*c*/N: usize>() -> usize { N }\n",
            "fn f<const // c\n    N: usize>() -> usize { N }\n",
            "struct S<A, const\n    N: usize>([u8; N], A);\n",
        ] {
            let names = const_generic_params(source);
            assert!(
                names.contains("N"),
                "the parameter after the `const` keyword must be read: {source:?} -> {names:?}"
            );
        }
    }

    /// A source that ends inside an unclosed block comment must not panic.
    ///
    /// The scanner runs over the raw source before rustc sees it, so malformed
    /// input reaches it. An unterminated `/*` after a `const` generic parameter
    /// runs the comment skip to end-of-file, and stepping two bytes past the
    /// buffer made the following slice panic -- a crash on input whose only
    /// correct handling is to let rustc report the syntax error.
    #[test]
    fn const_generic_params_tolerates_an_unclosed_block_comment() {
        for source in [
            "fn f<const /*",
            "fn f<const /*x",
            "fn f<const /* ",
            "fn f<const /*/",
            "fn f<const /*x*",
            "fn f<const /*x*/",
            "fn f<const /*\n",
        ] {
            // The property is "does not panic"; the call itself is the assertion.
            let _ = const_generic_params(source);
        }
    }

    /// The trait an `impl` block implements is read from its header, and an
    /// inherent `impl` has none.
    ///
    /// This is what separates a local `impl From<u8> for u16` from the standard
    /// library's when both own `u16` and both spell their method `from`. The path
    /// is kept whole (`std::convert::From`), because a bare `From` is *not* a
    /// suffix of the qualified path a call prints for the library trait, and that
    /// non-match is the guard. See [`Specs::impl_traits`].
    #[test]
    fn impl_trait_reads_the_trait_and_refuses_an_inherent_impl() {
        assert_eq!(impl_trait("impl From<u8> for u16 {"), Some("From".to_string()));
        assert_eq!(
            impl_trait("impl std::convert::From<u8> for u16 {"),
            Some("std::convert::From".to_string())
        );
        assert_eq!(impl_trait("impl core::cmp::Ord for Foo {"), Some("core::cmp::Ord".to_string()));
        // An `impl<T>` parameter list is skipped, as for the owner.
        assert_eq!(impl_trait("impl<T> From<T> for Wrapper<T> {"), Some("From".to_string()));
        // `unsafe impl` still names its trait.
        assert_eq!(impl_trait("unsafe impl Send for Foo {}"), Some("Send".to_string()));
        // An inherent impl has no trait.
        assert_eq!(impl_trait("impl u16 {"), None);
        assert_eq!(impl_trait("impl<T> Wrapper<T> {"), None);
        // A nested type argument does not end the path early.
        assert_eq!(
            impl_trait("impl Convert<Option<u8>> for Foo {"),
            Some("Convert".to_string())
        );
    }

    /// The `impl_traits` map is keyed by the `impl` keyword's location -- the same
    /// key as `impl_owners` -- and qualifies the trait with its enclosing module.
    ///
    /// A call prints a module-local trait with its module (`<u16 as m::From<u8>>::from`),
    /// so the recorded path must carry that module too, or the guard would refuse a
    /// legitimate local impl. A crate-root impl keeps its bare path.
    #[test]
    fn impl_traits_are_keyed_by_location_and_module_qualified() {
        let src = "mod m {\n    pub trait From<T> { fn from(t: T) -> Self; }\n    \
                   impl From<u8> for u16 { fn from(_t: u8) -> u16 { 7 } }\n}\n\
                   struct Wrapper(u8);\n\
                   impl Wrapper { fn make() -> Wrapper { Wrapper(0) } }\n";
        let specs = extract(src);
        // `impl From` is on line 3; the module `m` prefixes it.
        assert_eq!(specs.impl_traits.get(&(3, 5)), Some(&"m::From".to_string()));
        assert_eq!(specs.impl_owners.get(&(3, 5)), Some(&"u16".to_string()));
        // The inherent `impl Wrapper` on line 6 has an owner but no trait.
        assert_eq!(specs.impl_owners.get(&(6, 1)), Some(&"Wrapper".to_string()));
        assert_eq!(specs.impl_traits.get(&(6, 1)), None);
    }

    /// `split_leading_attrs` peels every leading attribute and reports a `#[cfg]`
    /// among them, so a same-line attribute cannot hide the item behind it.
    #[test]
    fn leading_attributes_are_peeled_and_a_cfg_is_reported() {
        // No attribute: the line is returned unchanged and no `cfg` is seen.
        assert_eq!(split_leading_attrs("use a::B;"), ("use a::B;", false));
        // A bare attribute on its own line is peeled.
        assert_eq!(split_leading_attrs("#[cfg(any())] use a::B;"), ("use a::B;", true));
        // Two attributes: the `cfg` is reported even when it is not the first.
        assert_eq!(
            split_leading_attrs("#[allow(unused)] #[cfg(test)] use a::B;"),
            ("use a::B;", true)
        );
        // A non-`cfg` attribute is peeled but not reported.
        assert_eq!(split_leading_attrs("#[allow(dead_code)] use a::B;"), ("use a::B;", false));
        // The body's own brackets nest, so the attribute ends at its own `]`.
        assert_eq!(
            split_leading_attrs("#[cfg(all(unix, target_os = \"linux\"))] use a::B;"),
            ("use a::B;", true)
        );
        // `cfg_attr` is a `cfg`-family attribute, so it is reported too.
        assert_eq!(split_leading_attrs("#[cfg_attr(x, allow(y))] use a::B;"), ("use a::B;", true));
    }

    /// `is_use_start` sees a `use` behind a same-line attribute, and `strip_visibility`
    /// reads the visibility that follows one.
    #[test]
    fn a_use_behind_a_same_line_attribute_is_still_an_import() {
        assert!(is_use_start("#[cfg(all())] use std::convert::From;"));
        assert!(is_use_start("#[allow(unused)] pub(crate) use a::B;"));
        assert!(!is_use_start("#[allow(unused)] let x = 1;"));
        // A visibility behind a same-line attribute is stripped as before.
        assert_eq!(strip_visibility("#[allow(x)] pub(crate) use a::B;"), "use a::B;");
    }

    /// A `#[cfg]`-conditional import never displaces an unconditional binding, but a
    /// later unconditional one still wins over an earlier conditional.
    #[test]
    fn a_cfg_import_does_not_displace_a_live_binding() {
        // Two modules at the same depth: line 1 `m`, and the crate root for the rest.
        let lines: Vec<&str> = vec![
            "mod m {",
            "    use std::convert::From as Conv;",
            "    #[cfg(any())]",
            "    use crate::Other as Conv;",
            "}",
            "struct Other;",
            "use crate::Other as Root;",
        ];
        let scopes = line_scopes(&lines.join("\n"));
        let imports = module_imports(&scopes, &lines);
        // The module `m` keeps `Conv` bound to the standard trait: the disabled
        // conditional did not overwrite the live unconditional binding.
        let m = &imports[1];
        assert_eq!(m.get("Conv"), Some(&"std::convert::From".to_string()));
        // The crate-root `Root` import is read as usual.
        assert_eq!(imports[6].get("Root"), Some(&"crate::Other".to_string()));
    }

    /// A conditional binding that is the *only* one still binds, and a later
    /// unconditional binding replaces an earlier conditional one.
    #[test]
    fn a_conditional_binding_is_held_below_an_unconditional_one() {
        let lines: Vec<&str> = vec![
            "mod m {",
            "    #[cfg(all())] use std::convert::From as Conv;",
            "    pub struct Local;",
            "}",
        ];
        let scopes = line_scopes(&lines.join("\n"));
        let imports = module_imports(&scopes, &lines);
        // Only a conditional binding: it is applied, so the impl it names resolves.
        assert_eq!(imports[1].get("Conv"), Some(&"std::convert::From".to_string()));

        let lines: Vec<&str> = vec![
            "mod m {",
            "    #[cfg(any())] use crate::Other as Conv;",
            "    use std::convert::From as Conv;",
            "}",
        ];
        let scopes = line_scopes(&lines.join("\n"));
        let imports = module_imports(&scopes, &lines);
        // The unconditional binding comes later and replaces the conditional one.
        assert_eq!(imports[1].get("Conv"), Some(&"std::convert::From".to_string()));
    }

    /// `is_cfg_use` reads a `#[cfg]` that spans lines, and does not read an
    /// attribute belonging to a different item.
    #[test]
    fn a_multiline_cfg_attribute_is_seen_above_a_use() {
        // A one-line `#[cfg]` above the `use` is seen (the pre-existing case).
        let lines: Vec<&str> = vec!["#[cfg(any())]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 1));

        // A `#[cfg]` that wraps: the line above the `use` is its closing `)]`, so a
        // one-line look misses it. The whole attribute must be read.
        let lines: Vec<&str> = vec![
            "#[cfg(all(",
            "    any(),",
            "))]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 3), "a multi-line cfg must still be seen");

        // A non-`cfg` attribute above the `use` is not a condition.
        let lines: Vec<&str> = vec!["#[allow(unused)]", "use a::B as C;"];
        assert!(!is_cfg_use(&lines, 1));

        // A non-attribute line (an earlier item's text) ends the block: the `#[cfg]`
        // above it belongs to that item, not to this `use`.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "struct X;", "use a::B as C;"];
        assert!(!is_cfg_use(&lines, 2), "a non-attribute line ends the attribute block");

        // A blank line also ends the block.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "", "use a::B as C;"];
        assert!(!is_cfg_use(&lines, 2), "a blank line ends the attribute block");

        // Two attributes, the `cfg` second, the first spanning a line: both belong to
        // the `use`, so the condition is seen.
        let lines: Vec<&str> = vec![
            "#[allow(",
            "    unused,",
            ")]",
            "#[cfg(any())]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 4), "a cfg below another attribute is still this item's");
    }

    /// A delimiter inside a quoted string or char literal is not a delimiter.
    ///
    /// `#[doc = "("]` carries an unmatched `(` in a string. Counting it as a delimiter
    /// makes the reader run past the attribute's real end, so a `#[cfg]` above it is
    /// not read and a *disabled* import looks live -- the alias it displaces is the
    /// lost proof this reader prevents. The reader must skip string and character
    /// literal contents (honouring escapes) while matching `#[…]`.
    #[test]
    fn a_delimiter_inside_a_quoted_attribute_is_not_a_delimiter() {
        // A `#[cfg]` followed by a `#[doc = "("]`: the `(` is in a string, so the
        // attribute run still ends at the `]` and the condition is read.
        let lines: Vec<&str> = vec![
            "#[cfg(any())]",
            "#[doc = \"(\"]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 2), "an unmatched `(` in a string must not hide the cfg");

        // The same with the bracket characters that would otherwise close the run.
        let lines: Vec<&str> = vec![
            "#[cfg(any())]",
            "#[doc = \"]\"]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 2), "a `]` in a string must not close the attribute early");

        // An escaped quote does not end the string, so the `(` after it is still text.
        let lines: Vec<&str> = vec![
            "#[cfg(any())]",
            "#[doc = \"\\\"(\"]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 2), "an escaped quote must not end the string");

        // A char literal holding a delimiter is text too.
        let lines: Vec<&str> = vec![
            "#[cfg(any())]",
            "#[doc = ')']",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 2), "a `)` in a char literal must not close the attribute");

        // A `cfg` whose own argument is a string containing a delimiter is still a
        // condition, and the run still ends where the attribute does.
        let lines: Vec<&str> = vec![
            "#[cfg(feature = \"(\")]",
            "#[doc = \")\"]",
            "use a::B as C;",
        ];
        assert!(is_cfg_use(&lines, 2), "a quoted `(` in a cfg argument must not unbalance it");

        // A lifetime in an attribute is not an unclosed char literal: it must not make
        // the run unreadable, so the non-`cfg` case stays `false` and does not panic.
        let lines: Vec<&str> = vec!["#[allow('a)]", "use a::B as C;"];
        assert!(!is_cfg_use(&lines, 1), "a lifetime must not open a char literal");
    }

    /// A raw string's contents are opaque: a `\` does not escape, so the `"` that
    /// follows it still closes the string.
    ///
    /// `r"\"` is the two bytes `\` and `"`; the `"` ends the literal. Read as an
    /// ordinary string, the `\` would escape it, the literal would swallow the rest
    /// of the line, and the `#[cfg]` above would go unread -- a disabled import
    /// would then displace a live alias, the lost proof this reader prevents. The
    /// raw-string form carries an optional `b`/`c` prefix and any number of `#`
    /// delimiters.
    #[test]
    fn a_raw_string_attribute_is_read_opaque() {
        // The reported shape: a raw string whose last character is a backslash.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r\"\\\"]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a trailing backslash in a raw string must not hide the cfg");

        // A `#`-delimited raw string, whose contents may hold a bare `"`.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r#\"a \" b\"#]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a raw string with hashes must be read whole");

        // A byte raw string, with the `b` prefix.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = br\"(\"]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a byte raw string must be read whole");

        // A raw string holding a delimiter that would otherwise unbalance the run.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r\")\"]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a `)` inside a raw string must not close the attribute");
    }

    /// A comment is not code: a quote inside one does not open a string, and a
    /// bracket inside one does not close the attribute.
    ///
    /// Rust discards comments before parsing attributes, so a `"` in a comment is
    /// not a string and a `]` in one is not the close. Counting them makes the
    /// reader miss the attribute's real end and lose a following `#[cfg]` -- a
    /// disabled import would displace a live alias, the lost proof this reader
    /// prevents.
    #[test]
    fn a_comment_inside_an_attribute_is_not_code() {
        // A line comment with a quote, inside a multi-line `cfg`.
        let lines: Vec<&str> = vec!["#[cfg(any( // \" note", "))]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a quote in a line comment must not open a string");

        // A line comment with a closing bracket.
        let lines: Vec<&str> = vec!["#[cfg(any() // ]", ")]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a `]` in a line comment must not close the attribute");

        // A block comment with a quote, on one line.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = /* \" */ \"x\"]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 2), "a quote in a block comment must not open a string");

        // A block comment spanning lines.
        let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = /* \"", "*/ \"x\"]", "use a::B as C;"];
        assert!(is_cfg_use(&lines, 3), "a multi-line block comment must be skipped whole");
    }

    /// A quoted attribute on the `use`'s own line does not hide the `use`.
    ///
    /// [`split_leading_attrs`] peels leading attributes to reach the `use` behind
    /// them. A `(` inside a string in the attribute is not a delimiter, so counting
    /// it runs the attribute past its real end and the `use` is never found -- the
    /// import is lost. The same scanner [`read_attr_run`] uses is applied here.
    #[test]
    fn a_quoted_attribute_on_the_use_line_does_not_hide_it() {
        // A same-line doc attribute with an unmatched `(` in a string.
        assert_eq!(
            split_leading_attrs("#[doc = \"(\"] use a::B;"),
            ("use a::B;", false)
        );
        assert!(is_use_start("#[doc = \"(\"] use a::B;"));

        // The same with a raw string and a trailing backslash.
        assert_eq!(
            split_leading_attrs("#[doc = r\"\\\"] use a::B;"),
            ("use a::B;", false)
        );

        // A `cfg` attribute before a quoted one is still seen, and the `use` found.
        assert_eq!(
            split_leading_attrs("#[cfg(any())] #[doc = \")\"] use a::B;"),
            ("use a::B;", true)
        );
    }

    /// A comment between two tokens separates them; deleting it joins them.
    ///
    /// `ret == n/**/as/**/u8` is the cast `n as u8` in Rust, because a comment is a
    /// token separator. The block reader skipped comments whole, so the clause came
    /// out as `ret == nasu8` -- an identifier nobody wrote. A function that also
    /// takes an argument named `nasu8` then *verified* that postcondition, which is
    /// the false-proof direction: the source says the result is `n as u8`, and the
    /// tool checked it against a different variable.
    ///
    /// The line-comment case is pinned too, since it shares the fix, and a comment
    /// at the *start* of a clause must not make the clause look non-empty.
    #[test]
    fn a_comment_separates_tokens_rather_than_joining_them() {
        use super::split_clauses;
        let cases = [
            ("ensures: ret == n/**/as/**/u8", vec!["ensures: ret == n as u8"]),
            ("ensures: ret == n/*c*/+/*c*/1", vec!["ensures: ret == n + 1"]),
            // A line comment ends at the newline, which stays as the separator, so
            // the clause continues on the next line instead of joining `n` to `+`.
            (
                "ensures: ret == n // trailing\n  + 1",
                vec!["ensures: ret == n \n  + 1"],
            ),
            // Two clauses split on the comma even when a comment sits on it.
            (
                "requires: n/*c*/> 0, ensures: ret == n",
                vec!["requires: n > 0", "ensures: ret == n"],
            ),
            // A leading comment must not make an otherwise empty clause non-empty.
            ("/*c*/", Vec::new()),
        ];
        for (text, want) in cases {
            let (got, _) = split_clauses(text, &vec![0usize; text.len()]);
            let got: Vec<&str> = got.iter().map(|(_, t)| t.as_str()).collect();
            assert_eq!(got, want, "clause split of {text:?}");
        }
    }

    /// A comment *before* the colon is whitespace, and Rust's matcher allows it.
    ///
    /// The matcher is `$($clause:ident : $body:expr,)*`, so `requires/**/: true` is a
    /// precondition. The separator fix turns the comment into a space, giving
    /// `requires : true`, and `take_clause` matched the literal `requires:` -- so the
    /// clause was refused as unknown and the function was *skipped*, a lost proof on
    /// valid syntax. Every supported keyword is checked, because the split is shared
    /// and a fix for one is a fix for all.
    #[test]
    fn a_comment_before_the_colon_does_not_drop_the_clause() {
        use super::{extract, split_clauses};
        for (text, want) in [
            ("requires/**/: true", "requires : true"),
            ("ensures/**/: ret == n", "ensures : ret == n"),
            ("invariant/**/: i <= n", "invariant : i <= n"),
            ("decreases/**/: n", "decreases : n"),
            ("variant/**/: n - i", "variant : n - i"),
            ("unwind/**/: 4", "unwind : 4"),
        ] {
            let (got, _) = split_clauses(text, &vec![0usize; text.len()]);
            assert_eq!(got.first().map(|(_, t)| t.as_str()), Some(want), "split of {text:?}");
        }
        // End to end: a block whose clauses carry a comment before the colon is read,
        // not refused. A `spec!` block with an unknown clause would be reported, so
        // the absence of `unknown` is the evidence the keywords were recognised.
        let src = "spec! {\n    requires/**/: n > 0,\n    ensures/**/: ret == n,\n}\npub fn f(n: u8) -> u8 { n }\n";
        let specs = extract(src);
        let c = specs.by_fn.get("f").expect("f must carry a contract");
        assert!(c.unknown.is_empty(), "no clause should be unknown: {:?}", c.unknown);
        assert_eq!(c.requires, vec!["n > 0".to_string()]);
        assert_eq!(c.ensures, vec!["ret == n".to_string()]);
        // The loop clauses take the same path, and each has its own arm in
        // `take_clause`; a fix that split only the first four would leave a loop
        // contract dropped. `unwind` parses its body as an integer, so a comment
        // before its colon also exercises the split-then-parse order.
        let loop_src = "spec! {\n    invariant/**/: i <= n,\n    variant/**/: n - i,\n    unwind/**/: 4,\n}\npub fn g(n: u8) -> u8 { let mut i = 0u8; while i < n { i += 1; } i }\n";
        let lspecs = extract(loop_src);
        let lc = lspecs.by_fn.get("g").expect("g must carry a contract");
        assert!(lc.unknown.is_empty(), "no loop clause should be unknown: {:?}", lc.unknown);
        assert_eq!(lc.invariants, vec!["i <= n".to_string()]);
        assert_eq!(lc.variant, Some("n - i".to_string()));
        assert_eq!(lc.unwind, Some(4));
    }

    /// A non-ASCII identifier is read as the character that was written.
    ///
    /// `split_clauses` walks bytes, and `byte as char` reads one byte as Latin-1, so
    /// `µ` (0xC2 0xB5) became `µ` -- a *different* identifier. A contract naming `µ`
    /// was therefore checked against a variable nobody declared, and a function with
    /// an argument of the mangled spelling verified it. Rust accepts non-ASCII
    /// identifiers, so this is a shape a real crate can write.
    #[test]
    fn a_non_ascii_identifier_is_not_mangled() {
        use super::split_clauses;
        for (text, want) in [
            ("ensures: ret == µ", "ensures: ret == µ"),
            ("requires: 日本 > 0", "requires: 日本 > 0"),
            // A multi-byte character next to a comment and a comma: the separator
            // fix and the decode must not interfere.
            ("requires: µ/*c*/> 0, ensures: ret == µ", "requires: µ > 0"),
        ] {
            let (got, _) = split_clauses(text, &vec![0usize; text.len()]);
            assert_eq!(got.first().map(|(_, t)| t.as_str()), Some(want), "clause of {text:?}");
        }
    }
}