File: rewrite.lisp

package info (click to toggle)
acl2 8.6%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 1,111,420 kB
  • sloc: lisp: 17,818,294; java: 125,359; python: 28,122; javascript: 23,458; cpp: 18,851; ansic: 11,569; perl: 7,678; xml: 5,591; sh: 3,976; makefile: 3,833; ruby: 2,633; yacc: 1,126; ml: 763; awk: 295; csh: 233; lex: 197; php: 178; tcl: 49; asm: 23; haskell: 17
file content (23391 lines) | stat: -rw-r--r-- 1,067,740 bytes parent folder | download | duplicates (2)
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
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
; ACL2 Version 8.6 -- A Computational Logic for Applicative Common Lisp
; Copyright (C) 2025, Regents of the University of Texas

; This version of ACL2 is a descendent of ACL2 Version 1.9, Copyright
; (C) 1997 Computational Logic, Inc.  See the documentation topic NOTE-2-0.

; This program is free software; you can redistribute it and/or modify
; it under the terms of the LICENSE file distributed with ACL2.

; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; LICENSE for more details.

; Written by:  Matt Kaufmann               and J Strother Moore
; email:       Kaufmann@cs.utexas.edu      and Moore@cs.utexas.edu
; Department of Computer Science
; University of Texas at Austin
; Austin, TX 78712 U.S.A.

(in-package "ACL2")

; We introduce ev-fncall+ early in this file to support its use in the
; definition of scons-term.

; Essay on Evaluation of Apply$ and Loop$ Calls During Proofs

; (Note: This essay also applies similarly to badge, even though we do not
; discuss badge in it.)

; A goal from the earliest days of ACL2 has been efficient evaluation, not only
; for forms submitted at the top-level loop, but also during proofs.  The
; earliest implementations of apply$, badge, and loop$ limited their evaluation
; during proofs, essentially disallowing apply$ or badge for user-defined
; functions.  This is not particularly unreasonable since attachments are
; disallowed during proofs, which is completely appropriate.

; This situation has been remedied starting in March, 2019, by expanding the
; use in the rewriter of doppelganger-apply$-userfn and
; doppelganger-badge-userfn, for calls of apply$-userfn and badge-userfn on
; concrete arguments, where the first argument has a warrant.  If the warrant
; is not known to be true in the current context, then it is forced (unless it
; is known to be false).  See community book
; books/system/tests/apply-in-proofs.lisp for examples.

; The key idea is that the truth of the warrant for fn justifies replacement of
; (apply$ 'fn '(arg1 ... argk)) by (fn arg1 ... argk); let's call this a
; "warranted replacement".  A version of ev-fncall, ev-fncall+, records the
; warrants that are required to be true in order to make those warranted
; replacements during evaluation.  Ev-fncall+ is actually a small wrapper for
; ev-fncall+-w, which in turn has a raw Lisp implementation that relies on a
; Lisp global, *warrant-reqs*.  The definition of *warrant-reqs* has a comment
; explaining its legal values, and a search of the sources for *warrant-reqs*
; should make reasonably clear how this variable is used; but here is a
; summary.  When *warrant-reqs* has its global value of nil, no special
; behavior occurs: ev-fncall+[-w] essentially reduces to ev-fncall[-w].
; Otherwise, *warrant-reqs* can be initialized to t to represent the empty
; list, and this "list" is extended by maybe-extend-warrant-reqs each time a
; new function requires a true warrant because of a warranted replacement (as
; described above).  Upon completion of a ground evaluation using ev-fncall+,
; this list of functions is returned as the third value of ev-fncall+.  The
; function push-warrants then processes this list of functions as follows: for
; the warrant of each function in that list, either the warrant is known to be
; true or it is forced (except that if it the warrant is known to be false, the
; evaluation is considered to have failed).

; Note that *aokp* must be true for the apply$-lambda and loop$ shortcuts.  So
; for the rewriter as described above, where *aokp* is nil but *warrant-reqs*
; is non-nil, evaluation involving apply$ or loop$ always reduces to evaluation
; of apply$-userfn, which is handled with warranted replacements as described
; above.  At one time we considered allowing these shortcuts for lambdas and
; loop$ forms, and we could reconsider if we want more efficiency.  But the
; current implementation seems to provide sufficient efficiency (until someone
; complains, at least), and has the following advantage: the function symbols
; stored in *warrant-reqs* are exactly those for which warranted replacement is
; used; but if we allow shortcuts for lambdas and loop$ forms, then we will
; need to include all user-defined functions occurring in the lambda body or
; loop$ body even when lying on an IF branch that was not taken during a given
; evaluation.

; We considered handling evaluation in expand-abbreviations as described above
; for the rewriter.  However, there is no type-alist readily available in
; expand-abbreviations for determining which warrants are known to be true.
; Moreover, the rules justifying warranted replacements (with names like
; apply$-fn) are conditional rewrite rules, which we traditionally ignore
; during preprocess-clause (and hence during expand-abbreviations) in favor of
; considering only "simple" rules.  However, we do use ev-fncall+ in
; expand-abbreviations, so that we can avoid wrapping HIDE around the ground
; function application when the evaluation aborted rather than doing a
; warranted replacement.  This case is represented by the case that the third
; value of ev-fncall+[-w] is a function symbol.  Special handling is important
; for this case, to avoid wrapping the call in HIDE, since that would prevent
; the rewriter from later performing a successful evaluation using warranted
; replacements.  Note that we initialize *warrant-reqs* to :nil! in this case
; instead of t, which causes evaluation to abort immediately the first time
; that a warranted replacement is called for.  For very long loops this
; obviously can be important for efficiency!

; We considered also using ev-fncall+ for eval-ground-subexpressions, but that
; seemed to introduce more complexity than it's worth; this could change based
; on user demand.  Since eval-ground-subexpressions does not introduce HIDE, we
; don't have the need for ev-fncall+ that is described above for
; expand-abbreviations.

; Note that our scheme works nicely with the executable-counterpart of apply$
; disabled.  Specifically, all warranted replacements are justified by warrants
; -- actually by rules with names like apply$-fn -- rather than by the
; execution of apply$ calls.

; Next we develop the logical and raw Lisp definitions of ev-fncall+.

(defun warranted-fns-of-world1 (x wrld)

; X is the :badge-userfn-structure of the badge-table.  It is always a
; true-list of elements made by make-badge-userfn-structure-tuple containing a
; fn symbol in the car and a warrantp and badge elsewhere.  We collect each fn
; whose warrantp is non-nil.

; However we must do this in guard-verified manner because the function is used
; in the partial-encapsulate of ev-fncall+-fns.  Since we know x will always be
; of the right shape, it doesn't matter what we do when the shape is wrong, as
; long as we return a list of function symbols.  But we have to check.

  (declare (xargs :mode :logic :guard (plist-worldp wrld)))
  (cond ((atom x) nil)
        ((and (weak-badge-userfn-structure-tuplep (car x))
              (access-badge-userfn-structure-tuple-warrantp (car x))
              (symbolp (car (car x)))
              (function-symbolp (car (car x)) wrld))
         (cons (car (car x))
               (warranted-fns-of-world1 (cdr x) wrld)))
        (t nil)))

(defun warranted-fns-of-world (wrld)

; We return the list of all warranted functions in wrld, but in a way that can
; be guard-verified and can be proved to return a list of function symbols that
; is a subset of the warranted functions of wrld.  The guard verification comes
; later during initialization (in boot-strap-pass-2-a.lisp).

  (declare (xargs :mode :logic
                  :guard (plist-worldp wrld)
                  :verify-guards nil))
  (and (alistp (table-alist 'badge-table wrld))
       (warranted-fns-of-world1
        (cdr (assoc-eq :badge-userfn-structure
                       (table-alist 'badge-table wrld)))
        wrld)))

(partial-encapsulate

; See the Essay on Evaluation of Apply$ and Loop$ Calls During Proofs.

; We think of (ev-fncall+-fns fn args wrld big-n safe-mode gc-off nil) as the
; list of badged functions supplied to apply$-userfn or badge-userfn during
; evaluation of the call of fn on args in wrld using the given
; user-stobj-alist, big-n, safe-mode, and gc-off.  But if the last argument,
; strictp, is non-nil, then we think of the result as the first function symbol
; encountered during evaluation, if any, for which a true warrant was required
; to complete that call of fn.

; The constraint below can almost surely be explicitly strengthened, but we see
; no need at this point.

; Also see ev-fncall+-w.

 (((ev-fncall+-fns * * * * * * *) => *))
 nil

 (logic)

 (local (defun ev-fncall+-fns (fn args wrld big-n safe-mode gc-off strictp)
          (declare (ignore fn args big-n safe-mode gc-off))
          (and (not strictp)
               (warranted-fns-of-world wrld))))

 (local
  (defthm all-function-symbolps-ev-fncall+-fns-lemma
    (all-function-symbolps (warranted-fns-of-world1 x wrld) wrld)))

 (defthm all-function-symbolps-ev-fncall+-fns
   (let ((fns (ev-fncall+-fns fn args wrld big-n safe-mode gc-off nil)))
     (all-function-symbolps fns wrld)))

 (local
  (defthm subsetp-equal-cons
    (implies (subsetp-equal x y)
             (subsetp-equal x (cons a y)))))

 (local
  (defthm subsetp-equal-x-x
    (subsetp-equal x x)))

 (defthm ev-fncall+-fns-is-subset-of-badged-fns-of-world
   (subsetp (ev-fncall+-fns fn args wrld big-n safe-mode gc-off nil)
            (warranted-fns-of-world wrld)))

 (defthm function-symbolp-ev-fncall+-fns-strictp
   (let ((fn (ev-fncall+-fns fn args wrld big-n safe-mode gc-off t)))
     (and (symbolp fn)
          (or (null fn)
              (function-symbolp fn wrld))))
   :rule-classes nil))

#+acl2-loop-only
(defun ev-fncall+-w (fn args w safe-mode gc-off strictp)

; See the Essay on Evaluation of Apply$ and Loop$ Calls During Proofs.

; This function allows apply$-userfn and badge-userfn to execute on warranted
; functions even when *aokp* is nil.  It returns an error triple whose
; non-erroneous value is a list of the functions that need warrants in order to
; trust the result.  However, in the case of an error when strictp is true, the
; value is a function symbol responsible for the error when a warrant is
; required so that evaluation is aborted, else nil.  Its implementation is in
; the #-acl2-loop-only definition of this function; the present logical
; definition is incomplete in the sense that ev-fncall+-fns is partially
; constrained.

; This logical definition actually permits a list, computed by constrained
; function ev-fncall+-fns, that properly includes the intended list as a
; subset.  But the under-the-hood implementation of ev-fncall+-w produces
; exactly the set of functions given to apply$-userfn or badge-userfn.

  (let* ((big-n (big-n))
         (fns (ev-fncall+-fns fn args w big-n safe-mode gc-off strictp)))
    (mv-let (erp val latches)
      (ev-fncall-rec-logical fn args
                             nil ; irrelevant arg-exprs (as latches is nil)
                             w
                             nil ; user-stobj-alist
                             big-n safe-mode gc-off
                             nil ; latches
                             t   ; hard-error-returns-nilp
                             nil ; aokp
                             (and (not strictp) fns))
      (declare (ignore latches))
      (mv erp val fns))))

#-acl2-loop-only
(defvar *warrant-reqs*

; See the Essay on Evaluation of Apply$ and Loop$ Calls During Proofs.

; Legal values of this variable are as follows.

; nil -   Always the global value, and always the value when *aokp* is non-nil
; t   -   Represents the empty list, enabling accumulation of function symbols
;         whose (true) warrants support evaluation
; lst   - A non-empty, duplicate-free list, which represents a set of warranted
;         function symbols whose (true) warrants support evaluation
; :nil! - Like nil, but causes evaluation to stop if a warrant is ever required
; fn  -   A function symbol for which evaluation is aborted because its warrant
;         is required (because *warrant-reqs* is :nil!)

  nil)

; The third result of ev-fncall+ is LOGICALLY constrained (in the
; partial-encapsulate in rewrite.lisp before the logic definition of
; ev-fncall+-w) to always be a subset of the functions named in the
; :badge-userfn-structure of the badge-table.  Thus, every function named in
; that third result has a warrant because :badge-userfn-structure is updated
; only by successful defwarrants.  But the COMPUTED value of the third result
; is accumulated in raw Lisp as the value of the special *warrant-reqs*.  This
; comment explains how we know *warrant-reqs* satisfies the constraint.

; The function maybe-extend-warrant-reqs is the only way we add a new element
; to *warrant-reqs*.  That function is called in doppelganger-badge-userfn and
; doppelganger-apply$-userfn.  In both contexts, maybe-extend-warrant-reqs is
; used to extend *warrant-reqs* with a function, fn, that has passed
; query-badge-userfn-structure, which does just what its name suggests: it
; inspects the :badge-userfn-structure.

#-acl2-loop-only
(defun ev-fncall+-w (fn args w safe-mode gc-off strictp)

; See comments in the logic definition of this function.

  (let ((*warrant-reqs*

; See comments in the definition of *warrant-reqs* for a discussion of the
; :nil! and t values of this global.

         (if strictp :nil! t)))
    (declare (special *warrant-reqs*)) ; just to be safe
    (mv-let (erp val latches)
      (ev-fncall-w fn args w
                   nil ; user-stobj-alist
                   safe-mode gc-off
                   t    ; hard-error-returns-nilp
                   nil) ; aok
      (declare (ignore latches))
      (mv erp
          val
          (if (member-eq *warrant-reqs* '(t nil :nil!))
              nil
            *warrant-reqs*)))))

(defun ev-fncall+ (fn args strictp state)

; See the Essay on Evaluation of Apply$ and Loop$ Calls During Proofs.
; Also see comments in the logic definition of ev-fncall+-w.

  (ev-fncall+-w fn args
                (w state)
                (f-get-global 'safe-mode state)
                (gc-off state)
                strictp))

; We start our development of the rewriter by coding one-way-unify and the
; substitution fns.

; Essay on Equivalence, Refinements, and Congruence-based Rewriting

; (Note: At the moment, the fact that fn is an equivalence relation is encoded
; merely by existence of a non-nil 'coarsenings property.  No :equivalence rune
; explaining why fn is an equivalence relation is to be found there -- though
; such a rune does exist and is indeed found among the 'congruences of fn
; itself.  We do not track the use of equivalence relations, we just use them
; anonymously.  It would be good to track them and report them.  When we do
; that, read the Note on Tracking Equivalence Runes in subst-type-alist1.)

; (Note: Some of the parenthetical remarks in this code are extremely trite
; observations -- to the ACL2 aficionado -- added when I sent this commented
; code off to friends to read.)

; We will allow the user to introduce new equivalence relations.  At the
; moment, they must be functions of two arguments only.  Parameterized
; equivalence relations, e.g., x == y (mod n), are interesting and may
; eventually be implemented.  But in the spirit of getting something done right
; and working, we start simple.

; An equivalence relation here is any two argument function that has been
; proved to be Boolean, symmetric, reflexive, and transitive.  The rule-class
; :EQUIVALENCE indicates that a given theorem establishes that equiv is an
; equivalence relation.  (In the tradition of Nqthm, the ACL2 user tells the
; system how to use a theorem when the theorem is submitted by the user.  These
; instructions are called "rule classes".  A typical "event" might therefore
; be:
; (defthm set-equal-is-an-equivalence-rel
;   (and (booleanp (set-equal x y))
;        (set-equal x x)
;        (implies (set-equal x y) (set-equal y x))
;        (implies (and (set-equal x y)
;                      (set-equal y z))
;                 (set-equal x z)))
;   :rule-classes :EQUIVALENCE)
; The rule class :EQUIVALENCE just alerts the system that this formula states
; that something is an equivalence relation.  If the formula is proved, the
; system identifies set-equal as the relation and adds to the database certain
; information that enables the processing described here.)

; The Boolean requirement is imposed for coding convenience.  In
; assume-true-false, for example, when we assume (equiv x y) true, we simply
; give it the type-set *ts-t*, rather than something complicated like its full
; type-set take away *ts-nil*.  In addition, the Boolean requirement means that
; (equiv x y) is equal to (equiv y x) (not just propositionally) and hence we
; can commute it at will.  The other three requirements are the classic ones
; for an equivalence relation.  All three are exploited.  Symmetry is used to
; justify commutativity, which currently shows up in assume-true-false when we
; put either (equiv x y) or (equiv y x) on the type-alist -- depending on
; term-order -- and rely on it to assign the value of either.  Reflexivity is
; used to eliminate (equiv x term) as a hypothesis when x does not occur in
; term or elsewhere in the clause.  Transitivity is used throughout the
; rewriting process.  These are not guaranteed to be all the places these
; properties are used!

; Note: Some thought has been given to the idea of generalizing our work to
; non-symmetric reflexive and transitive relations.  We have seen occasional
; utility for the idea of rewriting with such a monotonic relation, replacing a
; term by a stronger or more defined one.  But to implement that we feel it
; should be done in a completely independent second pass in which monotonic
; relations are considered.  Equivalence relations are of such importance that
; we did not want to risk doing them weakly just to allow this esoteric
; variant.

; Note: We explicitly check that an equivalence relation has no guard because
; we never otherwise consider their guards.  (The "guard" on an ACL2 function
; can be thought of as a "precondition" or a characterization of the domain of
; the function definition.  In Common Lisp many functions, e.g., car and cdr,
; are not defined everywhere and guards are our way of taking note of this.
; Equivalence relations have "no" guard, meaning their guard is t, i.e., they
; are defined everywhere.)

; The motivation behind equivalence relations is to allow their use as :REWRITE
; rules.  For example, after set-equal has been proved to be an equivalence
; relation and union-eq, say, has been proved to be commutative (wrt
; set-equal),

; (implies (and (symbol-listp a)
;               (true-listp a)
;               (symbol-listp b)
;               (true-listp b))
;          (set-equal (union-eq a b) (union-eq b a)))

; then we would like to be able to use the above rule as a rewrite rule to
; commute union-eq expressions.  Of course, this is only allowed in situations
; in which it is sufficient to maintain set-equality as we rewrite.  Implicit
; in this remark is the idea that the rewriter is given an equivalence relation
; to maintain as it rewrites.  This is a generalization of id/iff flag in
; Nqthm's rewriter; that flag indicates whether the rewriter is maintaining
; identity or propositional equivalence.  :CONGRUENCE lemmas, discussed later,
; inform the rewriter of the appropriate relations to maintain as it steps from
; (fn a1 ... an) to the ai.  But given a relation to maintain and a term to
; rewrite, the rewriter looks at all the :REWRITE rules available and applies
; those that maintain the given relation.

; For example, suppose the rewriter is working on (memb x (union-eq b a)),
; where memb is a function that returns t or nil according to whether its first
; argument is an element of its second.  Suppose the rewriter is to maintain
; identity during this rewrite, i.e., it is to maintain the equivalence
; relation equal.  Suppose a :CONGRUENCE rule informs us that equal can be
; preserved on memb expressions by maintaining set-equal on the second
; argument.  Then when rewriting the second argument to the memb, rewrite
; shifts from maintaining equal to maintaining set-equal.  This enables it to
; use the above theorem as a rewrite rule, replacing (union-eq b a) by
; (union-eq a b), just as Nqthm would had the connecting relation been equal
; instead of set-equal.

; This raises the problem of refinements.  For example, we may have some rules
; about union-eq that are expressed with equal rather than set-equal.  For
; example, the definition of union-eq is an equality!  It is clear that a rule
; may be tried if its connecting equivalence relation is a refinement of the
; one we wish to maintain.  By ``equiv1 is a refinement of equiv2'' we mean

; (implies (equiv1 x y) (equiv2 x y)).

; Such rules are called :REFINEMENT rules and are a distinguished rule-class,
; named :REFINEMENT.  Every equivalence relation is a refinement of itself.
; Equal is a refinement of every equivalence relation and no other relation is
; a refinement of equal.

; Every equivalence relation, fn, has a non-nil value for the property
; 'coarsenings.  The value of the property is a list of all equivalence
; relations (including fn itself) known to admit fn as a refinement.  This list
; is always closed under the transitivity of refinement.  That is, if e1 is a
; refinement of e2 and e2 is a refinement of e3, then the 'coarsenings for e1
; includes e1 (itself), e2 (of course), and e3 (surprise!).  This makes it
; easier to answer quickly the question of who is a refinement of whom.

; Equivalence relations are the only symbols with non-nil 'coarsenings
; properties, thus this is the way they are recognized.  Furthermore, the
; 'coarsenings property of 'equal will always list all known equivalence
; relations.

; When we are rewriting to maintain equiv we use any rule that is a known
; refinement of equiv.  Thus, while rewriting to maintain set-equal we can use
; both set-equal rules and equal rules.

; Now we move on to the heart of the matter: knowing what relation to maintain
; at each step.  This is where :CONGRUENCE rules come in.

; To understand the key idea in congruence-based rewriting, consider lemmas of
; the form

; (implies (equiv1 x y)
;          (equiv2 (fn a1 ... x ... an)
;                  (fn a1 ... y ... an))),

; where equiv1 and equiv2 are equivalence relations, the ai, x, and y are
; distinct variables and x and y occur in the kth argument position of the
; n-ary function fn.  These lemmas can be used to rewrite fn-expressions,
; maintaining equiv2, by rewriting the kth argument position maintaining
; equiv1.  In the separate Essay on Patterned Congruences and Equivalences we
; generalize to what we call "patterned congruence rules", but in this Essay we
; focus only on lemmas of the form above.

; We call such a lemma a ``congruence lemma'' and say that it establishes that
; ``equiv2 is maintained by equiv1 in the kth argument of fn.''  The rule-class
; :CONGRUENCE indicates when a lemma is to be so used.

; An example :CONGRUENCE lemma is

; (implies (set-equal a b) (iff (member x a) (member x b))).

; (In my previous example I used memb.  Here I use member, the Common Lisp
; function.  When member succeeds, it returns the tail of its second arg that
; starts with its first.  Thus, (member x a) is not necessary equal to (member
; x b), even when a and b are set-equal.  But they are propositionally
; equivalent, i.e., mutually nil or non-nil.  Iff is just another equivalence
; relation.)

; That is, iff is maintained by set-equal in the second argument of member.
; Thus, when rewriting a member expression while trying to maintain iff it is
; sufficient merely to maintain set-equivalence on the second argument of
; member.  In general we will sweep across the arguments of a function
; maintaining an appropriate equivalence relation for each argument as a
; function of the relation we wish to maintain outside.

; A literal interpretation of the lemma above suggests that one must maintain
; identity on the first argument of member in order to rely on the lemma in the
; second argument.  What then justifies our independent use of :CONGRUENCE
; lemmas in distinct argument positions?

; Congruence Theorem 1.  :CONGRUENCE lemmas for different argument positions of
; the same function can be used independently.  In particular, suppose equiv is
; maintained by e1 in the kth argument of fn and equiv is maintained by e2 in
; the jth argument of fn, where j is not k.  Suppose a is e1 to a' and b is e2
; to b'.  Then (fn ...a...b...) is equiv to (fn ...a'...b'...), where a and b
; occur in the kth and jth arguments, respectively.

; Proof.  By the :CONGRUENCE lemma for equiv and e1 we know that (fn
; ...a...b...) is equiv (fn ...a'...b...).  By the :CONGRUENCE lemma for equiv
; and e2 we know that (fn ...a'...b...) is equiv to (fn ...a'...b'...).  The
; desired result is then obtained via the transitivity of equiv.  Q.E.D.

; Again, we are not considering patterned congruences in the present Essay.
; For the proof above it is important that in the :CONGRUENCE lemma, each
; argument of a call of fn is a distinct variable.

; While we require the user to formulate (non-patterned) :CONGRUENCE lemmas as
; shown above we actually store them in a data structure, called the
; 'congruences property of fn, in which lemmas for different slots have been
; combined.  Indeed, we ``generalize'' still further and allow for more than
; one way to rewrite a given argument position.  If fn has arity n, then the
; 'congruences property of fn is a list of tuples, each of which is of the form
; (equiv slot1 slot2 ... slotn), where equiv is some equivalence relation and
; each slotk summarizes our knowledge of what is allowed in each argument slot
; of fn while maintaining equiv.  The entire n+1 tuple is assembled from many
; different :CONGRUENCE lemmas.  Indeed, it is modified each time a new
; :CONGRUENCE lemma is proved about fn and equiv.  Without discussing yet the
; structure of slotk, such a tuple means:

; (implies (and (or (equiv1.1 x1 y1)
;                   ...
;                   (equiv1.i x1 y1))
;               ...
;               (or (equivn.1 xn yn)
;                   ...
;                   (equivn.j xn yn)))
;          (equiv (fn x1 ... xn)
;                 (fn y1 ... yn))).

; Thus, to rewrite (fn x1 ... xn) maintaining equiv we sweep across the
; arguments rewriting each in turn, maintaining any one of the corresponding
; equivk.l's, which are encoded in the structure of slotk.

; Note that each equivk,l above is attributable to one and only one :CONGRUENCE
; lemma.  Since the ors cause searching, we allow the user to control the
; search by disabling :CONGRUENCE lemmas.  We only pursue paths introduced by
; enabled lemmas.

; The structure of slotk is a list of ``congruence-rules'', which are instances
; of the following record.

(defrec congruence-rule (nume equiv . rune) t)

; The :equiv field is the function symbol of an equivalence relation which, if
; maintained in argument k, is sufficient to maintain equiv for the
; fn-expression; :rune (it stands for "rule name") is the name of the
; :CONGRUENCE lemma that established this link between equiv, :equiv, fn, and
; k; and :nume is the nume of the rune (a "nume" is a unique natural number
; corresponding to a rune, used only to speed up the answer to the question:
; "is the named rule enabled -- i.e., among those the user permits us to apply
; automatically?"), allowing us to query the enabled structure directly.

; Because we allow more than one :CONGRUENCE rule per argument, we have a
; problem.  If we are trying to maintain equiv for fn and are rewriting an
; argument whose slot contains (equivk.1 ... equivk.l), what equivalence
; relation do we try to maintain while rewriting the argument?  We could
; iteratively try them each, rewriting the argument l times.  This suffers
; because some rules would be tried many times due to our use of refinements.
; For example, all of the equality rules would be tried for each equivk.i
; tried.

; It is desirable to eliminate the need for more than one pass through rewrite.
; We would like to rewrite once.  But if we pass the whole set in, with the
; understanding that any refinement of any of them can be used, we are not
; assured that the result of rewrite is equivalent in any of those senses to
; the input.  The reason is that rewrite may recursively rewrite its
; intermediate answer.  (If our rewriter simplifies a to a' it may then rewrite
; a' to a''.)  Thus, a may rewrite to a' maintaining equivk.1 and then a' may
; rewrite to a'' maintaining equivk.2 and it may be that a is not equivalent to
; a'' in either the equivk.1 or equivk.2 sense.  However, note that there
; exists an equivalence relation of which equivk.1 and equivk.2 are
; refinements, and that is the relation being maintained.  Call that the
; ``generated relation.''  Numerous questions arise.  Is the generated relation
; definable in the logic, for if so, perhaps we could allow only one
; equivalence relation per slot per fn and equiv and force the user to invent
; the necessary generalization of the several relations he wants to use.
; Furthermore, if both equivk.1 and equivk.2 maintain equiv in the kth slot of
; fn, does their generated relation maintain it?  We need to know that the
; answer is ``yes'' if we are going to replace a by a'' (which are equivalent
; only in the generated sense) and still maintain the goal relation.

; We have taken the tack of allowing more than one :CONGRUENCE rule per slot by
; automatically (indeed, implicitly) dealing with the generated equivalence
; relations.  To justify our code, we need a variety of theorems about
; generated relations.  We state and prove those now.

; Let e1 and e2 be two binary relations.  We define the relation s ``generated
; by e1 and e2,'' denoted {e1 e2}, as follows.  Because order is unimportant
; below, our set notation {e1 e2} is acceptable.

; (s x y) iff there exists a finite sequence x1, x2, ..., xn such that x = x1,
; y = xn, and for all i, ((e1 xi xi+1) or (e2 xi xi+1)).  We read this as
; saying ``(s x y) iff there is a chain connecting x to y composed entirely of
; e1 and/or e2 links.''

; Congruence Theorem 2. If e1 and e2 are equivalence relations, so is {e1 e2}.

; Proof.  Let s be {e1 e2}.  Then s is reflexive, symmetric, and transitive, as
; shown below.

; Reflexive.  To show that (s x x) holds we must exhibit a sequence linking x
; to x via e1 and/or e2.  The sequence x,x suffices.

; Symmetric.  If (s x y) holds, then there exists a sequence linking x to y via
; e1 and/or e2 steps.  Let that sequence be x, x2, ..., xk, y.  By definition,
; either e1 or e2 links each pair.  Since e1 is symmetric, if a pair, xi, xj,
; is linked by e1 then the pair xj, xi is also linked by e1.  Similarly for e2.
; Thus, the sequence obtained by reversing that above, y, xk, ..., x2, x, has
; the desired property: each pair is linked by e1 or e2.  Therefore, (s y x).

; Transitive.  If (s x y) holds, then there exists a sequence linking x to y,
; say x, x2, ..., xk, y.  If (s y z) holds, there exists a sequence linking y
; to z, say, y, y1, ..., yk, z.  Consider the concatenation of those two
; sequences, x, x2, ..., xk, y, y, y1, ..., yk, z.  It links x and z and every
; pair is linked by either e1 or e2.  Thus, (s x z).

; Q.E.D.

; Thus, the relation generated by two equivalence relations is an equivalence
; relation.

; Congruence Theorem 3. If e1 and e2 are equivalence relations, they are both
; refinements of {e1 e2}.

; Proof.  Let s be {e1 e2}.  We wish to prove (implies (e1 x y) (s x y)) and
; (implies (e2 x y) (s x y)).  We consider the first goal only.  The second is
; symmetric.  But clearly, if x is linked to y by e1 then (s x y) holds, as
; witnessed by the sequence x,y.  Q.E.D.

; Congruence Theorem 4.  Let equiv, e1 and e2 be equivalence relations.
; Suppose equiv is preserved by e1 in the kth argument of fn.  Suppose equiv is
; also preserved by e2 in the kth argument of fn.  Then equiv is preserved by
; {e1 e2} in the kth argument of fn.

; Proof.  Let s be {e1 e2}.  Without loss of generality we restrict our
; attention to a function, fn, of one argument.  We have

; (implies (e1 x y) (equiv (fn x) (fn y)))
; and
; (implies (e2 x y) (equiv (fn x) (fn y)))

; We wish to prove
; (implies (s x y) (equiv (fn x) (fn y)))

; The hypothesis (s x y) establishes that there is a chain linking x to y via
; e1 and/or e2.  Let that chain be x, x2, ..., xk, y.  Since each adjacent pair
; is linked via e1 or e2, and both preserve equiv, we get that (equiv (fn x)
; (fn x2)), (equiv (fn x2) (fn x3)), ... (equiv (fn xk) (fn y)).  By the
; transitivity of equiv, therefore, (equiv (fn x) (fn y)).  Q.E.D.

; Lemma.  If e1 is preserved by e in the kth argument of fn then so is {e1 e2},
; for any relation e2.

; Proof.  We have that (e a b) implies (e1 (f ...a...) (f ...b...)).  Let s be
; {e1 e2}.  We wish to prove that (e a b) implies (s (f ...a...) (f ...b...)).
; But by Congruence Theorem 3 above, e1 is a refinement of s.  Hence, (e1 (f
; ...a...) (f ...b...))  implies (s (f ...a...) (f ...b...)).  Q.E.D.

; Congruence Theorem 5.  Let e1, ..., e4 be equivalence relations.  Then if e2
; is preserved by e1 in the kth argument of fn and e4 is preserved by e3 in the
; kth argument of fn, then {e2 e4} is preserved by {e1 e3} in the kth argument
; of fn.

; Proof.  By the above lemma, we know {e2 e4} is preserved by e1 in the kth
; argument of fn.  Similarly, {e2 e4} is preserved by e3 in the kth argument of
; fn.  Thus, the hypotheses of Theorem 4 are satisfied and we have that {e2 e4}
; is preserved by {e1 e3} in the kth argument of fn.  Q.E.D.

; We generalize the notion of the relation generated by two relations to that
; generated by n relations, {e1, e2, ..., en}.  By the above results, {e1, ...,
; en} is an equivalence relation if each ei is, each ei is a refinement of it,
; and it supports any congruence that all ei support.  We adopt the convention
; that the relation generated by {} is EQUAL and the relation denoted by {e1}
; is e1.

; In our code, generated equivalence relations are represented by lists of
; congruence-rules.  Thus, if cr1 and cr2 are two instances of the
; congruence-rule record having :equivs e1 and e2 respectively, then {e1 e2}
; can be represented by '(cr1 cr2).

; The equivalence relation to be maintained by rewrite is always represented as
; a generated equivalence relation.  In our code we follow the convention of
; always using a variant of the name ``geneqv'' for such an equivalence
; relation.  When a variable contains (or is expected to contain) the name of
; an equivalence relation rather than a :CONGRUENCE rule or geneqv, we use a
; variant of the name ``equiv'' or even ``fn''.

; The geneqv denoting EQUAL is nil.  The geneqv denoting IFF is:

(defconst *geneqv-iff*
  (list (make congruence-rule
              :rune *fake-rune-for-anonymous-enabled-rule*
              :nume nil
              :equiv 'iff)))

; This completes our general essay on the subject.  The theorems proved above
; are mentioned by name elsewhere in our code.  In addition, various details
; are discussed elsewhere.  For a simple example of how all of this works
; together, see the function subst-equiv-expr which implements substitution of
; new for old in term to produce term', where it is given that new is equiv1
; old and term is to be equiv2 term'.

; We now turn to the most primitive functions for manipulating equivalences and
; generated equivalences.  We deal with refinements first and then with the
; question of congruences.

(defun refinementp (equiv1 equiv2 wrld)

; Note: Keep this function in sync with refinementp1.

; (ACL2 is an applicative subset of Common Lisp.  When this
; function, refinementp, is called, its third argument, wrld, will be
; the current "property list world" which is just an association
; list binding symbols and property names to values.  The lookup of
; a symbol's property in wrld is via the ACL2 function getprop.
; Getprop is coded in a clever way so that in the case that the
; world is in fact that implicit in the global property list
; structure of Common Lisp, then getprop is just Common Lisp's
; non-applicative get.  In our code, wrld is always that world,
; but the code works correctly -- if somewhat more slowly -- if
; called on a different world.)

; Both equiv1 and equiv2 are function symbols.  We determine whether
; equiv1 is a known refinement of equiv2, given wrld.  If we return t
; we must be correct.  Nil means ``maybe not.''  For an explanation of
; why our database contains the 'coarsenings property instead of the
; inverse 'refinements property, see the discussion of
; geneqv-refinements below.

  (cond ((eq equiv1 'equal)

; Equal is a refinement of all equivalence relations.

         t)
        ((eq equiv2 'equal)

; No other relation is a refinement of equal.

         nil)
        ((eq equiv1 equiv2)

; Every equivalence relation is a refinement of itself.

         t)
        (t

; Otherwise, look for equiv2 among the known coarsenings of equiv1.
; The database must be kept so that the transitive property of
; refinement is manifested explicitly.  This function is called very
; often and we do not want to go searching through the transitive
; closure of refinementhood or coarseninghood.  So if e1 is a known
; refinement of e2 and e2 is a known refinement of e3, then the
; 'coarsenings property of e1 must include not just e2 but also e3.
; We know the first element in the 'coarsenings of equiv1 is equiv1
; -- which isn't equiv2 -- so we skip it.

         (member-eq equiv2
                    (cdr (getpropc equiv1 'coarsenings nil wrld))))))

; The above function determines if one equivalence symbol is a
; refinement of another.  More often we want to know whether a symbol
; is a refinement of a generated equivalence relation.  That is, is e1
; a refinement of {e2 e3}?  The most common occurrence of this
; question is when we are maintaining {e2 e3} and want to know if we
; can apply a :REWRITE rule about e1.

(defun geneqv-refinementp1 (coarsenings geneqv)

; We determine whether any name in coarsenings is the :equiv of any
; :CONGRUENCE rule in geneqv.  If so, we return the :rune of the rule
; found.

  (cond ((null geneqv) nil)
        ((member-eq (access congruence-rule (car geneqv) :equiv)
                    coarsenings)
         (access congruence-rule (car geneqv) :rune))
        (t (geneqv-refinementp1 coarsenings (cdr geneqv)))))

(defun geneqv-refinementp (equiv geneqv wrld)

; We determine whether the equivalence relation symbol equiv is a
; known refinement of the generated relation geneqv.  If so, we return
; the rune of the :CONGRUENCE rule in geneqv used, or
; *fake-rune-for-anonymous-enabled-rule* if equality was used.
; Otherwise we return nil.

; This function is used both as a function and a predicate.  Its
; primary use is as a predicate, typically to determine whether it is
; permitted to use a :REWRITE rule whose top-level equivalence is
; equiv.  If the function reports success and the rewrite in fact
; succeeds, the caller will typically use the value of the function as
; the rune of the :CONGRUENCE rule used, adding it into the tag-tree of
; the term being rewritten.

; Note: If the database contained only a 'refinements property for e2
; and e3, we would have to access both of them to determine whether e1
; was among the known refinements.  But if the database contains a
; 'coarsenings property for e1 we can access just that and then look
; for e2 or e3 in it.  This saves us doing unnecessary getprops.

; Historical Note: Once we passed around geneqvs that contained
; possibly disabled :CONGRUENCE rules and this function got, as an
; additional argument, the current enabled structure and had the job
; of ignoring those :CONGRUENCE rules.  This proved cumbersome and we
; adopted the idea of passing around geneqvs that are fully enabled.
; It means, of course, filtering out the disabled components when we
; form new geneqvs from those in the database.  In any case, this
; function does not get the enabled structure and takes no note of the
; status of any rule.

  (cond ((eq equiv 'equal) *fake-rune-for-anonymous-enabled-rule*)
        ((null geneqv) nil)
        (t (geneqv-refinementp1 (getpropc equiv 'coarsenings nil wrld)
                                geneqv))))

; We now define the function which constructs the list of generated
; equivalences to be maintained across the arguments of fn, as a
; function of the generated equivalence to be maintained overall and
; the current enabled structure.  Our main concern, technically, here
; is to avoid consing.  Most often, we expect that the list of geneqvs
; stored a given fn will be the list we are to return, because we will
; be trying to maintain just one primitive equivalence and we will
; know at most one way to do it for each arg, and none of the
; :CONGRUENCE rules are disabled.  So we start with the function that
; filters out of the geneqv stored in slot k all of the disabled
; congruences -- and we code it so as to first check to see whether
; anything needs to be removed.  Then we move up to the corresponding
; operation on a stored list of geneqvs.  Finally, we consider the
; problem of unioning together the slot k's for all of the primitive
; equivalences to be maintained.

(defun some-congruence-rule-disabledp (geneqv ens)
  (cond ((null geneqv) nil)
        ((enabled-numep (access congruence-rule (car geneqv) :nume) ens)
         (some-congruence-rule-disabledp (cdr geneqv) ens))
        (t t)))

(defun filter-geneqv1 (geneqv ens)
  (cond ((null geneqv) nil)
        ((enabled-numep (access congruence-rule (car geneqv) :nume) ens)
         (cons (car geneqv) (filter-geneqv1 (cdr geneqv) ens)))
        (t (filter-geneqv1 (cdr geneqv) ens))))

(defun filter-geneqv (geneqv ens)

; Geneqv is a set (list) of :CONGRUENCE rules, generally retrieved from
; slot k of some equiv entry on some function's 'congruences.  We
; return the subset consisting of the enabled ones.  We avoid consing
; if they are all enabled.

  (cond ((some-congruence-rule-disabledp geneqv ens)
         (filter-geneqv1 geneqv ens))
        (t geneqv)))

; Now we repeat this exercise one level higher, where we are dealing with
; a list of geneqvs.

(defun some-geneqv-disabledp (lst ens)
  (cond ((null lst) nil)
        ((some-congruence-rule-disabledp (car lst) ens) t)
        (t (some-geneqv-disabledp (cdr lst) ens))))

(defun filter-geneqv-lst1 (lst ens)
  (cond ((null lst) nil)
        (t (cons (filter-geneqv (car lst) ens)
                 (filter-geneqv-lst1 (cdr lst) ens)))))

(defun filter-geneqv-lst (lst ens)

; It is handy to allow ens to be nil, indicating that nothing is disabled.

  (cond ((null ens)
         lst)
        ((some-geneqv-disabledp lst ens)
         (filter-geneqv-lst1 lst ens))
        (t lst)))

; Next we must union together two lists of :CONGRUENCE rules.  To keep
; the lists from getting large we will eliminate refinements.  That
; is, if we have {e1 e2} U {e3 e4}, and e1 is a refinement of e3, but
; there is no refinement relation between e2, e3 and e4, then the
; answer will be {e2 e3 e4}.  In general, we will assume the two lists
; are free of internal refinement relations and we will generate such
; a list.  It is a little messy because e3 may be a refinement of e2,
; say.  In which case the answer is {e2 e4}.

(defun refinementp1 (equiv1 coarsenings1 equiv2)

; Note: Keep this function in sync with refinementp.

; Both equiv1 and equiv2 are function symbols and coarsenings1 is the
; cdr of the 'coarsenings property of equiv1 (the car of that property
; is equiv1 itself).  We determine whether equiv1 is a known
; refinement of equiv2.  This function should be kept in sync with the
; more general refinementp.

  (cond ((eq equiv1 'equal) t)
        ((eq equiv2 'equal) nil)
        ((eq equiv1 equiv2) t)
        (t (member-eq equiv2 coarsenings1))))

(defun pair-congruence-rules-with-coarsenings (geneqv wrld)

; We pair each congruence rule in geneqv with non-id coarsenings,
; i.e., the cdr of the 'coarsenings property of its :equiv.

  (cond
   ((null geneqv) nil)
   (t (cons (cons (car geneqv)
                  (cdr (getpropc (access congruence-rule (car geneqv) :equiv)
                                'coarsenings nil wrld)))
            (pair-congruence-rules-with-coarsenings (cdr geneqv) wrld)))))

(defun add-to-cr-and-coarsenings
  (new-cr new-cr-coarsenings old-crs-and-coarsenings both-tests-flg)

; New-cr is a congruence rule and new-cr-coarsenings is the
; 'coarsenings property of its :equiv.  Note that the car of
; new-cr-coarsenings is thus the :equiv name.  Old-crs-and-coarsenings
; is a list of pairs of the form (congruence-rule . non-id-coarsenings).
; We assume no member of the old list refines any other member.

; We ``add'' the new pair (new-cr . non-id-new-cr-coarsenings) to the old
; list.  However, if new-cr is a refinement of any equiv in the old
; list, we do nothing.  Furthermore, if any member of the old list is
; a refinement of new-cr, we delete that member.

  (cond
   ((null old-crs-and-coarsenings)

; Add the new-cr and its non-id coarsenings to the list.

    (list (cons new-cr (cdr new-cr-coarsenings))))
   ((and both-tests-flg
         (refinementp1
          (car new-cr-coarsenings) ; new-equiv
          (cdr new-cr-coarsenings) ; new-equiv's non-id coarsenings
          (access congruence-rule  ; first old-equiv
                  (car (car old-crs-and-coarsenings))
                  :equiv)))

; The new equiv is a refinement of the first old one.  Nothing to do.

    old-crs-and-coarsenings)
   ((refinementp1
     (access congruence-rule ; first old-equiv
             (car (car old-crs-and-coarsenings))
             :equiv)
     (cdr (car old-crs-and-coarsenings)) ; first old-equiv's non-id coarsenings
     (car new-cr-coarsenings))           ; new-equiv

; The first old equiv is a refinement of the new one.  Delete the old
; one.  Continue inserting the new one -- it may cause other
; refinements to be deleted.  But there is no possibility that it will
; be dropped because any old cr which it refines would have been
; refined by the one we just dropped.  So we can henceforth only test for
; this case.

    (add-to-cr-and-coarsenings new-cr new-cr-coarsenings
                               (cdr old-crs-and-coarsenings)
                               nil))
   (t (cons (car old-crs-and-coarsenings)
            (add-to-cr-and-coarsenings new-cr new-cr-coarsenings
                                       (cdr old-crs-and-coarsenings)
                                       both-tests-flg)))))

(defun union-geneqv1 (geneqv1 old-crs-and-coarsenings wrld)

; Geneqv1 is a geneqv and old-crs-and-coarsenings is a list of pairs
; of the form (congruence-rule . coarsenings), where the coarsenings
; are the non-id coarsenings of the :equiv of the corresponding
; congruence-rule.  This data structure makes it possible to answer
; refinement questions without going back to the world.  We scan down
; geneqv1 and augment old-crs-and-coarsenings, adding a new
; (congruence-rule . non-id-coarsenings) pair for each congruence rule in
; geneqv1 that is not a refinement of any rule already in the old set.
; In addition, if we find an old rule that is a refinement of some new
; one, we drop it from the old set, replacing it with the new one.

  (cond
   ((null geneqv1) old-crs-and-coarsenings)
   (t (union-geneqv1 (cdr geneqv1)
                     (add-to-cr-and-coarsenings (car geneqv1)
                                                (getpropc
                                                 (access congruence-rule
                                                         (car geneqv1)
                                                         :equiv)
                                                 'coarsenings nil wrld)
                                                old-crs-and-coarsenings
                                                t)
                     wrld))))

(defun union-geneqv (geneqv1 geneqv2 wrld)

; We union together the congruence rules in the two geneqv's, forming
; a set with the property that no element in it is a refinement of any
; other.  Roughly speaking we simply add the equivs of geneqv1 into
; those of geneqv2, not adding any that is a refinement and deleting
; any that is refined by a new one.  To make this process faster we
; first annotate geneqv2 by pairing each congruence rule in it with
; the non-id 'coarsenings property of its :equiv.  Union-geneqv1 does the
; work and returns such an annotated list of congruence rules.  We
; convert that back into a geneqv by stripping out the annotations.

  (strip-cars
   (union-geneqv1
    geneqv1
    (pair-congruence-rules-with-coarsenings geneqv2 wrld)
    wrld)))

; And now we do slotwise union.

(defun pairwise-union-geneqv (lst1 lst2 wrld)

; Lst1 and lst2 are lists of geneqvs that are in 1:1 correspondence.
; We pairwise union their elements.

  (cond ((null lst1) nil)
        (t (cons (union-geneqv (car lst1) (car lst2) wrld)
                 (pairwise-union-geneqv (cdr lst1) (cdr lst2) wrld)))))

; That brings us to the main function we've been wanting: the one that
; determines what generated equivalence relations must be maintained
; across the arguments of fn in order to maintain a given
; generated equivalence relation for the fn-expression itself.  Because
; we form new geneqvs from stored ones in the database, we have to
; have the enabled structure so we filter out disabled congruence
; rules.

(defun geneqv-lst1 (congruences geneqv ens wrld)

; Congruences is the list of congruences of a certain function, fn.
; Geneqv is a list of congruence-rules whose :equiv relations we are
; trying to maintain as we sweep across the args of fn.  For each
; element of congruences, (equiv slot1 ... slotn), such that equiv is
; an element of geneqv we filter disabled rules out of each slot and
; then union together corresponding slots.

; In coding this, the following question arose.  ``Should we include
; those equiv that are refinements of elements of geneqv or just those
; that are literally elements of geneqv?''  Our answer is ``include
; refinements.''  Suppose geneqv is {set-equal}.  Suppose list-equal
; is a known refinement of set-equal.  Suppose that for the fn in
; question we know a :CONGRUENCE rule that preserves list-equal but we
; know no rules that preserve set-equal.  Then if we do not include
; refinements we will be fooled into thinking that the only way to
; preserve set-equal for the fn is to preserve equal across the args.
; But if we do include refinements we will know that we can admit
; whatever relations are known to maintain list-equal across the args.

  (cond ((null congruences)

; This is a little subtle.  We return nil where we ought to return a
; list of n nils.  But it is ok.  An optimization below (in which we
; avoid pairwise-union-geneqv when the second arg is nil) makes it
; clearly ok.  But even without the optimization it is ok because
; pairwise-union-geneqv is controlled by its first arg!

         nil)
        (t (let ((ans (geneqv-lst1 (cdr congruences) geneqv ens wrld)))
             (cond
              ((geneqv-refinementp (caar congruences) geneqv wrld)
               (cond
                ((null ans)
                 (filter-geneqv-lst (cdar congruences) ens))
                (t (pairwise-union-geneqv
                    (filter-geneqv-lst (cdar congruences) ens)
                    ans
                    wrld))))
              (t ans))))))

; On the Optimization of Geneqv-lst

; Once upon a time we suspected that geneqv-lst might be causing a significant
; slowdown of ACL2 compared to Nqthm.  So we tried the following experiment.
; First we ran the code on the Nqthm package and learned that geneqv-lst is
; called a total of 876843 times.  The entire series of proofs took 1654
; seconds (on Rana, a Sparc 2).  Then we recoded the function so that it saved
; every input and output and reran it on the proof of the Nqthm package to
; collect all io pairs.  Analyzing the io pairs showed that we could reproduce
; the behavior of geneqv-lst on that series of proofs with the following code.
; Note that this does does not look at the property lists nor at the enabled
; structure.  Nor does it do any consing.

;    (defun geneqv-lst (fn geneqv ens wrld)
;     (declare (ignore ens wrld))
;   ; (setq geneqv-cnt (1+ geneqv-cnt))
;     (cond
;      ((and (eq fn 'IFF)
;            (equal geneqv *geneqv-iff*))
;       '(((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))
;         ((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))))
;      ((and (eq fn 'IMPLIES)
;            (equal geneqv *geneqv-iff*))
;       '(((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))
;         ((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))))
;      ((eq fn 'IF)
;       (cond
;        ((null geneqv)
;         '(((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))
;           nil nil))
;        ((equal geneqv *geneqv-iff*)
;         '(((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))
;           ((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))
;           ((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))))
;        (t nil)))
;      ((and (eq fn 'NOT)
;            (equal geneqv *geneqv-iff*))
;       '(((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL))))
;      (t nil)))

; (Note: ((NIL IFF :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE NIL)) is just
; *geneqv-iff*.)

; Then we recompiled the entire ACL2 system with this definition in place (to
; ensure that the calls were all fast) and reran the Nqthm package proofs.  The
; result was that it took 1668 seconds!

; Not wanting to believe these results (it seems so obvious that this function
; is inefficient!) we tried redefining geneqv-lst so that it always returned
; nil.  This is not the same behavior as the geneqv-lst below, but at least it
; is fast.  The resulting proofs took 1780 seconds but investigation showed
; that some proofs followed different paths, so this experiment was discounted.

; Next, we simply remembered the complete sequence of answers generated by the
; code below (all 876843 of them) and then redefined the function to feed back
; those very answers in the same sequence.  The answers were pushed into a
; stack during one run, the stack was reversed, and the answers were popped off
; during the second run.  The code for geneqv-lst was simply (pop
; geneqv-stack).  We cannot imagine a faster implementation.  The second
; run took 1685 seconds.

; The conclusion of these experiments is that geneqv-lst is not likely to be
; optimized!

(defun geneqv-lst (fn geneqv ens wrld)

; Suppose we are attempting to rewrite a term whose function is fn while
; maintaining the generated equivalence relation geneqv.  Fn may be a lambda
; expression.  We return the list of generated equivalence relations to be
; maintained at each argument position.  See the essay above for some
; experiments on the optimization of this function.

; For example, while rewriting a MEMBER expression, (MEMBER x s) to
; maintain IFF we should rewrite x maintaining EQUAL and rewrite s
; maintaining SET-EQUAL.  That is, given MEMBER and IFF (for fn and
; geneqv) we wish to return (EQUAL SET-EQUAL), a list in 1:1
; correspondence with the formals of fn giving the equivalence
; relations that must be maintained for the arguments in order to
; maintain geneqv.  However, rather than (EQUAL SET-EQUAL) we return a
; list of two geneqvs, namely '(nil (cr)), where cr is the congruence
; rule which establishes that IFF is maintained by SET-EQUAL in the
; 2nd arg of MEMBER.

; The fact that nil denotes the equivalence generated by 'EQUAL,
; combined with the facts that the car and cdr of nil are nil, allows
; us to return nil to denote a list of a suitable number of generated
; equalities.  Thus, the answer nil is always correct and is in fact
; the answer returned for all those functions for which we know no
; :CONGRUENCE rules.

; If fn is a lambda-expression, we return nil.  Otherwise, the
; 'congruences property of the symbol fn is an alist.  The entries of
; the alist are of the form (equiv geneqv1 ... geneqvn).  Consider the
; entry for each refinement of some :equiv in the goal geneqv, after
; filtering out the disabled rules from each:

; (equiv1 geneqv1,1 ... geneqv1,n)
; (equiv2 geneqv2,1 ... geneqv2,n)
; ...
; (equivk geneqvk,1 ... geneqvk,n)

; The union down the first column is geneqv.  Let the union down
; subsequent columns be geneqv1, ... geneqvn.  Then by Congruence
; Theorem 5, we have that geneqv is maintained by geneqvi in the ith
; argument of fn.  Thus, we return (geneqv1 ... geneqvn).

; Observe that if some equivj in geneqv is not mentioned in the
; known congruences then we have, implicitly, the entry

; (equivj {} ... {}) and so its contribution to the union is
; justifiably ignored.

; Observe that if we throw away a disabled rule from a geneqvi,j we
; are just strengthening the equivalence relation to be maintained
; in that slot.  Thus, our heuristic use of ens is sound.

; We allow ens to be nil, to signify that all rules are to be considered as
; enabled.

  (cond ((flambdap fn) nil)
        ((eq fn 'if)

; IF is an unusual function symbol vis-a-vis congruence.  We know that
; equality is preserved by iff in the 1st argument of IF.  But more
; significantly, for every equivalence relation, equiv, we have that
; equiv is preserved by equiv in the 2nd and 3rd arguments of if.
; Thus, we could store a lot of congruences under IF, one for each
; equivalence relation:  (equiv iff equiv equiv).  Instead, we just
; manufacture it when we are asked.  This is inefficient in that we
; may cons up the same structure repeatedly.  But we do not suffer
; as much as one might think because the really heavy-duty users of
; geneqv-lst, e.g., rewrite, build in their handling of IF anyway and
; never call geneqv-lst on 'IF.

         (list *geneqv-iff* geneqv geneqv))
        (t (let ((congruences (getpropc fn 'congruences nil wrld)))
             (cond
              ((null congruences) nil)
              ((null geneqv)

; This is a special case.  If we are trying to maintain equality
; then the likelihood is that we have to maintain equality across
; the args, i.e., return nil.  But it is possible that the congruences
; for fn lists 'equal explicitly.  If so, we use those.  Otherwise nil.
; But we have to filter for disabled rules.

               (filter-geneqv-lst (cdr (assoc-eq 'equal congruences)) ens))
              (t

; This is the general case in which the function has some known congruence
; relations and the equivalence relation we are trying to maintain is not just
; equality.  In this case, we are prepared to do some consing.

               (geneqv-lst1 congruences geneqv ens wrld)))))))


; As an exercise in the use of the equivalence and congruence stuff, we
; now code the function that substitutes one term for another maintaining
; a given generated equivalence.  We begin with elementary substitution
; because it illustrates the fundamental notion of substitution.

; Elementary Expression Substitution (``Equals for Equals'')

; Students of our code might find it helpful to look at subst-var
; before looking at the following.

; We show how to substitute one term, new, for another term, old,
; in a term.  The presumption is that new and old are known to be
; equal.  This might be used, for example, to substitute
; A for (CAR (CONS A B)) in (FOO (CAR (CONS A B))) to produce
; (FOO A).

(mutual-recursion

(defun subst-expr1 (new old term)
  (declare (xargs :guard (and (pseudo-termp new)
                              (pseudo-termp old)
                              (pseudo-termp term))))
  (cond ((equal term old) new)
        ((variablep term) term)
        ((fquotep term) term)
        (t (cons-term (ffn-symb term)
                      (subst-expr1-lst new old (fargs term))))))

(defun subst-expr1-lst (new old args)
  (declare (xargs :guard (and (pseudo-termp new)
                              (pseudo-termp old)
                              (pseudo-term-listp args))))
  (cond ((endp args) nil)
        (t (cons (subst-expr1 new old (car args))
                 (subst-expr1-lst new old (cdr args))))))

)

(defun subst-expr-error (const)
  (declare (xargs :guard nil))
  (er hard 'subst-expr-error
      "An attempt was made to substitute for the explicit value ~x0.  ~
       The substitution functions were optimized to disallow this."
      const))

(defun subst-expr (new old term)
  (declare (xargs :guard (and (pseudo-termp new)
                              (pseudo-termp old)
                              (not (quotep old))
                              (pseudo-termp term))))
  (cond ((variablep old) (subst-var new old term))
        ((fquotep old) (subst-expr-error old))
        (t (subst-expr1 new old term))))

; Congruence-Based Substitution:

; Below we develop the function that substitutes new for old into
; term, where new is equiv to old and we are supposed to produce an
; answer that is geneqv to term.  The main reason we're developing
; this function is to solidify our ideas on congruence rewriting.

; Note: The relation between new and old is some primitive
; equivalence, i.e., equiv is a function symbol.  But the relation we
; are trying to maintain is a generated equivalence, i.e., a set of
; primitive equivs.  We could pursue the idea of generalizing equiv to
; a generated equivalence.  However, we don't, at the moment, see the
; value in that.  In the first place, this function is meant as a
; model of how rewrite should handle geneqvs and each :REWRITE rule is
; about a single primitive equivalence, not a generated equivalence.
; In the second place, everywhere this function is used, e.g., when we
; eliminate a (set-equal a b) hyp in the conjecture by substituting a
; for b, we have a primitive equiv relating the two.  Now we will need
; the generalized version of this function if we ever obtain b, say,
; by rewriting a under some generated equivalence.  The resulting a
; and b are not related by a primitive equiv.  But we will wait until
; we need that to implement it.

; Here is an example of the kind of substitution we implement.  Let
; list-equal be the equivalence relation that is element by element
; equality on lists (ignoring the final cdr).  Let set-equal be
; permutationp.  Suppose that if a is set-equal to b then (listify a)
; is list-equal to (listify b).  A model of listify is that it removes
; duplicates and sorts with some total ordering, but preserves the
; final cdr just to prevent (listify a) from being equal to (listify
; b).  Suppose further that if x is list-equal to y then (member e x)
; iff (member e y).

; Given the foregoing, we have three equivalence relations,
; list-equal, set-equal, and iff, and two congruences.

; Under the 'congruences property of listify we have the congruence
; (list-equal ((nume set-equal . rune))) which means that list-equal
; is preserved by set-equal in the first argument of listify.

; Under the 'congruences property of member we have (iff nil ((nume
; list-equal . rune))) which means that iff is preserved by list-equal
; in the second argument of member.  The nil implicitly says ``iff is
; preserved by equal in the first argument of member.''

; Now suppose we want to substitute a for b (which are known to be
; set-equal) into (member e (listify b)) maintaining iff.  Then we see
; that iff can be maintained on the member expression if we substitute
; a for b in (listify b) maintaining list-equal.  Then we see that
; list-equal can be maintained on the listify expression if we
; substitute a for b in b maintaining set-equal.  But a is set-equal
; to b.  So we get (member e (listify a)).

; Now let us refine this slightly.  What does it mean for one
; equivalence relation, e1, to be a refinement of another, e2?  It
; means that (implies (e1 a b) (e2 a b)).  That is, if a and b are
; in a refinement of e2 they are in e2.  So for example, EQUAL is a
; refinement of every equivalence relation because (implies (equal a
; b) (e2 a b)) is the same as (e2 a a), which is just reflexivity.

; So suppose a is equiv1 to b and we want to substitute a for b in b
; maintaining equiv2.  What is a sufficient condition on equiv1 and
; equiv2?  Equiv1 must be a refinement of equiv2.  That is, they must
; be ``even more alike'' than equiv2 requires, in the sense of being
; in a smaller equivalence class.

; In our actual implementation equiv2 is generalized to a generated
; equivalence relation.

(defun comment-fn (x y)

; If y is a term, then (comment-fn x y) is a term.  We take advantage of this
; fact when calling comment-fn in hide-with-comment.

  (declare (xargs :guard t))
  `(return-last 'progn '(:comment . ,x) ,y))

(defmacro comment (x y)
  (comment-fn x y))

(defstub hide-with-comment-p () t)
(defattach hide-with-comment-p constant-t-function-arity-0)

(defun hide-with-comment (reason term wrld state)

; Reason should be either nil or of one of the forms (:kwd . data) recognized
; below.

  (declare (xargs :mode :program :stobjs state))
  (cond
   ((or (null reason)
        (null (hide-with-comment-p)))
    (fcons-term* 'hide term))
   (t
    (flet ((comment-fn+
            (x y) ; X must be a string.
            (comment-fn (concatenate 'string x ";
see :DOC comment")
                        y))
           (reason-string
            (erp scons-term-p wrld state)
            (let* ((fn (and (consp erp)
                            (eq (car erp)
                                'ev-fncall-null-body-er)
                            (symbolp (cdr erp))
                            (cdr erp)))
                   (fn (if (eq fn :non-exec) 'non-exec fn)))
              (and fn
                   (let* ((non-executablep
                           (getpropc fn 'non-executablep nil wrld))
                          (skip-pkg-prefix
                           (symbol-in-current-package-p fn state))
                          (str0
                           (if scons-term-p
                               "Failed attempt (during substitution) to call "
                             "Failed attempt to call "))
                          (str1 (cond
                                 ((eq fn 'non-exec) "")
                                 (non-executablep "non-executable function ")
                                 (t "constrained function ")))
                          (str2 (cond
                                 ((or (eq fn 'non-exec)
                                      (null (attachment-pair fn wrld)))
                                  "")
                                 ((warrant-function-namep fn wrld)
                                  ":
warrant functions are not executable during proofs")
                                 (t
                                  ":
its attachment is ignored during proofs"))))
                     (if skip-pkg-prefix
                         (concatenate 'string str0 str1 (symbol-name fn) str2)
                       (concatenate 'string
                                    str0
                                    str1
                                    (symbol-package-name fn)
                                    "::"
                                    (symbol-name fn)
                                    str2)))))))
      (case-match reason
        ((:non-executable . erp)
         (let ((reason-string (reason-string erp nil wrld state)))
           (fcons-term* 'hide
                        (if reason-string
                            (comment-fn+ reason-string term)
                          term))))
        ((:scons-term . erp)
         (let ((reason-string (reason-string erp t wrld state)))
           (fcons-term* 'hide
                        (if reason-string
                            (comment-fn+ reason-string term)
                          term))))
        ((:expand rune . skip-pkg-prefix)
         (fcons-term* 'hide
                      (comment-fn+
                       (let ((name
                              (if skip-pkg-prefix
                                  (symbol-name (base-symbol rune))
                                (concatenate
                                 'string
                                 (symbol-package-name (base-symbol rune))
                                 "::"
                                 (symbol-name (base-symbol rune))))))
                         (concatenate
                          'string
                          "Unable to expand using the rule "
                          name))
                       term)))
        ((:missing-warrant . fn?)
         (fcons-term*
          'hide
          (comment-fn+
           (let* ((disabledp (consp fn?))
                  (fn (if disabledp
                          (car fn?) ; apply$-fn
                        fn?))
                  (skip-pkg-prefix (symbol-in-current-package-p fn state))
                  (fn-str (if skip-pkg-prefix
                              (symbol-name fn)
                            (concatenate
                             'string
                             (symbol-package-name fn)
                             "::"
                             (symbol-name fn)))))
             (concatenate
              'string
              "Call failed because "
              (if disabledp
                  (concatenate
                   'string
                   "the rule "
                   fn-str
                   " is disabled")
                (concatenate
                 'string
                 "the warrant for "
                 fn-str
                 " is not known to be true"))))
           term)))
        (& (er hard 'hide-with-comment
               "Unexpected reason supplied to ~x0!"
               'hide-with-comment)))))))

(defun scons-term (fn args ens wrld state ttree)

; This function is (cons-term fn args) except that we evaluate any enabled fn
; on quoted arguments and may do any other replacements that preserve equality
; (e.g., (equal x x) = t).  In addition, we report the executable counterparts
; we use by adding them to ttree.  We return (mv hitp term ttree'), where: hitp
; is t iff term is something different than (cons-term fn args); term is
; provably equal to (cons-term fn args); and ttree' is an extension of ttree
; this equality.

; Warning: If scons-term is used for other than substitution, consider changing
; hide-with-comment and its call below.  Explanation:

; The leading "s" in scons-term may have originally denoted "smart", but it
; more precisely denotes "substitution".  The call of hide-with-comment is made
; below on (cons :scons-term erp) so that hide-with-comment can report that
; evaluation was attempted on behalf of substitution; see :DOC comment.

  (cond
   ((and (all-quoteps args)
         (or (flambdap fn)
             (and (enabled-xfnp fn ens wrld)

; We don't mind disallowing constrained functions that have attachments,
; because the call of ev-fncall below disallows the use of attachments (last
; parameter, aok, is nil).

                  (not (getpropc fn 'constrainedp nil wrld)))))

; Note: This code is supposed to be the same as in rewrite.  Keep them in sync
; and see the comment there for explanations.

    (cond ((flambdap fn)

; This is a problematic case.  At first sight, we could just create the term
; (fn . args) and then evaluate it with ev.  (We can't use ev-fncall as we do
; below because it doesn't handle lambdas.)  But this ignores some problems.
; How do we avoid evaluating :program fns that occur in the body?  How do
; we avoid evaluating disabled fns in the body?  How do we report the
; executable-counterparts we use?  Problems, problems.  We punt.

           (mv nil (cons-term fn args) ttree))
          ((eq fn 'if)
           (mv t
               (if (cadr (car args))
                   (cadr args)
                   (caddr args))
               ttree))
          ((programp fn wrld)

; It is March, 2019, and we ask: Is this test needed?  At one time we said "see
; the comment in rewrite", but there seems to be no such comment in rewrite.
; Perhaps it is no longer needed, but we keep this programp case just to be
; safe.  Also, we formerly returned t as the first value in this case, but that
; seems wrong so we return nil now.

           (mv nil (cons-term fn args) ttree))
          (t
           (mv-let
            (erp val bad-fn)
            (pstk
             (ev-fncall+ fn (strip-cadrs args) t state))
            (cond
             (erp
              (cond
               (bad-fn

; Since bad-fn is non-nil, the evaluation failure was caused by aborting when a
; warrant was needed.  This case is handled in rewrite, so we do not want to
; hide the term.  See the Essay on Evaluation of Apply$ and Loop$ Calls During
; Proofs.

                (mv nil (cons-term fn args) ttree))
               (t

; There is a guard violation, probably -- or perhaps there's some other kind of
; error.  We'll just hide this term so we don't see it again.

                (mv t
                    (hide-with-comment (cons :scons-term erp)
                                       (cons-term fn args)
                                       wrld state)
                    (push-lemma (fn-rune-nume 'hide nil nil wrld)
                                ttree)))))
             (t (mv t
                    (kwote val)
                    (push-lemma (fn-rune-nume fn nil t wrld)
                                ttree))))))))
   ((and (eq fn 'equal)
         (equal (car args) (cadr args)))
    (mv t *t* (puffert ttree)))
   (t (mv nil (cons-term fn args) ttree))))

(mutual-recursion

(defun subst-equiv-expr1 (equiv new old geneqv term ens wrld state ttree)

; This function substitutes new for old (which are known to be in the
; equivalence relation equiv) into term (maintaining the generated
; equivalence relation geneqv).  We assume that geneqv contains only
; enabled :CONGRUENCE rules.  We use only enabled :CONGRUENCE rules.
; We return three values: a flag indicating whether we changed term,
; the new term, and a ttree recording the :CONGRUENCE rules used.
; When we create new terms we run enabled fns on constant args.  The
; executable-counterparts used are reported in the ttree.

; (The (mv a b c) expressions below mean we are returning "multiple
; values", in this case, triples consisting of a, b, and c.
; Logically speaking (mv a b c) is just (list a b c), but ACL2's
; syntactic rules ensure that the list structure is never seen, i.e.,
; the three values are immediately plucked out of the structure.
; Analogously, in (mv-let (a b c) term1 term2) term1 evaluates to a
; triple, the three variables a, b, and c are bound to the three items
; of that triple, and then term2 is evaluated under those bindings.
; ACL2 uses mv and mv-let in place of Common Lisp's multiple value
; mechanism because the Common Lisp mechanism is too flexible.  It
; allows a function to return varying numbers of things.  Ours is also
; faster.)

; NOTE:  We ignore occurrences of old inside arguments to HIDE.

  (cond ((and (equal term old)
              (geneqv-refinementp equiv geneqv wrld))
         (mv t new
             (push-lemma (geneqv-refinementp equiv geneqv wrld) ttree)))
        ((or (variablep term)
             (fquotep term)
             (eq (ffn-symb term) 'hide))
         (mv nil term ttree))
        (t (mv-let (hitp1 args ttree)
                   (subst-equiv-expr1-lst equiv new old
                                          (geneqv-lst (ffn-symb term)
                                                      geneqv
                                                      ens
                                                      wrld)
                                          (fargs term)
                                          ens wrld state ttree)

; Note: Observe that we are relying on the IF hack in geneqv-lst here,
; asking that function to generate (iff geneqv geneqv) to control our
; calls.  If we thought this function would see a lot of action on
; IF's it would be better to special-case the substitution into IF
; expressions.

                   (mv-let (hitp2 new-term ttree)
                           (scons-term (ffn-symb term) args ens wrld state ttree)
                           (mv (or hitp1 hitp2)
                               new-term
                               ttree))))))

(defun subst-equiv-expr1-lst (equiv new old geneqv-lst args ens wrld state ttree)

; Here geneqv-lst is in 1:1 correspondence with args.  We substitute
; into each arg.

  (cond ((null args)
         (mv nil nil ttree))
        (t (mv-let (hitp1 arg ttree)
                   (subst-equiv-expr1 equiv new old
                                      (car geneqv-lst)
                                      (car args)
                                      ens wrld state ttree)
                   (mv-let (hitp2 args ttree)
                           (subst-equiv-expr1-lst equiv new old
                                                  (cdr geneqv-lst)
                                                  (cdr args)
                                                  ens wrld state ttree)
                           (mv (or hitp1 hitp2)
                               (cons arg args)
                               ttree))))))

)

(defun subst-equiv-expr (equiv new old geneqv term ens wrld state ttree)
  (cond ((and (nvariablep old)
              (fquotep old))
         (mv (subst-expr-error old) term ttree))
        (t (subst-equiv-expr1 equiv new old geneqv term ens wrld state ttree))))

; This completes the definition of congruence-based substitution.

; Next we develop support for patterned congruence rules.  See the Essay just
; below the following code for an extension of one-way unification.

(defconst *anonymous-var* '|Anonymous variable|)

(mutual-recursion

(defun equal-mod-alist (term1 alist1 term2)

; We determine whether (sublis-var alist1 term1) is equal to term2.
; We just chase vars in term1 and use equal at the tips.  There is
; one subtlety.  Consider

; (equal-mod-alist '(foo x z (cons x y))
;                  '((x . '1) (y . '2))
;                  '(foo '1 z '(1 . 2)))

; The idea is that if term2 is a quoted constant and term1 is some
; function application, then it is possible that the sublis-var will
; convert term1 to a quoted constant.  We know that only happens if
; the top-most function symbol in term1 is a primitive, so we check
; that and do the sublis-var if we have to.  But it only happens on
; the ``tips.''

  (cond ((variablep term1)
         (let ((temp (assoc-eq term1 alist1)))
           (cond (temp (equal (cdr temp) term2))
                 (t (equal term1 term2)))))
        ((fquotep term1)
         (equal term1 term2))
        ((variablep term2) nil)
        ((fquotep term2)
         (cond ((and (not (flambdap (ffn-symb term1)))
                     (assoc-eq (ffn-symb term1)
                               *primitive-formals-and-guards*))
                (equal term2 (sublis-var alist1 term1)))
               (t nil)))
        ((equal (ffn-symb term1) (ffn-symb term2)) ; may be lambdas.
         (equal-mod-alist-lst (fargs term1) alist1 (fargs term2)))
        (t nil)))

(defun equal-mod-alist-lst (term1-lst alist1 term2-lst)
  (cond
   ((endp term1-lst) t)
   (t (and (equal-mod-alist (car term1-lst) alist1 (car term2-lst))
           (equal-mod-alist-lst (cdr term1-lst) alist1 (cdr term2-lst))))))
)

(mutual-recursion

(defun equal-mod-alist2 (term1 alist1 term2 alist2)

; This function is similar to equal-mod-alist, except that term1 and term2 are
; both to be instantiated: we determine whether (sublis-var alist1 term1) is
; equal to (sublis-var alist2 term2).

  (cond ((variablep term1)
         (let ((pair1 (assoc-eq term1 alist1)))
           (cond (pair1 (equal-mod-alist term2 alist2 (cdr pair1)))
                 ((variablep term2)
                  (let ((pair2 (assoc-eq term2 alist2)))
                    (eq term1 (if pair2 (cdr pair2) term2))))
                 (t nil))))
        ((variablep term2)
         (let ((pair2 (assoc-eq term2 alist2)))
           (cond (pair2 (equal-mod-alist term1 alist1 (cdr pair2)))
                 (t nil))))
        ((fquotep term1)
         (equal-mod-alist term2 alist2 term1))
        ((fquotep term2)
         (equal-mod-alist term1 alist1 term2))
        ((equal (ffn-symb term1) (ffn-symb term2)) ; may be lambdas
         (equal-mod-alist2-lst (fargs term1) alist1 (fargs term2) alist2))
        (t nil)))

(defun equal-mod-alist2-lst (term1-lst alist1 term2-lst alist2)
  (cond
   ((endp term1-lst) t)
   (t (and (equal-mod-alist2 (car term1-lst) alist1
                             (car term2-lst) alist2)
           (equal-mod-alist2-lst (cdr term1-lst) alist1
                                 (cdr term2-lst) alist2)))))
)

(mutual-recursion

(defun one-way-unify1-term-alist (pat term term-alist alist)

; Warning; Keep this function in sync with one-way-unify1.

; This function returns (mv ans alist'), where alist' minimally extends alist
; such that pat/alist' = term/term-alist if such an extension exists, in which
; case ans is non-nil, and otherwise ans is nil.  This function differs from
; one-way-unify1 in the following two ways.  First, in the present function,
; alist may contain pairs of the form (v . (:sublis-var u . s)), where u is a
; term, meaning that v is bound to u/s.  (Term-alist, however, is an ordinary
; substitution, without such :sublis-var "calls".)  Second, term is interpreted
; as term/term-alist.

; We optimize by considering term instead of term/term-alist when term-alist is
; nil.  This is certainly sound, and it seems unlikely that it will cause
; problems since we expect that term is in quote-normal form.

; There is an additional difference between this function and one-way-unify1.
; In the present function, we treat every occurrence of *anonymous-var* as a
; distinct, uniquely occurring variable, not bound in the input alist or in the
; resulting alist.

; This function is a "No-Change Loser" meaning that if it fails and returns nil
; as its first result, it returns the unmodified alist as its second.

  (declare (xargs :guard (and (pseudo-termp pat)
                              (pseudo-termp term)
                              (alistp term-alist)
                              (alistp alist))))
  (cond ((eq pat *anonymous-var*)
         (mv t alist))
        ((variablep pat)
         (let ((pair (assoc-eq pat alist)))
           (cond ((null pair)
                  (mv t
                      (acons pat
                             (if term-alist
                                 (list* :sublis-var term term-alist)
                               term)
                             alist)))
                 ((and (consp pair)
                       (consp (cdr pair))
                       (eq (car (cdr pair)) :sublis-var))
                  (cond ((null term-alist) ; optimization
                         (mv (equal-mod-alist (cadr (cdr pair))
                                              (cddr (cdr pair))
                                              term)
                             alist))
                        (t (mv (equal-mod-alist2 (cadr (cdr pair))
                                                 (cddr (cdr pair))
                                                 term
                                                 term-alist)
                               alist))))
                 ((null term-alist) ; optimization
                  (mv (equal term (cdr pair))
                      alist))
                 (t
                  (mv (equal-mod-alist term term-alist (cdr pair))
                      alist)))))
        ((fquotep pat)
         (cond ((if (null term-alist) ; optimization
                    (equal term pat)
                  (equal-mod-alist term term-alist pat))
                (mv t alist))
               (t (mv nil alist))))
        ((variablep term)
         (let ((pair (assoc-eq term term-alist)))
           (cond (pair (one-way-unify1-term-alist pat (cdr pair) nil alist))
                 (t (mv nil alist)))))
        ((fquotep term) ; then term/term-alist = term; treat term-alist as nil
         (mv-let
          (pat1 term1 pat2 term2)
          (one-way-unify1-quotep-subproblems pat term)
          (cond ((eq pat1 t) (mv t alist))
                ((eq pat1 nil) (mv nil alist))
                ((eq pat2 nil)
                 (one-way-unify1-term-alist pat1 term1 nil alist))
                (t

; We are careful with alist to keep this a no change loser.

                 (mv-let
                  (ans alist1)
                  (one-way-unify1-term-alist pat1 term1 nil alist)
                  (cond ((eq ans nil) (mv nil alist))
                        (t (mv-let
                            (ans alist2)
                            (one-way-unify1-term-alist pat2 term2 nil alist1)
                            (cond (ans (mv ans alist2))
                                  (t (mv nil alist)))))))))))
        ((equal (ffn-symb pat) (ffn-symb term)) ; could be lambdas
         (mv-let
          (ans alist1)
          (one-way-unify1-term-alist-lst (fargs pat) (fargs term)
                                         term-alist alist)
          (cond
           (ans (mv ans alist1))
           ((eq (ffn-symb pat) 'equal)

; Try again, matching by commuting one of the equalities, in analogy to the
; second call of one-way-unify1-equal1 in one-way-unify1-equal.

            (let ((pat1 (fargn pat 1))
                  (pat2 (fargn pat 2))
                  (term1 (fargn term 1))
                  (term2 (fargn term 2)))
              (mv-let
               (ans alist1)
               (one-way-unify1-term-alist pat2 term1 term-alist alist)
               (cond
                (ans
                 (mv-let
                  (ans alist2)
                  (one-way-unify1-term-alist pat1 term2 term-alist alist1)
                  (cond (ans (mv ans alist2))
                        (t (mv nil alist)))))
                (t (mv nil alist))))))
           (t (mv nil alist)))))
        (t (mv nil alist))))

(defun one-way-unify1-term-alist-lst (pl tl term-alist alist)

; Warning: Keep this in sync with one-way-unify1-lst.  See
; one-way-unify1-term-alist.

; This function is NOT a No Change Loser.  That is, it may return nil
; as its first result, indicating that no substitution exists, but
; return as its second result an alist different from its input alist.

  (declare (xargs :guard (and (pseudo-term-listp pl)
                              (pseudo-term-listp tl)
                              (alistp term-alist)
                              (alistp alist))))
  (cond
   ((null pl) (mv t alist))
   (t
    (mv-let
     (ans alist)
     (one-way-unify1-term-alist (car pl) (car tl) term-alist alist)
     (cond
      (ans (one-way-unify1-term-alist-lst (cdr pl) (cdr tl) term-alist alist))
      (t (mv nil alist)))))))

)

; Essay on Patterned Congruences and Equivalences

; This Essay documents the addition of support for pattern-based congruence
; rules: congruence rules that are not based on the application of some
; function to distinct variables.  We assume familiarity both with the Essay on
; Equivalence, Refinements, and Congruence-based Rewriting and with the
; documentation topics for congruence and patterned-congruence.

; We begin with some initial observations that have guided our implementation.

; A key design principle is that the geneqv arguments to existing functions are
; essentially unchanged.  In particular, as rewrite recurs through
; rewrite-args, which recurs back through rewrite, geneqv is passed around much
; as it was before, but can be enhanced by using so-called patterned
; equivalences that are passed through these functions' arguments.  This
; approach has allowed us to continue to use some existing functions, in
; particular geneqv-lst.

; Another basic principle is that we deal with the inherently sequentiality of
; rewrite-args, in the sense that unlike ordinary geneqvs, the use of patterned
; equivalences must be done one argument at a time.  Consider the following
; example.

; (defun triv-equiv (x y)
;      (declare (ignore x y))
;      t)

; (defequiv triv-equiv)

; (defun some-consp (x y)
;   (or (consp x) (consp y)))

; (defthm triv-equiv-implies-equal-some-consp-1
;   (implies (triv-equiv x x-equiv)
;            (equal (some-consp x (cons a b))
;                   (some-consp x-equiv (cons a b))))
;   :rule-classes (:congruence))

; (defthm triv-equiv-implies-equal-some-consp-2
;   (implies (triv-equiv y y-equiv)
;            (equal (some-consp (cons a b) y)
;                   (some-consp (cons a b) y-equiv)))
;   :rule-classes (:congruence))

; (defthm cons-is-nil
;   (triv-equiv (cons x y) nil))

; Now consider the following purported "theorem".

; (thm (equal (some-consp (cons c1 c2) (cons d1 d2))
;             (some-consp nil nil)))

; Each of the two above congruence rules applies to one of the arguments of the
; first call of some-consp in the formula just above.  One might thus expect to
; be able to apply the rule cons-is-nil to each of these arguments, reducing
; the first call above of some-consp to the second call, thus proving the
; formula.  But the formula is clearly not provable; in fact, the first call of
; some-consp is true but the second is false, by definition of some-consp!  We
; therefore must take care not to propagate such congruences independently in
; the arguments of a function call, unlike for example what we do with the
; function geneqv-lst.

; Consider the following new-style congruence rule.

; (implies (inner-equiv y1 y2)
;          (outer-equiv (mv-nth 1 (foo x (g y1) z))
;                       (mv-nth 1 (foo x (g y2) z))))

; We imagine that there may be many such rules about mv-nth, so we index such
; rules not by the outer function symbol (here, mv-nth), but by the next
; function symbol down towards the designated variable (here, foo).  The
; rewriter will consider this rule after it has already dived into a call of
; foo; so the rewriter passes information about the parent call of mv-nth.  Now
; suppose we are rewriting the term (mv-nth 1 (foo a (h b1) c)), and assume
; that some rewrite rule equates (h b1) with (g b1).  As we rewrite inside-out,
; we pick up the congruence rule when we reach the call (foo a (h b1) c).  We
; might be tempted to have the rewriter ignore this congruence rule when
; passing to the term (h b1), but that would be a mistake: at that point, (h
; b1) rewrites to (g b1), and the rewriter is then called recursively.  We want
; this recursive call to notice the congruence rule, so that it will be
; sufficient to preserve inner-equiv when making that recursive call on (g b1).
; Thus, we introduce a notion of a "next" operation that is invoked when
; passing from the call of foo to the call of h, and we do not discard "next"
; data based on a mere failure to match the current call, which here is (h b1).

; This concludes initial observations that have guided our implementation.

; We assume familiarity with the concepts described in the Essay on
; Equivalence, Refinements, and Congruence-based Rewriting, but we begin with a
; brief review.  That Essay describes the notion of rewriting with respect to a
; generated equivalence relation, or geneqv: a list of congruence-rule
; structures that denotes the transitive closure of the union of the
; equivalence relations represented by the :equiv fields of those congruence
; rules.  When ACL2 rewrites a function call with respect to a geneqv, it
; rewrites each argument of that function call with respect to a geneqv derived
; by applying congruence rules to the original geneqv.  A congruence rule has
; the following form, where fn is a function symbol and its two calls are made
; on the same sequence of distinct variables, except that x and y occur
; uniquely in corresponding positions as shown.

; (implies (equiv1 x y)
;          (equiv2 (fn a1 ... x ... an)
;                  (fn a1 ... y ... an))),

; Let us call these rules "classic" congruence rules.  We will refer to equiv1
; as the "inner equivalence", equiv2 as the "outer equivalence", fn as the
; "function symbol", x as the "variable", y as the "replacement variable", and
; the first and second arguments of the above call of equiv2 as the "lhs" and
; "rhs" of the rule, respectively.  In such a case, where x is the kth argument
; of fn in the lhs of the rule, we say that it "suffices to maintain equiv1 at
; the kth argument of a call of fn in order to maintain equiv2".  This notion
; does not depend on a specific congruence rule; that is, it makes sense for
; any pair equiv1 and equiv2 of equivalence relations, any function symbol fn,
; and any positive k not exceeding the arity of fn.

; In this Essay we discuss a generalization of the above notion of congruence
; rules in which the notions of variable, replacement variable, lhs, and rhs
; still apply: congruence rules still have the following form, where lhs and
; rhs are calls of the same function symbol.

; (implies (equiv1 x y)
;          (equiv2 lhs rhs)),

; As before, lhs and rhs must be the same with the exception that the variable
; and replacement variable occur uniquely in the rule and, moreover, at the
; same address (same position) in lhs and rhs, respectively.  But we relax the
; other requirements on the arguments of lhs (and hence rhs): they need not be
; variables, and duplicates are permissible.  The following are examples of
; congruence rules that are not classic, since each lhs has non-variable
; arguments.  (As of this writing, these and other examples may be found in
; community book demos/patterned-congruences.lisp.)  In each case the variable
; is y1 and the replacement variable is y2.

; Inner equivalence e1, outer equivalence iff:

;    (implies (e1 y1 y2)
;             (iff (f1 3 y1 (cons x x))
;                  (f1 3 y2 (cons x x))))

; Inner equivalence e4, outer equivalence equal:

;    (implies (e4 y1 y2)
;             (equal (mv-nth 1 (id (f7 y1)))
;                    (mv-nth 1 (id (f7 y2)))))

; The first of these two rules is called "shallow" because y1 and y2 occur as
; top-level arguments of the lhs and rhs of the rule (respectively), just as
; they do in the classic congruence rule previously displayed above.  The
; second of these rules is not of that form because y1 and y2 occur inside a
; subsidiary function call; the second rule is thus not shallow, so we call it
; "deep".  Both are what we call "patterned congruence rules".  Thus, the class
; of congruence rules is partitioned into the classes of classic and patterned
; congruence rules, and the patterned congruence rules are partitioned into the
; subclasses of shallow and deep congruence rules.

; A shallow or deep patterned congruence rule generates what we call a (shallow
; or deep, respectively) "patterned equivalence relation", or pequiv.

(defrec pequiv
  (pattern     ; a pequiv-pattern record
   unify-subst ; a (unifying) substitution
   .
   congruence-rule ; a congruence-rule record
   )
  t)

; The :unify-subst field is nil for the pequiv generated by a patterned
; congruence rule, but need not be nil in general; we describe its role when we
; give the semantics of pequiv records later below.  The :congruence-rule field
; is the congruence-rule record corresponding to the patterned congruence rule
; from which this pequiv is derived.  Finally, we describe the :pattern field,
; which represents the lhs of a patterned congruence rule.  This field is
; actually a pequiv-pattern record (defined below), which represents a term,
; specifically a function call, along with a variable that occurs uniquely
; within the term.  Function make-pequiv-pattern creates a pattern from the
; term and (the address of the) variable, informally as follows.  The :fn of
; the pattern is the function symbol of the term.  The :posn is the one-based
; position within the arguments of the term under which the variable (uniquely)
; occurs.  The :pre-rev field is the reverse of the list of arguments strictly
; before that position, while the :post field is the list of arguments strictly
; after that position.  Finally, the :next field is either a variable
; (corresponding to the variable of the patterned congruence rule) or else is,
; recursively, the pattern representing the argument at :posn (along with the
; same variable).

(defrec pequiv-pattern ; see description just above
  (fn posn pre-rev post next)
  t)

; The discussion above is perhaps a bit misleading because of the following
; optimization.  Our algorithm attempts to extend a unifying substitution by
; matching the :pre-rev and :post fields with a term.  But we do not need to
; record matching of a variable that will not be encountered further.
; Therefore, before creating the pattern from the term, we replace each
; uniquely-occurring variable in the term by the variable, *anonymous-var*.  In
; order to justify this transformation, we first check that *anonymous-var*
; does not occur anywhere in the term.  (Perhaps it is sufficient that
; *anonymous-var* does not occur in the arguments of lhs other than the
; variable of the rule, but the stronger check avoids the need to think through
; whether that is truly sufficient.)  Then, we use a matching algorithm that
; always succeeds when matching *anonymous-var*, but never binds
; *anonymous-var* in the unifying substitution.  This optimization thus saves
; some consing.  In the rest of this discussion we will ignore the above
; optimization when we believe this will not lead to confusion.

; We will freely abuse terminology when we expect no confusion to result.  For
; example, we may confuse a patterned congruence rule with its corresponding
; pequiv, and we may confuse a term with its corresponding pattern.  Thus, we
; may speak of the "term" of a pequiv to denote the term corresponding to its
; :pattern field; similarly, the "variable" of a pequiv is just the variable of
; the corresponding patterned congruence rule.  (One could expect to reach that
; variable by following the :next field of the :pattern of the pequiv until
; :next is a variable, except of course that the variable will have been
; replaced by the anonymous variable described above.)

; A pequiv record denotes the following equivalence relation, which we may
; refer to as the corresponding "patterned equivalence".  For this discussion
; we assume a global binding of variables to values; intuitively, when you
; submit a formula to ACL2 to prove, the variables in the formula represent
; values provided by an arbitrary such binding.  Recall the notion of an
; equivalence relation generated by a binary relation, namely, the
; equivalential (reflexive, symmetric, transitive) closure of that binary
; relation.  The patterned equivalence relation denoted by a pequiv is the
; equivalential closure of the following binary relation.  Let t0 be the term
; of the pequiv.  Two values v1 and v2 are related if for some substitution s
; that extends the :unify-subst of the pequiv and for variants s1 and s2 of s
; obtained by rebinding only the variable of the pequiv, then v1 = t0/s1 and v2
; = t0/s2.

; Let p be a pequiv, fn be a function symbol, and first-rev and rest be term
; lists.  We next define the notion of the "next equiv" for a pequiv, p, with
; respect to fn, first-rev, and rest.  Let pat be the :pattern field of p.
; This next equiv is either undefined or is obtained from p as described below.
; Let k, pre-rev, post, and next be the :pre-rev, :post, and :next fields of
; pat, respectively.  The next equiv is undefined unless, at a minimum: fn is
; equal to the :fn field of pat, first-rev has the same length as the :pre-rev
; field of pat, and rest has the same length as the :post field of pat.  So
; assume that these conditions hold.  Let s0 be the :unify-subst field of p,
; and let s be the minimal extension of s0 such that pre-rev/s = first-rev and
; post/s = rest, if such s exists; otherwise the next equiv does not exist.  If
; p is a deep pequiv, then the next equiv is the result of replacing the
; :unify-subst of p by s and replacing the :pattern of p by next.  If p is a
; shallow equiv, then the next equiv for p is the equivalence relation of the
; :congruence-rule of p.  Note: If we refer to the next equiv for p and u,
; where u is a term, we are really referring to the next equiv for p with
; respect to fn, first-rev and rest, where u is of the form (cons fn (revappend
; first-rev (cons arg rest))) for some arg and the length of first-rev is the
; value of the :posn field of the :pattern field of p.

; The correctness of our implementation relies on the theorems below, whose
; proofs we leave to the reader.  The first theorem justifies the addition of a
; pequiv to the list of equivalence relations being maintained by the rewriter,
; while the second justifies how a pequiv is used when rewriting an argument of
; a function call.

; Patterned Congruence Theorem 1.  Let E be the pequiv corresponding to a
; provable patterned congruence rule with outer equivalence e2.  Then for terms
; t1 and t2, (implies (E t1 t2) (e2 t1 t2)) is provable.

; Patterned Congruence Theorem 2.  Let p be a pequiv, let u be a term, and
; assume that the next equiv for p and u exists; call it n.  Let arg be the kth
; argument of u, where k is the :posn field of the :pattern field of u, let
; arg' be a term, and let u' be the result of replacing the kth argument of u
; by arg'.  Then (implies (n arg arg') (p u u')).

; A final data structure for supporting patterned congruence rules is the
; pequiv-info record.  The rewrite clique takes a pequiv-info formal parameter
; that is either nil or such a record.

(defrec pequiv-info

; Each function in the rewrite clique has a pequiv-info argument that either is
; nil or is one of these records.  In the latter case, that argument represents
; information from a parent call of rewrite on a function call, where one
; argument of the call is the "current term" being processed, and other
; "sibling arguments" of the call are stored as indicated below.

  (((rewritten-args-rev ; reverse of (rewritten) preceding sibling arguments
     .
     rest-args) ; later sibling arguments, not yet rewritten
    .
    (alist ; alist under which the current term and rest-args are rewritten
     .
     bkptr)) ; one-based position of the current term
   .
   (geneqv ; geneqv of the parent call of rewrite
    fn ; function symbol of the term rewritten by the parent call of rewrite
    .

; Finally, deep-pequiv-lst is a list of (deep) pequivs from the parent call of
; rewrite, each of which has an enabled :congruence-rule field.

    deep-pequiv-lst))
  t)

; When rewrite is called with a pequiv-info argument of nil, its spec is
; unchanged from what it was before the introduction of patterned congruences:
; the term returned by (rewrite term alist ... geneqv ...) is provably in
; relation geneqv to term/alist.  Of course, "provably" should be understood
; relative to the assumptions implicit in the other arguments of rewrite: the
; type-alist, world, and pot-list.

; Subtle Logical Aside.  More subtly, terms u1 and u2 can be understood as
; being "provably in relation geneqv" if there is a sequence of terms t0, ...,
; tk such that t0 = u1, tk = u2, and for each i < k and where j = i+1, there is
; some equivalence relation E in geneqv such that (E ti tj) is provable (again,
; with respect to the implicit assumptions).  We may wish to take this view of
; "provably in relation geneqv" because the geneqv relation is defined in terms
; of a transitive closure, which is not a first-order notion.  In the case of
; ACL2 we could actually provide a first-order definition of geneqv by using
; sequences: it is first-order to state that there is a finite sequence of
; values such that each is in relation E to the next for some E in geneqv.
; Either of these two notions of "provably in relation geneqv" is in fact
; adequate; choose your favorite!  End of Subtle Logical Aside.

; We turn now to modifying the above spec for the case of (rewrite term alist
; bkptr ... geneqv pequiv-info ...), where pequiv-info is a pequiv-info record
; with fields rewritten-args-rev, rest-args, alist, bkptr, parent-geneqv,
; parent-fn, and deep-pequiv-lst, and obvious assumptions are left implicit (in
; particular, bkptr is the length of rewritten-args-rev).  Generate an
; equivalence relation E by extending geneqv by each of the following, as p
; ranges over members of deep-pequiv-lst: the next-equiv for p with respect to
; parent-fn, rewritten-args-rev, and rest-args/alist.  Then the output from the
; above call of rewrite is provably in relation E to term.  (Note: in our
; implementation, p also ranges over some pequivs that provably refine a member
; of parent-geneqv; but we can include these, by the theorems above.)  We
; discuss later how to prove this spec, after summarizing how pequivs are
; processed by the rewriter.

; In order to minimize property list accesses, we store deep and shallow
; equivalences in a single structure, as follows.

(defrec pequivs-property
  (deep shallow . deep-pequiv-p)
  t)

; The :deep and :shallow fields are alists whose elements have the form (equiv
; pequiv1 pequiv2 ... pequivn), where each pequivk is a patterned equivalence
; that refines equiv.  When such a record is the value of the 'pequivs property
; of a function symbol, fn, then fn is the :fn field of the :pattern field of
; each such pequivk in the case of the :shallow field; but in the case of the
; :deep field, each such pequivk is a deep pequiv, and fn is the :fn field of
; the :next field of the :pattern field.  In brief, consider a patterned
; congruence rule with function symbol fn together with outer equivalence e and
; corresponding pequiv, p.  If the rule (and hence also p) is shallow, then we
; will find p in the :shallow field of the 'pequivs property of fn, which is an
; alist with an element (e ... p ...).  Otherwise the rule (and hence also p)
; is deep, with lhs of the form (fn ... (fn2 ...) ...) such that the variable
; of the rule occurs in the displayed call of fn2.  In that case, we will find
; p in the :deep field of the 'pequivs property of fn2, which is an alist with
; an element (e ... p ...).

; Algorithm discussion.  Next, we describe how rewrite passes pequiv
; information to rewrite-args and how rewrite-args passes pequiv information to
; rewrite.

; Rewrite computes a list of deep-pequivs and a list of shallow-pequivs to pass
; to rewrite-args using function pequivs-for-rewrite-args, where the input term
; is a call of function symbol fn, a symbol (not a lambda).  In (a) and (b)
; below, we compute the next pequiv with respect to the following function
; symbol, first-rev, and rest: the function symbol is fn; first-rev is the
; :rewritten-args-rev field of pequiv-info; and for rest, we take the
; :rest-args field of pequiv-info and instantiate it with the :alist field of
; pequiv-info.  Note that the pequiv-info argument is guaranteed not to be nil
; if there are any pequivs in (a) or (b) for which to take the next equiv.

; (a) Derive the list of next equivs from the :deep-pequiv-lst field of the
;     pequiv-info argument, restricting to those (deep) pequivs whose :next
;     field has :fn field equal to fn.  Sort these into a list of deep pequivs
;     and a list of shallow pequivs.

; (b) Derive the list of next equivs from deep pequivs stored in the 'pequivs
;     property of fn, restricting to those that are stored under an outer equiv
;     that is enabled and refines the geneqv of pequiv-info.  Sort these into a
;     list of deep pequivs and a list of shallow pequivs.

; (c) Compute additional shallow pequivs from the shallow pequivs stored in the
;     'pequivs property of fn, restricting to those that are stored under an
;     outer equiv that is enabled and refines the geneqv argument of (the
;     present call of) rewrite.

; Note that rewrite is not passed any shallow pequivs.  Rather, rewrite derives
; shallow-pequivs as described above and passes these to rewrite-args, which
; uses them to augment the geneqv passed to the child call of rewrite.  That
; augmentation is done by geneqv-and-pequiv-info-for-rewrite, which is called
; by rewrite-args in preparation for its call of rewrite; we describe this
; next.

; Now consider a call (rewrite-args args alist bkptr rewritten-args-rev
; deep-pequiv-lst shallow-pequiv-lst parent-geneqv parent-fn ... geneqv-lst
; ...).  These arguments are used by function
; geneqv-and-pequiv-info-for-rewrite to produce the geneqv and pequiv-info
; arguments for its "child call" of rewrite.  That child call's geneqv is
; constructed initially from the geneqv-lst passed to rewrite-args, but is
; extended (by function geneqv-for-rewrite) using the next equiv for each
; member of shallow-pequiv-lst with respect to parent-fn, rewritten-args-rev,
; and (cdr args).  In doing this, we maintain the invariant that a geneqv does
; not contain two equivs such that one refines the other.  The pequiv-info
; record for the child call of rewrite is constructed by function
; pequiv-info-for-rewrite, with fields taken unchanged from the inputs of
; rewrite-args, in particular without taking the "next" for the pequivs.
; Except, nil may be returned for pequiv-info when a pequiv-info record is not
; needed by rewrite, in order to save consing; see pequiv-info-for-rewrite.

; We will briefly sketch the proof by computational induction that the ACL2
; rewriter satisfies the spec given above for rewrite.  The interesting
; induction steps are for calling rewrite on a first argument that is a
; function call when the pequiv-info argument is not nil, and for calling
; rewrite-args on a non-empty first parameter, args.  Our spec for rewrite is
; above, and although a detailed proof would also involve a spec for each
; function in the rewrite clique, for this sketch we give an additional spec
; only for rewrite-args.  (Then we will sketch the proof.)

; Consider a call (rewrite-args args alist bkptr rewritten-args-rev
; deep-pequiv-lst shallow-pequiv-lst parent-geneqv parent-fn ... geneqv-lst
; ...), which results in a term list args', and define the "input term" and
; "output term" to be, respectively, (cons parent-fn (revappend
; rewritten-args-rev args/alist)) and (cons parent-fn args').  Assume that
; geneqv-lst is a list of generated equivalence relations that corresponds
; positionally to args, such that for each element g of this list and
; corresponding position k in the argument list of parent-fn, it suffices to
; preserve g at the kth argument of parent-fn in order to preserve
; parent-geneqv.  Then the input and output terms are provably equivalent with
; respect to the equivalence relation generated by parent-geneqv,
; deep-pequiv-lst, and shallow-pequiv-lst.

; Turning now to the proof sketch, first consider the induction step for
; (rewrite-args (cons arg rest-args) alist bkptr rewritten-args-rev
; deep-pequiv-lst shallow-pequiv-lst parent-geneqv parent-fn ... (cons geneqv
; geneqv-lst) ...).  This call is equal to the call (rewrite-args rest-args
; alist (1+ bkptr) (cons rewritten-arg rewritten-args-rev) deep-pequiv-lst
; shallow-pequiv-lst parent-geneqv parent-fn ... geneqv-lst), where
; rewritten-arg is produced by rewrite using the geneqv and pequiv-info
; returned by the call that rewrite-args makes of
; geneqv-and-pequiv-info-for-rewrite.  It suffices by the inductive hypothesis
; to show that arg/alist and rewritten-arg are provably in the equivalence
; relation generated by parent-geneqv, deep-pequiv-lst, and shallow-pequiv-lst.
; But this follows from Patterned Congruence Theorem 2, since by hypothesis
; geneqv is sufficient for preserving parent-geneqv, and because the spec for
; rewrite is with respect to the next equivs for deep-pequiv-lst and
; shallow-pequiv-lst.

; Now consider the induction step for (rewrite term alist ... pequiv-info ...).
; Now pequivs-for-rewrite-args sets up a call of rewrite-args with next equivs
; generated from pequiv-info (if non-nil) as in (a) and (b) above, and with new
; pequivs as in (c) above.  These next equivs are justified by Patterned
; Congruence Theorems 1 and 2.  By the inductive hypothesis, that call of
; rewrite-args returns a term that is suitably equivalent to term/alist.  Then
; the inductive hypothesis takes care of any ensuing call of rewrite, say from
; rewrite-if or from the right-hand side of an applied rewrite rule.

; We conclude this essay by emphasizing that our support for patterned
; congruence rules is limited; in particular, it is mainly for the rewriter.
; Thus, pequivs fail to be used heuristically in some places that ordinary
; congruences are used: for example, as in test-3 in community book
; books/demos/patterned-congruences.lisp, remove-trivial-equivalences and
; fertilize-clause doesn't use patterned congruence rules.  If we decide to add
; such support, then we should think carefully so that we don't introduce
; unsoundness.  See the examples in the above book involving congruence rules
; triv-equiv-implies-equal-some-consp-1 and
; triv-equiv-implies-equal-some-consp-2; while we don't have similar examples
; at hand to illustrate the danger of careless substitution with
; remove-trivial-equivalences and fertilize-clause, we can imagine that such
; dangers exist.  Finally support for pequivs is provided in the function
; geneqv-at-subterm-top, used in the proof-builder, but is not provided in the
; code the warns about missing opportunities for the use of double-rewrite
; (e.g., double-rewrite-opportunities).

; End of Essay on Patterned Congruences and Equivalences

(defconst *empty-pequivs-property*
  (make pequivs-property
        :deep nil
        :shallow nil
        :deep-pequiv-p nil))

(defmacro pequivs-property-field (prop field)

; We currently store nil as the 'pequivs property of a newly defined function
; (see defuns-fn1 and intro-udf), which accounts for the test below that prop
; is non-nil.  We could instead store *empty-pequivs-property* initially, in
; which case we could eliminate this macro and just use access directly.

  (declare (xargs :guard (and (member-eq field
                                         '(:deep :shallow :deep-pequiv-p))
                              (not (keywordp prop))))) ; avoid capture
  `(let ((prop ,prop))
     (and prop
          (access pequivs-property prop ,field))))

(defun next-pequiv (pequiv rewritten-args-rev rest-args alist)

; We return the next equiv for the given deep pequiv with respect to an
; implicit function symbol (already checked by the caller) together with
; rewritten-args-rev and rest-args/alist.  See the Essay on Patterned
; Congruences and Equivalences.

  (let ((pattern (access pequiv pequiv :pattern)))
    (mv-let
     (flg unify-subst)
     (one-way-unify1-term-alist-lst (access pequiv-pattern pattern :pre-rev)
                                    rewritten-args-rev
                                    nil
                                    (access pequiv pequiv :unify-subst))
     (cond ((null flg) nil)
           (t (mv-let
               (flg unify-subst)
               (one-way-unify1-term-alist-lst (access pequiv-pattern pattern
                                                      :post)
                                              rest-args alist unify-subst)
               (cond ((null flg) nil)
                     ((equal (access pequiv pequiv :unify-subst)
                             unify-subst) ; to avoid consing
                      (change pequiv pequiv
                              :pattern
                              (access pequiv-pattern pattern :next)))
                     (t (change pequiv pequiv
                                :pattern
                                (access pequiv-pattern pattern :next)
                                :unify-subst
                                unify-subst)))))))))

(defun next-pequivs (deep-pequiv-lst rewritten-args-rev rest-args alist bkptr
                                     parent-fn child-fn ens
                                     next-deep-pequiv-lst
                                     next-shallow-pequiv-lst)

; We return next equivs for (deep) pequivs in deep-pequiv-lst, as described
; below.  See the Essay on Patterned Congruences and Equivalences.

; This function is really a combination of two functions.  In one case, we
; expect all congruences within deep-pequiv-lst to be enabled; then child-fn is
; required to be the function symbol of the child and ens is irrelevant.  In
; the other case, we expect all pequivs in deep-pequiv-lst to have :next
; patterns whose :fn is the child function, so we pass in child-fn = nil but we
; also pass in ens as an enabled structure, in order to filter deep-pequiv-lst
; by enabled congruences.

  (cond
   ((endp deep-pequiv-lst)
    (mv next-deep-pequiv-lst next-shallow-pequiv-lst))
   (t (let* ((deep-pequiv (car deep-pequiv-lst))
             (pat (access pequiv deep-pequiv :pattern))
             (next (access pequiv-pattern pat :next))
             (next-pequiv
              (assert$
               (not (variablep next)) ; deep-equiv is deep
               (and (eq parent-fn (access pequiv-pattern pat :fn))
                    (eql bkptr (access pequiv-pattern pat :posn))
                    (if child-fn
                        (eq child-fn (access pequiv-pattern next :fn))
                      (enabled-numep
                       (access congruence-rule
                               (access pequiv deep-pequiv :congruence-rule)
                               :nume)
                       ens))
                    (next-pequiv deep-pequiv rewritten-args-rev rest-args
                                 alist)))))
        (cond
         ((not next-pequiv)
          (next-pequivs (cdr deep-pequiv-lst) rewritten-args-rev rest-args
                        alist bkptr parent-fn child-fn ens
                        next-deep-pequiv-lst next-shallow-pequiv-lst))
         ((variablep (access pequiv-pattern next :next)) ; next is shallow
          (next-pequivs
           (cdr deep-pequiv-lst) rewritten-args-rev rest-args alist
           bkptr parent-fn child-fn ens
           next-deep-pequiv-lst
           (cons next-pequiv next-shallow-pequiv-lst)))
         (t ; next is deep
          (next-pequivs
           (cdr deep-pequiv-lst) rewritten-args-rev rest-args alist
           bkptr parent-fn child-fn ens
           (cons next-pequiv next-deep-pequiv-lst)
           next-shallow-pequiv-lst)))))))

(defun next-pequivs-alist (deep-pequiv-alist rewritten-args-rev rest-args
                                             alist bkptr parent-fn
                                             parent-geneqv wrld ens
                                             next-deep-pequiv-lst
                                             next-shallow-pequiv-lst)

; Deep-pequiv-alist is a list of entries of the form (equiv pequiv1
; ... pequivk).  For each such entry for which equiv refines parent-geneqv, and
; then for each pequivi -- which is a deep pequiv -- whose congruence-rule is
; enabled, accumulate into next-deep-pequiv-lst and next-shallow-pequiv-lst the
; next equiv with respect to parent-fn, rewritten-args-rev, and
; rest-args/alist.  See the Essay on Patterned Congruences and Equivalences.

  (cond ((endp deep-pequiv-alist)
         (mv next-deep-pequiv-lst next-shallow-pequiv-lst))
        ((geneqv-refinementp (caar deep-pequiv-alist) parent-geneqv wrld)
         (mv-let (next-deep-pequiv-lst next-shallow-pequiv-lst)
                 (next-pequivs (cdar deep-pequiv-alist)
                               rewritten-args-rev rest-args alist bkptr
                               parent-fn
                               nil ; child-fn
                               ens
                               next-deep-pequiv-lst next-shallow-pequiv-lst)
                 (next-pequivs-alist (cdr deep-pequiv-alist)
                                     rewritten-args-rev rest-args
                                     alist bkptr parent-fn
                                     parent-geneqv wrld ens
                                     next-deep-pequiv-lst
                                     next-shallow-pequiv-lst)))
        (t (next-pequivs-alist (cdr deep-pequiv-alist)
                               rewritten-args-rev rest-args
                               alist bkptr parent-fn
                               parent-geneqv wrld ens
                               next-deep-pequiv-lst
                               next-shallow-pequiv-lst))))

(defun extend-pequiv-lst (pequiv-lst ens acc)
  (cond ((endp pequiv-lst) acc)
        (t (extend-pequiv-lst
            (cdr pequiv-lst)
            ens
            (cond ((enabled-numep (access congruence-rule
                                          (access pequiv (car pequiv-lst)
                                                  :congruence-rule)
                                          :nume)
                                  ens)
                   (cons (car pequiv-lst) acc))
                  (t acc))))))

(defun accumulate-shallow-pequiv-alist (alist geneqv wrld ens acc)

; Alist associates each of its keys, an equivalence relation, with a list of
; shallow pequivs.  We accumulate those pequivs into acc for which the key
; refines geneqv and the congruence-rule is enabled.

  (cond ((endp alist) acc)
        (t (accumulate-shallow-pequiv-alist
            (cdr alist) geneqv wrld ens
            (cond ((geneqv-refinementp (caar alist) geneqv wrld)
                   (extend-pequiv-lst (cdar alist) ens acc))
                  (t acc))))))

(defun pequivs-for-rewrite-args (fn geneqv pequiv-info wrld ens)

; See the Essay on Patterned Congruences and Equivalences, in particular the
; discussion of computations of a list of deep-pequivs and a list of
; shallow-pequivs to pass to rewrite-args shown there as (a), (b), and (c).

; Consider a call of rewrite whose term argument, u, has input fn as its
; function symbol, whose rcnst argument has input ens as its enabled structure,
; and whose geneqv, pequiv-info, and wrld arguments are corresponding inputs of
; the present function.  We return two values, next-deep-pequiv-lst and
; next-shallow-pequiv-lst, which are suitable for the ensuing call of
; rewrite-args on the arguments of u.  These are lists of deep and of shallow
; pequivs, respectively, except that next-deep-pequiv-lst can take the special
; value of :none, which represents the empty list but indicates that the
; :deep-pequiv-p field is true for the 'pequivs property of fn, indicating that
; some deep pequiv has a :pattern whose :fn is fn.

  (cond
   ((flambdap fn) ; no chance of a match by child rewrite call
    (mv nil nil))
   (t (let* ((prop (getpropc fn 'pequivs nil wrld))
             (shallow-pequiv-alist (pequivs-property-field prop :shallow)))
        (cond
         ((not pequiv-info) ; no pequivs for which to take the "next"
          (mv (and (pequivs-property-field prop :deep-pequiv-p)
                   :none)
              (accumulate-shallow-pequiv-alist ; (c)
               shallow-pequiv-alist geneqv wrld ens nil)))
         (t
          (let ((deep-pequiv-lst (access pequiv-info pequiv-info
                                         :deep-pequiv-lst))
                (rewritten-args-rev (access pequiv-info pequiv-info
                                            :rewritten-args-rev))
                (rest-args (access pequiv-info pequiv-info
                                   :rest-args))
                (alist (access pequiv-info pequiv-info
                               :alist))
                (bkptr (access pequiv-info pequiv-info
                               :bkptr))
                (parent-fn (access pequiv-info pequiv-info
                                   :fn)))
            (mv-let
             (next-deep-pequiv-lst next-shallow-pequiv-lst) ; (a)
             (next-pequivs deep-pequiv-lst rewritten-args-rev rest-args alist
                           bkptr parent-fn fn
                           nil ; or ens -- irrelevant argument
                           nil nil)
             (mv-let
              (next-deep-pequiv-lst next-shallow-pequiv-lst) ; (b)
              (next-pequivs-alist (pequivs-property-field prop :deep)
                                  rewritten-args-rev rest-args alist bkptr
                                  parent-fn
                                  (access pequiv-info pequiv-info :geneqv)
                                  wrld ens
                                  next-deep-pequiv-lst next-shallow-pequiv-lst)
              (mv (or next-deep-pequiv-lst
                      (and (pequivs-property-field prop :deep-pequiv-p)
                           :none))
                  (accumulate-shallow-pequiv-alist ; (c)
                   shallow-pequiv-alist
                   geneqv wrld ens next-shallow-pequiv-lst)))))))))))

(defun pequiv-info-for-rewrite (fn bkptr rewritten-args-rev args alist geneqv
                                   deep-pequiv-lst)

; See the Essay on Patterned Congruences and Equivalences.

  (cond ((or (null deep-pequiv-lst) ; common case (note: nil, not :none)
             (flambdap fn)
             (variablep (car args))
             (fquotep (car args)))

; In this case we return nil in order to avoid consing, as the ensuing child
; call of rewrite from rewrite-args will not need a pequiv-info record.  Why
; won't such a record be needed?

; If the term passed to the parent call of rewrite is a lambda application --
; that is, fn is a lambda -- then no matching will take place, as we do not
; allow lambdas in patterned congruence rules (see the call of
; lambda-subtermp-lst in interpret-term-as-congruence-rule); so the child
; rewrite call will not need pequiv-info.  If the term passed to the child call
; of rewrite is a variable or a quotep, then we don't expect a recursive call
; of rewrite and hence we don't expect an ensuing call of rewrite-args, so
; again we won't need pequiv-info.  Otherwise, it suffices that deep-pequiv-lst
; be nil, as we can see by considering the two potential sources of next equivs
; whose computation would require pequiv-info -- conditions (a) and (b) from
; the Essay on Patterned Congruences and Equivalences.  One source (from (a))
; is the :deep-pequiv-lst field of pequiv-info, which will be empty if the
; deep-pequivs argument of rewrite-args is empty.  The other source (from (b))
; is the deep pequivs stored in the 'pequivs property of fn (so, fn is a
; function symbol in this case, not a lambda).  But if there are any such deep
; pequivs, then deep-pequiv-lst is either a non-empty list or :none (as
; computed by pequivs-for-rewrite-args), not nil.

         nil)
        (t (make pequiv-info
                 :rewritten-args-rev rewritten-args-rev
                 :rest-args (cdr args)
                 :alist alist
                 :bkptr bkptr
                 :fn fn
                 :geneqv geneqv
                 :deep-pequiv-lst
                 (and (consp deep-pequiv-lst) ; rule out :none
                      deep-pequiv-lst)))))

(defun reduce-geneqv-for-equiv (equiv wrld geneqv)

; We will be adding equiv to geneqv.  Here, in preparation for that addition,
; return the result of deleting every refinement of equiv from geneqv.

  (cond ((endp geneqv) (mv nil nil))
        (t (mv-let
            (changedp rest)
            (reduce-geneqv-for-equiv equiv wrld (cdr geneqv))
            (cond
             ((refinementp (access congruence-rule (car geneqv) :equiv)
                           equiv
                           wrld)
              (mv t rest))
             (changedp
              (mv t (cons (car geneqv) rest)))
             (t (mv nil geneqv)))))))

(defun geneqv-for-rewrite (shallow-pequiv-lst fn bkptr rewritten-args-rev
                                              rest-args alist wrld geneqv)

; See the Essay on Patterned Congruences and Equivalences.  Here we return the
; result of extending geneqv using every non-nil next equiv for each (shallow)
; pequiv in shallow-pequiv-lst, with respect to fn, rewritten-args-rev, and
; rest-args/alist.  This function assumes that every congruence rule of
; shallow-pequiv-lst is enabled.

  (cond
   ((null shallow-pequiv-lst) geneqv)
   (t (let* ((pequiv (car shallow-pequiv-lst))
             (pat (access pequiv pequiv :pattern))
             (congruence-rule (access pequiv pequiv :congruence-rule))
             (equiv (access congruence-rule congruence-rule :equiv)))
        (geneqv-for-rewrite
         (cdr shallow-pequiv-lst)
         fn bkptr rewritten-args-rev rest-args alist wrld
         (cond
          ((or (not (eq fn (access pequiv-pattern pat :fn)))
               (not (eql bkptr (access pequiv-pattern pat :posn)))
               (geneqv-refinementp equiv geneqv wrld))
           geneqv)
          (t (mv-let
              (flg unify-subst)
              (one-way-unify1-term-alist-lst
               (access pequiv-pattern pat :pre-rev)
               rewritten-args-rev
               nil
               (access pequiv pequiv :unify-subst))
              (cond
               ((null flg) geneqv)
               (t (mv-let
                   (flg unify-subst)
                   (one-way-unify1-term-alist-lst
                    (access pequiv-pattern pat :post)
                    rest-args alist unify-subst)
                   (declare (ignore unify-subst))
                   (cond
                    ((null flg) geneqv)
                    (t

; We extend geneqv by the equiv of the congruence rule of pequiv.  If some
; member of geneqv is a refinement of equiv then we delete that member.  This
; process may be inefficient if many such equiv are processed, since we will
; continually be taking the coarsenings of geneqv.  But for now, at least, we
; pay that price rather than the alternative of building an alist that pairs
; each congruence rule in geneqv with the coarsenings of its :equiv.

                     (mv-let
                      (changedp geneqv)
                      (reduce-geneqv-for-equiv equiv wrld geneqv)
                      (declare (ignore changedp))
                      (cons congruence-rule geneqv)))))))))))))))

(defun geneqv-and-pequiv-info-for-rewrite (fn bkptr rewritten-args-rev args
                                              alist parent-geneqv child-geneqv
                                              deep-pequiv-lst
                                              shallow-pequiv-lst
                                              wrld)
  (mv (geneqv-for-rewrite shallow-pequiv-lst fn bkptr rewritten-args-rev
                          (cdr args) alist wrld child-geneqv)
      (pequiv-info-for-rewrite fn bkptr rewritten-args-rev args alist
                               parent-geneqv deep-pequiv-lst)))

; Next we develop clausify, the function that reduces a term to a set
; of clauses.

(mutual-recursion

(defun ffnnamesp (fns term)

; We determine whether some function fn (possibly a lambda-expression)
; in fns is used as a function in term.  So this function is:
; (exists fn in fns s.t. (ffnnamep fn term)).

  (cond ((variablep term) nil)
        ((fquotep term) nil)
        ((flambda-applicationp term)
         (or (member-equal (ffn-symb term) fns)
             (ffnnamesp fns (lambda-body (ffn-symb term)))
             (ffnnamesp-lst fns (fargs term))))
        ((member-eq (ffn-symb term) fns) t)
        (t (ffnnamesp-lst fns (fargs term)))))

(defun ffnnamesp-lst (fns l)
  (if (null l)
      nil
    (or (ffnnamesp fns (car l))
        (ffnnamesp-lst fns (cdr l)))))

)

(mutual-recursion

(defun collect-ffnnames (fns term ans)

; We collect onto ans those members of fns used as functions in term.
; If ffnnamesp returns non-nil, then this function returns the non-nil
; subset of fns responsible.

  (cond
   ((variablep term) ans)
   ((fquotep term) ans)
   ((flambda-applicationp term)
    (collect-ffnnames fns
                      (lambda-body (ffn-symb term))
                      (collect-ffnnames-lst
                       fns
                       (fargs term)
                       (if (member-equal (ffn-symb term) fns)
                           (add-to-set-equal (ffn-symb term) ans)
                           ans))))
   (t (collect-ffnnames-lst fns (fargs term)
                            (if (member-eq (ffn-symb term) fns)
                                (add-to-set-eq (ffn-symb term) ans)
                                ans)))))

(defun collect-ffnnames-lst (fns l ans)
  (cond ((null l) ans)
        (t (collect-ffnnames-lst fns (cdr l)
                                 (collect-ffnnames fns (car l) ans)))))

 )

(defun comm-equal (fn lhs rhs term)

; This function is equivalent to
; (or (equal `(,fn ,lhs ,rhs) term)
;     (equal `(,fn ,rhs ,lhs) term))

  (and (nvariablep term)
       (not (fquotep term))
       (eq fn (ffn-symb term))
       (if (equal rhs (fargn term 2))
           (equal lhs (fargn term 1))
         (and (equal rhs (fargn term 1))
              (equal lhs (fargn term 2))))))

(defun member-term2 (fn lhs rhs cl)

; We determine whether either `(,fn ,lhs ,rhs) or `(,fn ,rhs ,lhs) is
; a member of cl.

; Note on Nomenclature: This is a subroutine of member-term.  It ought
; to be named member-term1, but in symmetry with
; member-complement-term, we named it member-term2.  Member-equal
; plays the role of member-term1.

  (cond ((null cl) nil)
        ((comm-equal fn lhs rhs (car cl)) cl)
        (t (member-term2 fn lhs rhs (cdr cl)))))

(defun member-complement-term2 (fn lhs rhs cl)
  (cond ((null cl) nil)
        ((and (ffn-symb-p (car cl) 'not)
              (comm-equal fn lhs rhs (fargn (car cl) 1)))
         cl)
        (t (member-complement-term2 fn lhs rhs (cdr cl)))))

(defun member-complement-term1 (lit cl)

; Lit is known not to be an equality or iff.  This fn is equivalent to
; (member-equal `(not ,lit) cl).

  (cond ((null cl) nil)
        ((and (ffn-symb-p (car cl) 'not)
              (equal lit (fargn (car cl) 1)))
         cl)
        (t (member-complement-term1 lit (cdr cl)))))

(mutual-recursion

(defun member-term (lit cl)

; We determine whether lit is a member-equal of cl, except that if the
; atom of lit is an equality or iff term, we also look for its
; commuted version.

  (cond ((variablep lit) (member-eq lit cl))
        ((fquotep lit) (member-equal lit cl))
        ((or (eq (ffn-symb lit) 'equal)
             (eq (ffn-symb lit) 'iff))
         (member-term2 (ffn-symb lit) (fargn lit 1) (fargn lit 2) cl))
        ((eq (ffn-symb lit) 'not)
         (member-complement-term (fargn lit 1) cl))
        (t (member-equal lit cl))))

(defun member-complement-term (lit cl)

; We determine whether the complement of lit is a member-equal of cl,
; except that if the atom of lit is an equality or iff we recognize
; its commuted version.

  (cond ((variablep lit) (member-complement-term1 lit cl))
        ((fquotep lit) (member-complement-term1 lit cl))
        ((or (eq (ffn-symb lit) 'equal)
             (eq (ffn-symb lit) 'iff))
         (member-complement-term2 (ffn-symb lit) (fargn lit 1) (fargn lit 2)
                                  cl))
        (t

; Before Version_8.4, in the case (eq (ffn-symb lit) 'not), we only checked
; (member-term (fargn lit 1) cl).  But we found a case where lit was of the
; form (not u) and cl contains (not (not u)), and we want to catch that case,
; too.  This problem was evidenced as follows; after the fix, we get a more
; appropriate result (NIL NIL).

;   ACL2 !>(GUARD-CLAUSES '(FLOOR X Y)
;                          NIL T
;                          '((NOT (RATIONALP X))
;                            (NOT (RATIONALP Y))
;                            (NOT (NOT (EQL Y '0))))
;                          (w state) NIL 'NEWV)
;   ((((NOT (NOT (EQL Y '0)))
;      (NOT (RATIONALP Y))
;      (NOT (RATIONALP X))
;      (NOT (EQL Y '0))))
;    NIL)
;   ACL2 !>

; The term (NOT (NOT (EQL Y '0))) arises from clausify, specifically from a
; call of call-stack under if-interp.  A long comment in call-stack explains
; why we return (list 'not x), but not "simplify (not (not x)) to x".

         (or (and (eq (ffn-symb lit) 'not)
                  (member-term (fargn lit 1) cl))
             (member-complement-term1 lit cl)))))

)

(defun instr-listp (l)
  (cond ((atom l)
         (equal l nil))
        (t (and (or (integerp (car l))
                    (let ((carl (car l)))
                      (case-match carl
                                  (('push . x)
                                   (pseudo-termp x))
                                  (('push-local . n)
                                   (integerp n))
                                  (('push-frame-ptr) t)
                                  (('go . x) (integerp x))
                                  (('test . x) (integerp x))
                                  (('call . term)
                                   (pseudo-termp term))
                                  (('ret . lst)
                                   (pseudo-term-listp lst)))))
                (instr-listp (cdr l))))))

(defun spliced-instr-listp (l)
  (cond ((atom l)
         (equal l nil))
        (t (and (let ((carl (car l)))
                  (case-match carl
                              (('push . x)
                               (pseudo-termp x))
                              (('push-local . n)
                               (integerp n))
                              (('push-frame-ptr) t)
                              (('test . x)
                               (spliced-instr-listp x))
                              (('call . term)
                               (pseudo-termp term))
                              (('ret . lst)
                               (pseudo-term-listp lst))))
                (spliced-instr-listp (cdr l))))))

(defun next-tag (l)
  (declare (xargs :guard (instr-listp l)))
  (cond ((null l) 1)
        ((and (consp (car l))
              (eq (caar l) 'test))
         (+ 2 (cdr (car l))))
        (t (next-tag (cdr l)))))

(defun if-compile-formal (var rformals i)
  (declare (xargs :guard (and (symbolp var)
                              (true-listp rformals)
                              (member-eq var rformals))))
  (cond ((eq var (car rformals)) i)
        (t (if-compile-formal var (cdr rformals) (1+ i)))))

; Rockwell Addition: Repeatedly in this new code we will be concerned
; with the question of whether we look inside of lambdas or not.  Many
; functions have an additional lambda-exp arg, telling them whether to
; go inside lambda applications.  These extra args will show up in a
; window comparison but aren't commented upon henceforth.

(mutual-recursion

(defun ffnnamep-hide (fn term lambda-exp)

; We determine whether the function fn (possibly a lambda-expression)
; is used as a function in term, without diving inside calls of HIDE.
; If lambda-exp is t we look inside of lambda bodies.  Otherwise we
; don't.

  (cond ((variablep term) nil)
        ((fquotep term) nil)
        ((flambda-applicationp term)
         (or (equal fn (ffn-symb term))
             (and lambda-exp
                  (ffnnamep-hide fn (lambda-body (ffn-symb term))
                                 lambda-exp))
             (ffnnamep-hide-lst fn (fargs term) lambda-exp)))
        ((eq (ffn-symb term) fn) t)
        ((eq (ffn-symb term) 'hide) nil)
        (t (ffnnamep-hide-lst fn (fargs term) lambda-exp))))

(defun ffnnamep-hide-lst (fn l lambda-exp)
  (declare (xargs :guard (and (symbolp fn)
                              (pseudo-term-listp l))))
  (if (null l)
      nil
    (or (ffnnamep-hide fn (car l) lambda-exp)
        (ffnnamep-hide-lst fn (cdr l) lambda-exp))))

)

(mutual-recursion

(defun if-compile (term lambda-exp ac rformals)

; We compile term.  If lambda-exp is t, we expand lambda applications.
; Otherwise, we don't.  Rformals is the list of formal parameters that
; occur in term.  It is nil outside of lambdas.  It MIGHT be nil
; inside of a lambda: ((lambda nil ...)).

; Here is the target language of our compiler:
; (push . term)      push term onto the stack.
; (push-local . n)   push the nth local onto the stack, where we
;                    enumerate the locals 0-based, starting from
;                    the right-most!  That is, in the compiled
;                    code for body in
;                    ((lambda (x y z) body) a b c)
;                    z is the 0th local, y is the 1st, and x is the
;                    2nd.
; (push-frame-ptr)   the current stack represents a complete frame;
;                    think of this as marking this point on the stack
;                    so that (push-local . n) fetches from here, offset
;                    back by n.
; (go . n)           transfer control to the instruction labeled n
; (test . n)         pop and test the top of the stack and if nil,
;                    transfer control to the instruction labeled n,
;                    else execute the next instruction.
; (call fn . lst)    Lst is a list that is completely irrelevant
;                    except for its length, n.  Pop n things off
;                    the stack, apply fn to them (top-most item
;                    on the stack being the last arg to fn), and
;                    push the result.
; (ret . lst)        Lst is a list that is irrelevant except for
;                    its length, n.  Pop one value off the stack and
;                    hold it as the returned value of the lambda
;                    expression just evaluated, then pop n things
;                    off the stack, clearing the most recent frame,
;                    and finally push the returned value.

  (declare (xargs :guard (pseudo-termp term)))
  (cond ((variablep term)

; Note:  What if rformals is nil?  Then we couldn't have hit a variable
; and we aren't in a lambda.

         (cond (rformals
                (cons (cons 'push-local (if-compile-formal term rformals 0))
                      ac))
               (t (cons (cons 'push term) ac))))
        ((or (fquotep term)
             (eq (ffn-symb term) 'hide))
         (cons (cons 'push term) ac))
        ((flambdap (ffn-symb term))

; This is a lambda application.  If we are supposed to expand lambdas
; and there is an IF inside the body of this one, we compile the body.
; Otherwise we treat it the same way we do ordinary function symbol
; applications.

         (cond
          ((and lambda-exp
                (ffnnamep-hide 'if (lambda-body (ffn-symb term)) lambda-exp))
           (cons (cons 'ret (lambda-formals (ffn-symb term)))
                 (if-compile (lambda-body (ffn-symb term))
                             lambda-exp
                             (cons '(push-frame-ptr)
                                   (if-compile-lst (fargs term)
                                                   lambda-exp ac rformals))
                             (revappend (lambda-formals (ffn-symb term))
                                        nil))))
          ((or (ffnnamep-hide-lst 'if (fargs term) lambda-exp)
               rformals)
           (cons (cons 'call term)
                 (if-compile-lst (fargs term)
                                 lambda-exp ac rformals)))
          (t (cons (cons 'push term) ac))))
        ((eq (ffn-symb term) 'if)
         (let* ((test-seg (if-compile (fargn term 1)
                                      lambda-exp ac rformals))
                (n (next-tag test-seg)))
           (cons (+ n 1)
                 (if-compile (fargn term 3)
                             lambda-exp
                             (cons n (cons (cons 'go (+ n 1))
                                           (if-compile (fargn term 2)
                                                       lambda-exp
                                                       (cons (cons 'test n)
                                                             test-seg)
                                                       rformals)))
                             rformals))))
        ((or (ffnnamep-hide-lst 'if (fargs term) lambda-exp)
             rformals)

; If there is an IF in some arg, we compile the args to get rid of the
; IFs.  Alternatively, if we are compiling a lambda body (with
; rformals), we must compile the args to deref them via the stack.

         (cons (cons 'call term)
               (if-compile-lst (fargs term)
                               lambda-exp ac rformals)))
        (t (cons (cons 'push term) ac))))

(defun if-compile-lst (l lambda-exp ac rformals)
  (declare (xargs :guard (pseudo-term-listp l)))
  (cond ((null l) ac)
        (t (if-compile-lst (cdr l)
                           lambda-exp
                           (if-compile (car l) lambda-exp ac rformals)
                           rformals))))

)

; The following code is a little weird.  We implement a data structure called
; "assumptions" for representing assumed terms.  In particular, we can add to
; the data structure to assume a term true and then we can quickly convert that
; structure to one in which the term is assumed false.  The pair of these
; assumptions always costs exactly two conses, total: either the first costs 1
; cons and the next does also, or the first costs 2 and the next is free.  Our
; representation of assumptions relies upon the fact that the keywords :NOT and
; :IGNORE-WHEN-CONVERTING-TO-CLAUSE are not legal variable symbols.  Our
; machinery for manipulating assumptions also exploits the fact that we never
; assume a quoted term -- we simply decide the issue.  Thus, (nvariablep x)
; means (ffn-symb x) is a function symbol or lambda expression.

; To assume an atm true, we add it to the list (one cons).  To assume an atom
; false, we add it to the list and then add :NOT in front of it (two conses).
; To negate the last assumption you either add a :NOT (one cons) or delete a
; :NOT (no conses).  The element :IGNORE-WHEN-CONVERTING-TO-CLAUSE plays no
; special role in determining the value of an atom -- it looks like a variable
; symbol assumed true.  We never "negate" it though!  That is, the process of
; "negating the last assumption" must be done in a disciplined way in which you
; negate an assumption that you were responsible for adding in the first place.

; Below we first write the function for recovering from this structure the
; assumed value of a term, getting the answer t (for assumed true), 'f (for
; assumed false) or nil (for unassumed).  Like member-term and
; member-complement-term this recovering process knows about the commutativity
; of equal and iff.  But this is faster than those two, both because
; assumptions cost fewer conses and because we get the answer to the question
; "is it assumed and if so which way?" in the same time we can use member-term
; or member-complement-term to get only half the answer.

; Then we write the function for converting an assumptions structure into a
; clause.  All assumptions after the :IGNORE-WHEN-CONVERTING-TO-CLAUSE marker
; are ignored during the process.  Thus, it is possible to load into an initial
; assumption a bunch of literals that will be known true or false appropriately
; during the clausification process but which will not be transferred into the
; answer clauses produced.

; Finally we write the function that converts a clause into an initial set of
; assumptions, marked :IGNORE-WHEN-CONVERTING-TO-CLAUSE.

; All of this is in support of our fast clausifier.  The whole idea, here
; exposed at the very end of this long comment, is to make it fast to explore
; and recognize tautologies, paying the price for creating the clause only when
; we have to.

(defun if-interp-assume-true (not-flg term assumptions)

; Adds the assumption that term is true/false according to whether
; not-flg is nil/t.  Thus, to assume term true, use not-flg nil.
; These assumptions must be used in a propositional setting.  That is,
; if p is assumed true in assumptions then (if-interp-assumed-value p
; assumption) will be t, but this doesn't mean that p equals t, it
; means (iff p t).  Note that term should not be a quotep.

  (cond ((variablep term)
         (if not-flg
             (cons :not (cons term assumptions))
           (cons term assumptions)))
        ((eq (ffn-symb term) 'not)
         (if-interp-assume-true (not not-flg) (fargn term 1) assumptions))
        (t
         (if not-flg
             (cons :not (cons term assumptions))
           (cons term assumptions)))))

(defun if-interp-switch (assumptions)

; Converts assumptions to the opposite parity on the most recent
; assumption.  I.e., if assumptions was created by assuming term true,
; the after this switch, the assumptions assume term false.

  (cond ((eq (car assumptions) :not) (cdr assumptions))
        (t (cons :not assumptions))))

; We now start the development of the lookup functions.  See
; if-interp-assumed-value for the top-level function.  All the others
; are just subroutines of that one.

(defun if-interp-assumed-value0 (var assumptions)

; Look up the assumed value of a variable symbol.

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (cond ((eq var (cadr assumptions)) 'f)
               (t (if-interp-assumed-value0 var (cddr assumptions)))))
        ((eq (car assumptions) var) 't)
        (t (if-interp-assumed-value0 var (cdr assumptions)))))

(defun if-interp-assumed-value1 (term assumptions)

; Look up the assumed value of an arbitrary non-NOT term -- i.e., just
; like the variable case but using equal instead of eq to compare.

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (cond ((equal term (cadr assumptions)) 'f)
               (t (if-interp-assumed-value1 term (cddr assumptions)))))
        ((equal (car assumptions) term) 't)
        (t (if-interp-assumed-value1 term (cdr assumptions)))))

(defun if-interp-assumed-value2-equal-constant (arg const1 assumptions)

; This function is an optimization of if-interp-assumed-value2, which looks up
; the assumed value of an EQUAL or IFF term.  However, here, we know the term
; is of the form (EQUAL arg const1), where const1 is a quoted constant.  The
; key difference between this situation and the more general one is that if
; assumptions contains (EQUAL arg const2), where const2 is different from
; const1, we know the answer is 'f.

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (let ((term (cadr assumptions)))
           (cond
            ((variablep term)
             (if-interp-assumed-value2-equal-constant arg const1 (cddr assumptions)))
            ((and (eq 'EQUAL (ffn-symb term))
                  (or (and (equal arg (fargn term 1))
                           (equal const1 (fargn term 2)))
                      (and (equal arg (fargn term 2))
                           (equal const1 (fargn term 1)))))
             'f)
            (t (if-interp-assumed-value2-equal-constant arg const1 (cddr assumptions))))))
        (t (let ((term (car assumptions)))
             (cond
              ((variablep term)
               (if-interp-assumed-value2-equal-constant arg const1 (cdr assumptions)))
              (t (let ((term-fn (ffn-symb term)))

; Term-fn is either a function symbol or a lambda expression.

                   (cond
                    ((eq term-fn 'EQUAL)
                     (cond
                      ((or (and (equal arg (fargn term 1))
                                (equal const1 (fargn term 2)))
                           (and (equal arg (fargn term 2))
                                (equal const1 (fargn term 1))))
                       't)
                      ((or (and (equal arg (fargn term 1))
                                (quotep (fargn term 2))
                                (not (equal const1 (fargn term 2))))
                           (and (equal arg (fargn term 2))
                                (quotep (fargn term 1))
                                (not (equal const1 (fargn term 1)))))
                       'f)
                      (t (if-interp-assumed-value2-equal-constant arg const1
                                                                  (cdr assumptions)))))
                    (t (if-interp-assumed-value2-equal-constant arg const1
                                                                (cdr assumptions)))))))))))

(defun if-interp-assumed-value2 (fn arg1 arg2 assumptions)

; Look up the assumed value of (fn arg1 arg2), where fn is a function
; symbol (e.g., EQUAL or IFF) that is known to be commutative.  This is
; like (or (if-interp-assumed-value1 `(,fn ,arg1 ,arg2) assumptions)
;          (if-interp-assumed-value1 `(,fn ,arg2 ,arg1) assumptions)).

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (let ((term (cadr assumptions)))
           (cond
            ((variablep term)
             (if-interp-assumed-value2 fn arg1 arg2 (cddr assumptions)))
            ((and (eq fn (ffn-symb term))
                  (or (and (equal arg1 (fargn term 1))
                           (equal arg2 (fargn term 2)))
                      (and (equal arg1 (fargn term 2))
                           (equal arg2 (fargn term 1)))))
             'f)
            (t (if-interp-assumed-value2 fn arg1 arg2 (cddr assumptions))))))
        ((let* ((term (car assumptions))
                (term-fn (and (nvariablep term)
                              (ffn-symb term))))

; Term-fn is either nil (in case term is a variable), or else a function symbol
; or a lambda expression.  Once upon a time, the (and (nvariablep term) ...)
; above included the conjunct (not (fquotep term)).  That is unnecessary.  If
; (nvariablep term), then we know (ffn-symb term) is a function symbol or
; lambda expression.  Thus, term could not be a quotep.

           (and (eq fn term-fn) ;nil is not a function symbol
                (or (and (equal arg1 (fargn term 1))
                         (equal arg2 (fargn term 2)))
                    (and (equal arg1 (fargn term 2))
                         (equal arg2 (fargn term 1))))))
         't)
        (t (if-interp-assumed-value2 fn arg1 arg2 (cdr assumptions)))))

(defun if-interp-assumed-value3 (term assumptions)

; Look up the assumed value of an arbitrary non-NOT (RATIONALP x) term.
; This function is very similar to if-interp-assumed-value1 except that
; if we find (INTEGERP x) assumed true, we know (RATIONALP x) is true.

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (cond ((equal term (cadr assumptions)) 'f)
               (t (if-interp-assumed-value3 term (cddr assumptions)))))
        ((equal (car assumptions) term) 't)
        ((and (ffn-symb-p (car assumptions) 'INTEGERP)
              (equal (fargn term 1) (fargn (car assumptions) 1)))
         't)
        (t (if-interp-assumed-value3 term (cdr assumptions)))))

(defun if-interp-assumed-value4 (term assumptions)

; Look up the assumed value of an arbitrary non-NOT (INTEGERP x) term.
; This function is very similar to if-interp-assumed-value1 except that
; if we find (RATIONALP x) assumed false, we know (INTEGERP x) is false.

  (cond ((null assumptions) nil)
        ((eq (car assumptions) :not)
         (cond ((equal term (cadr assumptions)) 'f)
               ((and (ffn-symb-p (cadr assumptions) 'RATIONALP)
                     (equal (fargn term 1) (fargn (cadr assumptions) 1)))
                'f)
               (t (if-interp-assumed-value4 term (cddr assumptions)))))
        ((equal (car assumptions) term) 't)
        (t (if-interp-assumed-value4 term (cdr assumptions)))))

(defun if-interp-assumed-value-x (term assumptions)

; Look up the assumed value of an arbitrary non-NOT term, treating
; EQUAL and IFF as commutative and recognizing that INTEGERP
; implies RATIONALP.

  (cond ((variablep term)
         (if-interp-assumed-value0 term assumptions))
        ((eq (ffn-symb term) 'EQUAL)
         (cond
          ((quotep (fargn term 1))
           (if-interp-assumed-value2-equal-constant (fargn term 2)
                                                    (fargn term 1)
                                                    assumptions))
          ((quotep (fargn term 2))
           (if-interp-assumed-value2-equal-constant (fargn term 1)
                                                    (fargn term 2)
                                                    assumptions))
          (t (if-interp-assumed-value2 (ffn-symb term)
                                       (fargn term 1)
                                       (fargn term 2)
                                       assumptions))))
        ((eq (ffn-symb term) 'IFF)
         (if-interp-assumed-value2 (ffn-symb term)
                                   (fargn term 1)
                                   (fargn term 2)
                                   assumptions))
        ((eq (ffn-symb term) 'RATIONALP)
         (if-interp-assumed-value3 term assumptions))
        ((eq (ffn-symb term) 'INTEGERP)
         (if-interp-assumed-value4 term assumptions))
        (t (if-interp-assumed-value1 term assumptions))))

(defun if-interp-assumed-value (term assumptions)

; Look up the assumed value of an arbitrary term, treating EQUAL and
; IFF as commutative.  This function returns t, f, or nil.  The last
; means that no assumptions about term are available.  The other
; indicate that term has been assumed true or false, respectively.
; Note that a value of t does not mean (EQUAL term T) but (IFF term
; T), under the assumptions.

  (cond ((variablep term)
         (if-interp-assumed-value0 term assumptions))
        ((eq (ffn-symb term) 'NOT)
         (let ((temp (if-interp-assumed-value-x (fargn term 1) assumptions)))
           (cond ((eq temp t) 'f)
                 ((eq temp 'f) t)
                 (t nil))))
        (t (if-interp-assumed-value-x term assumptions))))

(defun convert-assumptions-to-clause-segment (assumptions ans known-constants)

; We convert an assumptions structure to a clause segment, a list of disjoined
; literals to use as the hypothesis.  Assumptions represents a conjunction of
; assumptions.  E.g., (A :NOT B C D) represents (AND A (NOT B) C D).  Observe
; that this is the same as (NOT (OR (NOT A) B (NOT C) (NOT D))).  Thus, the
; clause segment is ((NOT A) B (NOT C) (NOT D)).  We reverse it as we create
; it.  When we get to the special marker :ignore-when-converting-to-clause we
; stop and act as though assumptions were nil.  This allows us to load up
; assumptions with some initial implicit literals that do not get transferred
; into the clauses we generate.

; We implement the optimization that if one of our assumptions is
; (EQUAL x 'const1) then any subsequent (NOT (EQUAL x 'const2)) is T and
; can be omitted, where const1 and const2 are different constants.
; That is, if assumptions is
; ((EQUAL x 'const1) :NOT (equal x 'const2) P Q)
; we return
; ((NOT (EQUAL x 'const1)) (NOT P) (NOT Q))
; instead of
; ((NOT (EQUAL x 'const1)) (EQUAL x 'const2) (NOT P) (NOT Q)).
; (Actually, our answer is reversed.)

; We always know that the positive equality precedes the negative one in
; the input assumptions.  That is, we will never see
; (:NOT (equal x 'const2) (EQUAL x 'const1) P Q)
; as our assumptions.  The reason is that if (EQUAL x 'const1) is already
; assumed, then when if-interp gets the value of (equal x 'const2) under the
; assumptions it will come back 'f.

; Thus, whenever we see a positive equality with a constant, (EQUAL x 'const1), we
; add the pair (x . const1) onto known-constants.  Whenever we see a negative
; equality with a constant, we ask if we know what the value is.

  (cond ((or (null assumptions)
             (eq (car assumptions) :ignore-when-converting-to-clause))
         ans)
        ((eq (car assumptions) :not)
         (let ((test (cadr assumptions)))

; Everything in the first branch of the cond below is devoted to the optimization
; of (NOT (EQUAL x 'const2)) when x is known to be a different 'const1.  To see
; the simple case of this function, skip to the T clause of this cond.

           (cond ((and (ffn-symb-p test 'equal)
                       (or (quotep (fargn test 1))
                           (quotep (fargn test 2))))
                  (cond ((quotep (fargn test 1))
                         (let* ((x (fargn test 2))
                                (const2 (fargn test 1))
                                (temp (assoc-equal x known-constants)))

; We are processing (NOT (EQUAL x const2)), where const2 is a quoted constant.
; If x is bound on known-constants to a different object, this assumption is
; trivially T and can be omitted from our answer.

                           (cond ((and temp
                                       (not (equal const2 (cdr temp))))
                                  (convert-assumptions-to-clause-segment
                                   (cddr assumptions)
                                   ans
                                   known-constants))
                                 (t (convert-assumptions-to-clause-segment
                                     (cddr assumptions)
                                     (cons test ans)
                                     known-constants)))))
                        ((quotep (fargn test 2))
                         (let* ((x (fargn test 1))
                                (const2 (fargn test 2))
                                (temp (assoc-equal x known-constants)))

; We are processing (NOT (EQUAL x const2)), where const2 is a quoted constant.
; If x is bound on known-constants to a different object, this assumption is
; trivially T and can be omitted from our answer.

                           (cond ((and temp
                                       (not (equal const2 (cdr temp))))
                                  (convert-assumptions-to-clause-segment
                                   (cddr assumptions)
                                   ans
                                   known-constants))
                                 (t (convert-assumptions-to-clause-segment
                                     (cddr assumptions)
                                     (cons test ans)
                                     known-constants)))))
                        (t (convert-assumptions-to-clause-segment
                            (cddr assumptions)
                            (cons test ans)
                            known-constants))))
                 (t
                  (convert-assumptions-to-clause-segment
                   (cddr assumptions)
                   (cons test ans)
                   known-constants)))))
        (t
         (let ((test (car assumptions)))
           (cond ((and (ffn-symb-p test 'equal)
                       (or (quotep (fargn test 1))
                           (quotep (fargn test 2))))
                  (cond
                   ((quotep (fargn test 1))
                    (convert-assumptions-to-clause-segment
                     (cdr assumptions)
                     (cons (list 'not test) ans)
                     (cons (cons (fargn test 2) (fargn test 1))
                           known-constants)))
                   ((quotep (fargn test 2))
                    (convert-assumptions-to-clause-segment
                     (cdr assumptions)
                     (cons (list 'not test) ans)
                     (cons (cons (fargn test 1) (fargn test 2))
                           known-constants)))
                   (t (convert-assumptions-to-clause-segment
                       (cdr assumptions)
                       (cons (list 'not test) ans)
                       known-constants))))
                 (t (convert-assumptions-to-clause-segment
                     (cdr assumptions)
                     (cons (list 'not test) ans)
                     known-constants)))))))

(defun convert-clause-to-assumptions (clause ans)

; The falsity of each literal in clause is encoded into our assumptions format.
; We then cover the entire list of assumptions with the mark
; :ignore-when-converting-to-clause.  The function if-interp-assumed-value
; properly recovers from these assumptions the values of the literals assumed
; false here.  The :ignore-when-converting-to-clause marker is innocuous since
; it looks like a variable assumed true, but we will never ask about a keyword
; "variable".  As if-interp explores its term to construct clauses it will
; extend our assumptions and if-interp-assumed-value continues to recover
; values of new and old assumptions.  But when if-interp finally builds a
; clause from assumptions, it ignores the ones stemming from clause.

  (cond ((null clause)
         (cons :ignore-when-converting-to-clause ans))
        (t (convert-clause-to-assumptions
            (cdr clause)
            (if-interp-assume-true t (car clause) ans)))))

; Rockwell Addition: Minor change.  We used to create the instantiation
; sublis-var.  Now I chase vars.

(defun simplifiable-mv-nth1 (n cons-term alist)

; N is a natural number.  If cons-term/alist is of the form (cons v0 ... (cons
; vn ...)), we return (mv vn rewritep), where rewritep is a flag indicating
; whether vn is an already-rewritten term extracted from the alist (nil), or a
; term that still needs to be rewritten with respect to the alist (t).  We
; return (mv nil nil) if we do not like what we see.

  (cond ((variablep cons-term)
         (let ((temp (assoc-eq cons-term alist)))
           (cond (temp (mv-let (term1 rewritep)
                         (simplifiable-mv-nth1 n (cdr temp) nil)
                         (declare (ignore rewritep))

; The rewritep returned by this call is t if a term was returned, because alist
; = nil.  But since (cdr temp) has already been rewritten, so has term1 (if
; non-nil); so we return rewritep = nil.  The use of rewritep in the definition
; of rewrite, where simplifiable-mv-nth is called, is a change after
; Version_8.2.  At one time we always rewrote the new term (called term1 here),
; but Sol Swords noticed that such double rewriting can be very expensive.

                         (mv term1 nil)))
                 (t (mv nil nil)))))
        ((fquotep cons-term)

; If the guts of this quote is a true-list of sufficient length, we
; return the correct answer.  Otherwise, we indicate that we cannot
; determine the value.  We could, always, determine the value in this
; case, but we are lazy and there seems little point.

         (cond ((and (true-listp (cadr cons-term))
                     (> (length (cadr cons-term)) n))
                (mv (kwote (nth n (cadr cons-term)))

; We could perhaps return nil here, but instead we return t so that this quotep
; result is handled in the usual way by rewrite -- at this writing, it is
; returned unchanged -- rather than passing it to rewrite-solidify-plus.

                    t))
               (t (mv nil nil))))
        ((eq (ffn-symb cons-term) 'cons)
         (if (= n 0)
             (mv (fargn cons-term 1) t)
           (simplifiable-mv-nth1 (1- n) (fargn cons-term 2) alist)))
        (t (mv nil nil))))

(defstub simplifiable-mv-nth-p () t)
(defattach simplifiable-mv-nth-p constant-t-function-arity-0)

(defun simplifiable-mv-nth (term alist)

; Term must be of the form (mv-nth & &), i.e., the ffn-symb of term is known to
; be 'mv-nth.  We determine whether we can simplify this and if so we return
; (mv term' rewritep) as the simplification.  If we cannot, we return (mv nil
; nil).  We look for (mv-nth 'i (cons v1 ... (cons vi ...))), but we allow the
; two arguments of term to be variable symbols that are looked up.  That is, we
; allow (MV-NTH I V) where I is bound in alist to a quoted constant and V is
; bound to a CONS term.  The second value, rewritep, is T unless the second
; argument to the mv-nth was a variable, in which case it is NIL to indicate
; that the resulting term has already been rewritten and should not be
; rewritten again.

  (cond ((simplifiable-mv-nth-p)
         (let ((arg1 (cond ((variablep (fargn term 1))
                            (let ((temp (assoc-eq (fargn term 1) alist)))
                              (cond (temp (cdr temp))
                                    (t (fargn term 1)))))
                           (t (fargn term 1)))))
           (cond ((and (quotep arg1)
                       (integerp (cadr arg1))
                       (>= (cadr arg1) 0))
                  (simplifiable-mv-nth1 (cadr arg1) (fargn term 2) alist))
                 (t (mv nil nil)))))
        (t (mv nil nil))))

(defun call-stack (fn lst stack assumptions ac)
  (declare (xargs :guard (and (true-listp lst)
                              (true-listp stack)
                              (>= (length stack) (length lst)))))
  (cond ((null lst)
         (cons (cond
                ((eq fn 'not)
                 (let ((x (car ac)))
                   (cond
                    ((quotep x)
                     (if (eq (cadr x) nil)
                         *t*
                       *nil*))
                    (t (let ((temp (if-interp-assumed-value x
                                                            assumptions)))
                         (cond ((eq temp t) *nil*)
                               ((eq temp 'f) *t*)
;                              ((variablep x) (list 'not x))

; Note: In Version_2.7 it was noticed by Qiang Zhang that there was an
; unsoundness which we traced to the two lines commented out below.  This
; unsoundness goes fairly far back into the history of ACL2 and allowed us to
; prove (equal (and p q) (not (or (not p) (not q)))).  If it is found important
; to simplify (not (not x)) to x, as is done here, it will be necessary to
; determine whether we are in a propositional context, e.g., IFF-FLG = T or
; geneqv = *geneqv-iff*.  But we have no such contextual information in the
; compiled code being traversed by if-interp.  It would be necessary to change
; the if-compile to insert some kind of iff-flg into the instructions generated
; to code the fact that this value is destined to be used in a propositional
; way.  If we restore the lines below, then we will need to restore the line
; commented out above (with the variablep test).

;                              ((eq (ffn-symb x) 'not)
;                               (fargn x 1))

                               (t (list 'not x))))))))
                ((eq fn 'equal)
                 (cond
                  ((equal (car ac) (cadr ac))
                   *t*)
                  ((and (quotep (car ac))
                        (quotep (cadr ac)))
                   *nil*)
                  ((and (equal (car ac) *t*)
                        (ffn-symb-p (cadr ac) 'equal))

; Note:  (equal t (equal a b)) = (equal a b).

                   (cadr ac))
                  ((and (equal (cadr ac) *t*)
                        (ffn-symb-p (car ac) 'equal))
                   (car ac))
                  (t (fcons-term fn ac))))

; Rockwell Addition: Now during clausification we know that (< x x) is nil and
; (< 'i 'j) can be decided when i and j are rationals.

                ((eq fn '<)
                 (cond
                  ((equal (car ac) (cadr ac))
                   *nil*)
                  ((and (quotep (car ac))
                        (quotep (cadr ac))
                        (rationalp (cadr (car ac)))
                        (rationalp (cadr (cadr ac))))
                   (if (< (cadr (car ac)) (cadr (cadr ac)))
                       *t*
                     *nil*))
                  (t (cons-term fn ac))))
                ((eq fn 'iff)
                 (let ((arg1 (car ac))
                       (arg2 (cadr ac)))
                   (cond
                    ((equal arg1 arg2)
                     *t*)
                    (t (let ((temp1 (if (quotep arg1)
                                        (if (eq (cadr arg1) nil)
                                            'f
                                          t)
                                      (if-interp-assumed-value arg1 assumptions)))
                             (temp2 (if (quotep arg2)
                                        (if (eq (cadr arg2) nil)
                                            'f
                                          t)
                                      (if-interp-assumed-value arg2 assumptions))))
                         (cond ((and temp1
                                     temp2)
                                (if (eq temp1 temp2)
                                    *t*
                                  *nil*))

; There is a temptation here to simplify (iff t x) to x, which preserves iff
; but not equal.  But this call of IFF might be in a equal-preserving slot,
; e.g., (CONS (IFF T (IF A X Y)) TL).

                               (t (fcons-term fn ac))))))))
                ((eq fn 'mv-nth)

; This optimization of clausify is slightly tainted by the fact that it is
; using the definition of mv-nth without reporting it in a ttree (there is no
; ttree).

                 (let ((term (fcons-term fn ac)))
                   (mv-let (term1 rewritep)
                     (simplifiable-mv-nth term nil)
                     (declare (ignore rewritep))
                     (or term1 term))))
                (t (cons-term fn ac)))
               stack))
        (t (call-stack fn (cdr lst) (cdr stack)
                       assumptions
                       (cons (car stack) ac)))))

(defun ret-stack (lst stack)
  (cond ((null lst) stack)
        (t (ret-stack (cdr lst) (cdr stack)))))

(defun extra-info-lit-p (lit)
  (and (ffn-symb-p lit 'not)
       (let ((atm (fargn lit 1)))
         (and (nvariablep atm)
              (eq (ffn-symb atm) *extra-info-fn*)))))

(defun subsetp-equal-mod-extra-info-lits (x y)
  (declare (xargs :guard (and (true-listp y)
                              (true-listp x))))
  (cond ((endp x) t)
        ((or (extra-info-lit-p (car x))
             (member-equal (car x) y))
         (subsetp-equal-mod-extra-info-lits (cdr x) y))
        (t nil)))

(defun quick-and-dirty-subsumption-replacement-step1 (cl1 cl2)
  (cond ((null cl1) 'subsumed2)
        ((extra-info-lit-p (car cl1))
         (quick-and-dirty-subsumption-replacement-step1 (cdr cl1) cl2))
        ((null cl2) 'subsumed1)
        ((extra-info-lit-p (car cl2))
         (quick-and-dirty-subsumption-replacement-step1 cl1 (cdr cl2)))
        ((equal (car cl1) (car cl2))
         (let ((ans (quick-and-dirty-subsumption-replacement-step1 (cdr cl1) (cdr cl2))))
           (cond ((symbolp ans)

; Experiments show that (symbolp ans) is marginally faster than (or (null ans)
; (eq ans 'subsumed2) (eq ans 'subsumed1)).

                  ans)
                 (t (cons (car cl1) ans)))))
        ((and (complementaryp (car cl1) (car cl2))
              (subsetp-equal-mod-extra-info-lits (cdr cl1) (cdr cl2)))
         (cdr cl2))
        (t nil)))

(defun quick-and-dirty-subsumption-replacement-step (cl1 lst)

; Aka The Satriani Hack (Note on the Derivation of the Name: The theme music of
; this exercise was Joe Satriani's "Motorcycle Driver" on The Extremist album.
; That track was not just what I was listening to while this code was written;
; the structure of the music sort of inspired the code.  The music starts out
; boringly repetitive and "slow."  A fairly decent guitar solo at 2:02 doesn't
; do the job, in the sense that after this attempted speedup the plodding drums
; still dominate and the repetitive theme reemerges.  But then, at 3:33 the
; guitar, spewing frustration, breaks out into a really wild solo that persists
; into the next reoccurrence of the theme and ends the song.  The sense I get
; while listening to that solo is that the guitarist simply abandoned the
; structure and did whatever it took.  That is the theme of the Satriani Hack,
; which actually is not localized here but involves little tweaks and patches
; in several places, to get the speedup I wanted.  JSM.)

; This function is akin to subsumption-replacement-loop except that it only
; takes one step and is much more limited in its detection of the
; subsumption/replacement conditions.  Let lst be a set of clauses we have to
; prove.  Imagine that we are going to add cl1 to that set.  If cl1 is subsumed
; by any clause in lst, we needn't add it.  Among other things, this function
; checks a limited form of that condition; if we return 'subsumed1 then cl1 is
; subsumed by some clause in lst.  Otherwise, suppose that cl1 can be resolved
; against some clause, cl2, of lst to produce a clause cl3 that subsumes cl2.
; We call this a "replacement resolution."  For example, suppose

; cl1 = {a b  c d   e}
; cl2 = {a b -c d f e g}
; cl3 = {a b    d f e g}

; Then when we add cl1 to the set of clauses to prove we can delete cl2 from
; the set and replace it with cl3.  In addition, if cl1 simply subsumes some
; cl2, we can delete cl2 from the set.  If this function does not return
; 'subsumed1 then it returns a new set of clauses in which some of those
; subsumed by cl1 have been deleted and some of those that participate in
; replacement resolution with cl1 have been appropriately replaced.  Thus, if
; this function does not return 'subsumed1 it is sound to add cl1 to the output
; of this function and attack that set of clauses.

; The "quick and dirty" part of this is that we do not consider all possible
; literals upon which to do replacement resolution but rather only consider
; resolving on the first literal in cl1 that differs from the corresponding
; literal of cl2, and we insist that the corresponding literal of cl2 be the
; required complement.  The "step" part comes from the fact that we don't
; consider every possible pair of cl1 and cl2 but only the about-to-be-added
; cl1 against the already added cl2s.

; This rather draconian restriction is judged heuristically important because
; of the order in which clauses are generated.  The motivating example was of
; the form

;     (clausify
;      '(not (if A
;                (if (if E1
;                        't
;                        (if E2
;                            't
;                            E3))
;                    B
;                    'nil)
;                'nil))
;      nil
;      t    ; or nil, no lambdas here.
;      (sr-limit (w state)))

; Before we added this quick and dirty test, we created
; {-a -e1         -b}
; {-a  e1 -e2     -b}
; {-a  e1  e2 -e3 -b}
; The general-purpose subsumption-replacement-loop would work this down to
; {-a -e1         -b}
; {-a     -e2     -b}
; {-a         -e3 -b}

; But that was slow because it considers all possible ways of resolving and
; subsuming.  After a couple of days of Satriani and some false starts, it was
; realized (in the shower, no less) that the clauses were probably generated in
; just the right order to let us detect this condition quickly on the fly.

; Another motivating example comes from clausifying the opened up version of
; (not (member x '(1 2 ... 128))).  This arises when the member term is used as
; a hypothesis.  The problem becomes:

; (clausify '(not (if e1 't (if e2 't (if e3 't ...(if e127 't e128)...))))
;           nil t (sr-limit (w state)))

; which is like the (if e1 ...) nest above.  In Nqthm the clausifier had
; special purpose rules for handling a negated disjunction, but that is harder
; in ACL2 because the compiled form of the term hides the negation.  But the
; Satriani hack takes care of it, by cleaning up the clause set locally as it
; is produced, leaving the quadratic general-purpose
; subsumption-replacement-loop with nothing to do.

; To see this hack in action, first define the function that maps
; the list of standard chars into the list of standard codes:

;     (defun make-standard-codes (lst)
;      (if (endp lst)
;          nil
;          (cons (char-code (car lst)) (make-standard-codes (cdr lst)))))

; and use it to define the appropriate constant

;     (defconst *standard-codes* (make-standard-codes *standard-chars*))

; Then prove

;     (thm (implies (member x *standard-chars*)
;                   (member (char-code x) *standard-codes*)))

; With the Satriani hack in place, the proof takes 3.87 seconds.  With the
; Satriani hack omitted, it takes 431.92 seconds!  (Note: to omit the Satriani
; hack from these sources redefine the function if-interp-add-clause below so
; that ans is bound to ac rather than to the call of
; quick-and-dirty-subsumption-replacement-step.)

  (cond
   ((null lst) nil)
   ((time-limit5-reached-p ; nil, or throws
     "Out of time in subsumption ~
      (quick-and-dirty-subsumption-replacement-step).")
    nil)
   (t (let ((cl3 (quick-and-dirty-subsumption-replacement-step1 cl1 (car lst))))
        (cond
         ((eq cl3 'subsumed1) 'subsumed1)
         (t (let ((ans
                   (quick-and-dirty-subsumption-replacement-step cl1
                                                                 (cdr lst))))
              (cond
               ((eq cl3 'subsumed2)
                ans)
               ((eq ans 'subsumed1) ans)
               ((null cl3)
                (cons (car lst) ans))
               (t (cons cl3 ans))))))))))

(defstub quick-and-dirty-srs (cl1 ac) t)

(defun quick-and-dirty-srs-builtin (cl1 ac)
  (declare (ignore cl1 ac)
           (xargs :mode :logic :guard t))
  t)

(defattach quick-and-dirty-srs quick-and-dirty-srs-builtin)

(defun if-interp-add-clause (assumptions cl ac pflg)

; This is how we add a new clause to if-interp's accumulator, ac.  The clause
; we add is the one recovered from the current assumptions, starting with the
; clause cl.  If pflg is t then the caller is not interested in the set of
; clauses but just whether the set is empty or not.  In that case, we return t
; if the set of clauses is non-empty and nil if it is empty.

  (cond
   (pflg t)
   (t
    (let ((cl1 (convert-assumptions-to-clause-segment assumptions cl nil)))
      (cond
       ((quick-and-dirty-srs cl1 ac)
        (let ((ans (quick-and-dirty-subsumption-replacement-step cl1 ac)))
          (cond ((eq ans 'subsumed1) ac)
                (t (cons cl1 ans)))))
       (t (cons cl1 ac)))))))

(defun if-interp (instrs stack frame-ptr-stack assumptions ac pflg)

; First consider the case that pflg is nil.  Then we return the set of clauses
; extracted from instrs, together with those already in ac.

; Otherwise pflg is a natural number, and we quit as soon as we know that there
; will be at least one clause.  When we so quit, we return t.  Otherwise we
; return pflg, which counts down as steps are taken.  Thus if we return 0, then
; there might or might not be at least one clause, but if we return a positive
; integer, then the term encoded in instrs is a tautology.

  (declare (type (or null #.*fixnat-type*) pflg))
  (cond ((null instrs)
         (let ((v (car stack)))
           (or (cond ((quotep v)
                      (cond ((equal v *nil*)
                             (if-interp-add-clause assumptions nil ac pflg))
                            (t ac)))
                     (t (let ((assumed-val (if-interp-assumed-value v assumptions)))
                          (cond ((eq assumed-val t) ac)
                                ((eq assumed-val 'f)
                                 (if-interp-add-clause assumptions nil ac pflg))
                                (t (if-interp-add-clause assumptions (list v) ac pflg))))))
               pflg)))
        ((and pflg (zpf pflg))
         0)
        (t (let ((caarinstrs (caar instrs))
                 (pflg (and pflg (1-f pflg))))
             (declare (type (or null #.*fixnat-type*) pflg))
             (case caarinstrs
               (push (if-interp (cdr instrs)
                                (cons (cdr (car instrs))
                                      stack)
                                frame-ptr-stack
                                assumptions
                                ac
                                pflg))
               (push-local (if-interp (cdr instrs)
                                      (cons (nth (cdr (car instrs))
                                                 (car frame-ptr-stack))
                                            stack)
                                      frame-ptr-stack
                                      assumptions
                                      ac
                                      pflg))
               (push-frame-ptr (if-interp (cdr instrs)
                                          stack
                                          (cons stack frame-ptr-stack)
                                          assumptions
                                          ac
                                          pflg))
               (ret (if-interp (cdr instrs)
                               (cons (car stack)
                                     (ret-stack (cdr (car instrs)) (cdr stack)))
                               (cdr frame-ptr-stack)
                               assumptions
                               ac
                               pflg))
               (call (if-interp (cdr instrs)
                                (call-stack (cadr (car instrs))
                                            (cddr (car instrs))
                                            stack
                                            assumptions
                                            nil)
                                frame-ptr-stack
                                assumptions
                                ac
                                pflg))
               (test (let* ((v (car stack))
                            (stack (cdr stack)))
                       (cond ((quotep v)
                              (cond ((equal v *nil*)
                                     (if-interp (cdr (car instrs))
                                                stack
                                                frame-ptr-stack
                                                assumptions
                                                ac
                                                pflg))
                                    (t (if-interp (cdr instrs)
                                                  stack
                                                  frame-ptr-stack
                                                  assumptions
                                                  ac
                                                  pflg))))
                             (t (let ((temp (if-interp-assumed-value
                                             v
                                             assumptions)))
                                  (cond
                                   ((eq temp 'f)
                                    (if-interp (cdr (car instrs))
                                               stack
                                               frame-ptr-stack
                                               assumptions
                                               ac
                                               pflg))
                                   ((eq temp t)
                                    (if-interp (cdr instrs)
                                               stack
                                               frame-ptr-stack
                                               assumptions
                                               ac
                                               pflg))
                                   (pflg
                                    (let ((assumptions
                                           (if-interp-assume-true
                                            nil
                                            v
                                            assumptions)))
                                      (let ((pflg (if-interp (cdr instrs)
                                                             stack
                                                             frame-ptr-stack
                                                             assumptions
                                                             ac
                                                             pflg)))
                                        (cond
                                         ((eq pflg t) t)
                                         (t (if-interp (cdr (car instrs))
                                                       stack
                                                       frame-ptr-stack
                                                       (if-interp-switch
                                                        assumptions)
                                                       ac
                                                       pflg))))))
                                   (t
                                    (let ((assumptions
                                           (if-interp-assume-true
                                            nil v assumptions)))
                                      (if-interp (cdr instrs)
                                                 stack
                                                 frame-ptr-stack
                                                 assumptions
                                                 (if-interp (cdr (car instrs))
                                                            stack
                                                            frame-ptr-stack
                                                            (if-interp-switch assumptions)
                                                            ac
                                                            pflg)
                                                 pflg))))))))))))))

(defun splice-instrs1 (instrs ans alist)
  (declare (xargs :guard (instr-listp instrs)))
  (cond ((null instrs)
         ans)
        ((atom (car instrs))
         (splice-instrs1 (cdr instrs)
                         ans
                         (cons (cons (car instrs)
                                     ans)
                               alist)))
        (t (let ((caarinstrs (caar instrs)))
             (case caarinstrs
                   ((push push-local push-frame-ptr call ret)
                    (splice-instrs1
                     (cdr instrs)
                     (cons (car instrs) ans)
                     alist))
                   (test
                    (splice-instrs1
                     (cdr instrs)
                     (cons (cons 'test
                                 (cdr (assoc (cdr (car instrs)) alist)))
                           ans)
                     alist))
                   (go
                    (splice-instrs1
                     (cdr instrs)
                     (cdr (assoc (cdr (car instrs)) alist))
                     alist)))))))

(defun splice-instrs (instrs)
  (declare (xargs :guard (instr-listp instrs)))
  (splice-instrs1 instrs nil nil))

(defun strip-branches (term assumptions lambda-exp)

; We return a set of clauses whose conjunction is equivalent to term in the context
; of the assumptions given.  See clausify.

  (declare (xargs :guard (pseudo-termp term)))
  (cond
   ((and (ffn-symb-p term 'if)
         (equal (fargn term 3) *nil*))

; Term is of the form (if p q 'nil).  We will strip the branches of each in
; isolation and union them together.  The original justification of this was
; so that when we clausify the translation of (and (implies p q) r) we get
; back two clauses, {~p q} and {r}.  Without this modification, we get back
; three clauses, {p r}, {~p q}, and {~q r}.  Except for here, strip-branches
; is not recursive and this special treatment of conjuncts is not done in
; other contexts.

    (union-equal
     (strip-branches (fargn term 1) assumptions lambda-exp)
     (strip-branches (fargn term 2) assumptions lambda-exp)))
   (t
    (if-interp (splice-instrs (if-compile term lambda-exp nil nil)) nil nil
               assumptions
               nil nil))))

(defun merge-length (l1 l2)
  (declare (xargs :guard (and (true-list-listp l1)
                              (true-list-listp l2))))
  (cond ((null l1) l2)
        ((null l2) l1)
        ((<= (length (car l1)) (length (car l2)))
         (cons (car l1) (merge-length (cdr l1) l2)))
        (t (cons (car l2) (merge-length l1 (cdr l2))))))

(defun merge-sort-length (l)
  (declare (xargs :guard (true-list-listp l)))
  (cond ((null (cdr l)) l)
        (t (merge-length (merge-sort-length (evens l))
                         (merge-sort-length (odds l))))))

(defun member-equal-+- (lit clause)

; We return '+ if lit is a member of clause.  We return '- if the complement of
; lit is a member of clause.  Otherwise we return nil.  If both conditions are
; met, we return either '+ or '- depending on which occurs first.  For example,
; let clause be '(A (NOT B)).  Then if lit is A we return '+.  If lit is (NOT
; A) we return '-.  We also return '- when lit is B.  If lit is C we return
; nil.

  (cond ((null clause) nil)
        ((equal lit (car clause)) '+)
        ((complementaryp lit (car clause)) '-)
        (t (member-equal-+- lit (cdr clause)))))

(defun arg1-almost-subsumes-arg2 (arg1 arg2)
  (declare (xargs :guard (and (pseudo-term-listp arg1)
                              (pseudo-term-listp arg2))))

; We are interested in ``throwing away,'' or at least shortening, the
; clause arg2.  We return 'subsumed, a cons, or nil.

; If the clause arg1 subsumes (i.e. is a subset of) arg2, then
; 'subsumed is returned.  This means we can ``throw away arg2'',
; because arg1 <-> (arg1 & arg2) since if arg1 is true, so is arg2,
; whereas if arg1 is false, so is the conjunction.

; If arg1 is a subset of arg2 except for one literal of arg1 which occurs
; complemented in arg2, we return a cons whose car is that literal.
; Note that the resolvent of arg1 and arg2 on this literal produces a
; clause that subsumes arg2:  the clause obtained by deleting the
; complement of the literal in question.

; Here is a more careful argument that we can delete the complement.
; If the subsumption fails but arg1 has the form {x} u arg1' (x not
; in arg1'), arg1' subsumes arg2, and -x occurs in arg2, then the
; tail of arg1 starting at x (which will be non-nil, of course) is
; returned.  In this case, we can REPLACE arg2 with arg2 - {-x},
; which has one less literal.  This replacement is justified by the
; fact that arg1 & arg2 <-> arg1 & (arg2 - {-x}).  Proof.  If arg1 is
; false, both sides are false.  If arg1 is true, then the equivalence
; reduces to arg2 <-> arg2 - {-x}.  But if arg1 is true, either x or
; arg1' is true.  If arg1' is true, then so is arg2 and arg2 - {-x}.
; On the other hand, if x is true, then -x is false, so the
; equivalence is the observation that we can throw out false
; disjuncts.

  (cond ((null arg1)
         'subsumed)
        ((extra-info-lit-p (car arg1))
         (arg1-almost-subsumes-arg2 (cdr arg1) arg2))
        (t (let ((sign (member-equal-+- (car arg1) arg2)))

; Sign is +, -, or nil, meaning (car arg1) occurs in arg2, the complement of
; (car arg1) occurs in arg2, or neither occur.

             (cond
              ((null sign) nil)
              ((eq sign '+)
               (arg1-almost-subsumes-arg2 (cdr arg1) arg2))
              ((subsetp-equal-mod-extra-info-lits (cdr arg1) arg2)
               arg1)
              (t nil))))))

(defun find-subsumer-replacement-rec (cl l len-cl)
  (declare (xargs :guard (and (pseudo-term-listp cl)
                              (pseudo-term-list-listp l)
                              (equal len-cl (length cl)))))

; See find-subsumer-replacement.

  (cond ((null l) (mv nil nil))
        ((> (len (car l)) len-cl)

; Although in principle it seems that (car l) could "almost subsume" cl (in the
; sense of arg1-almost-subsumes-arg2 below), we rather expect that to be rare,
; since "almost subsume" is a sort of subset relation.

         (find-subsumer-replacement-rec cl (cdr l) len-cl))
        (t (let ((here (arg1-almost-subsumes-arg2 (car l) cl)))
             (cond ((eq here 'subsumed) (mv here (car l)))
                   (t (mv-let (rst cl0)
                        (find-subsumer-replacement-rec cl (cdr l) len-cl)
                        (cond ((eq rst 'subsumed) (mv rst cl0))
                              (t (mv (or here rst) nil))))))))))

(defun find-subsumer-replacement (cl l)
  (declare (xargs :guard (and (pseudo-term-listp cl)
                              (pseudo-term-list-listp l))))

; We return (mv val cl0), where val is nil to indicate that no subsumer or
; replacer was found, or 'subsumed to indicate cl is subsumed by clause cl0 in
; l, or if neither of these cases applies, then a pair (indicating that the
; complement of the car of the pair may be removed from cl).  The last case
; means that somewhere in l we found a clause that when resolved with cl
; produces a resolvent that subsumes cl.

  (find-subsumer-replacement-rec cl l (length cl)))

(defun remove-one-complement (lit cl)
  (declare (xargs :guard (and (pseudo-termp lit)
                              (pseudo-term-listp cl))))
  (cond ((null cl) nil)
        ((complementaryp lit (car cl)) (cdr cl))
        (t (cons (car cl) (remove-one-complement lit (cdr cl))))))

(defun weak-disc-tree (x)
  (and (or (consp x) (equal x nil))
       (cond ((equal (car x) 'node)
              (and (true-listp x)
                   (equal (length x) 4)
                   (pseudo-termp (cadr x))
                   (weak-disc-tree (caddr x))
                   (weak-disc-tree (cadddr x))))
             (t (pseudo-term-list-listp (cdr x))))))

(defun sweep-clauses1 (tree ac)
  (declare (xargs :guard (weak-disc-tree tree)))
  (cond ((eq (car tree) 'node)
         (sweep-clauses1 (caddr tree) (sweep-clauses1 (cadddr tree) ac)))
        (t (append (cdr tree) ac))))

(defun sweep-clauses (tree)
  (declare (xargs :guard (weak-disc-tree tree)))
  (sweep-clauses1 tree nil))

(defun filter-with-and-without (x l with-lst without-lst)

; L is a list of clauses.  X is a literal.  We partition l into two sets:  the
; with-lst contains those clauses with x as a (positive or negative) literal;
; the without-lst are all others.  Then we return (mv with-lst without-lst).

; We consider a negated call of EXTRA-INFO to belong to every clause!

  (cond ((null l) (mv with-lst without-lst))
        ((or (extra-info-lit-p x)
             (member-equal-+- x (car l)))
         (filter-with-and-without x (cdr l)
                                  (cons (car l) with-lst)
                                  without-lst))
        (t (filter-with-and-without x (cdr l)
                                    with-lst
                                    (cons (car l) without-lst)))))

(defun disc-tree (x)

; A disc-tree, or ``discrimination tree'' is a data structure that organizes a
; set of clauses.  The basic shape is

; disc-tree := (TIP clauses) | (NODE lit disc-tree_1 disc-tree_2),

; The ``clauses in a disc-tree'' is just the set of all the clauses occurring
; in some tip.  This is computed by sweep-clauses.

; But the important invariant of a disc-tree NODE is that all the clauses in
; disc-tree_1 contain a (positive or negative) occurrence of lit, and none of
; the clauses in disc-tree_2 contain such an occurrence.

; We test this invariant below by collecting all the clauses in disc-tree_i
; and confirming that either every clause or no clause contains the lit.  We
; use filter-with-and-without to partition the clauses in a list according to
; whether they contain an occurrence of lit.  If we partition the clauses in
; disc-tree_i into ``with lit'' and ``without lit'' buckets, the ``with lit''
; bucket is set equal to the entire set of disc-tree_1 and the ``without lit''
; bucket is set equal to the entire set for disc-tree_2.  But rather than test
; set equality we exploit the fact that we know filter-with-and-without really
; partitions and just test that the ``without lit'' bucket is empty for
; disc-tree_1 and the ``with lit'' bucket is empty for disc-tree_2.

  (and (or (consp x) (equal x nil))
       (cond ((equal (car x) 'node)
              (and (true-listp x)
                   (equal (length x) 4)
                   (pseudo-termp (cadr x))
                   (disc-tree (caddr x))
                   (disc-tree (cadddr x))
                   (mv-let (with-lst without-lst)
                     (filter-with-and-without (cadr x)
                                              (sweep-clauses (caddr x))
                                              nil nil)
                     (declare (ignore with-lst))
                     (null without-lst))
                   (mv-let (with-lst without-lst)
                     (filter-with-and-without (cadr x)
                                              (sweep-clauses (cadddr x))
                                              nil nil)
                     (declare (ignore without-lst))
                     (null with-lst))))
             (t (pseudo-term-list-listp (cdr x))))))

(defun find-clauses1 (clause tree ac)
  (declare (xargs :guard (and (disc-tree tree)
                              (pseudo-term-listp clause)
                              (pseudo-term-list-listp ac))))

; We compute a superset of all those clauses stored in tree which
; could subsume clause or which, when resolved with clause, could
; produce a new clause that subsumed clause.  If the key of a node
; does not occur+- in clause, then none of the clauses on the yes
; branch of the node can be relevant because all of the clauses
; on the yes branch contain+- the key.

  (cond ((eq (car tree) 'node)
         (cond ((or (extra-info-lit-p (cadr tree))
                    (member-equal-+- (cadr tree) clause))
                (find-clauses1 clause (caddr tree)
                               (find-clauses1 clause (cadddr tree) ac)))
               (t (find-clauses1 clause (cadddr tree) ac))))
        (t (append (cdr tree) ac))))

(defun find-clauses (clause tree)
  (find-clauses1 clause tree nil))

(defun remove-one-+- (x l)
  (cond ((null l) nil)
        ((equal x (car l)) (cdr l))
        ((complementaryp x (car l)) (cdr l))
        (t (cons (car l) (remove-one-+- x (cdr l))))))

(defun store-clause1 (clause undisc-lits tree)
  (declare (xargs :guard (and (pseudo-term-listp clause)
                              (pseudo-term-listp undisc-lits)
                              (disc-tree tree))))
  (cond
   ((eq (car tree) 'node)
    (cond ((extra-info-lit-p (cadr tree))
           (list 'node
                 (cadr tree)
                 (store-clause1 clause
                                undisc-lits
                                (caddr tree))
                 (cadddr tree)))
          ((member-equal-+- (cadr tree) clause)
           (list 'node
                 (cadr tree)
                 (store-clause1 clause
                                (remove-one-+- (cadr tree) undisc-lits)
                                (caddr tree))
                 (cadddr tree)))
          (t (list 'node
                   (cadr tree)
                   (caddr tree)
                   (store-clause1 clause
                                  undisc-lits
                                  (cadddr tree))))))
   ((null undisc-lits)
    (cons 'tip (cons clause (cdr tree))))
   ((extra-info-lit-p (car undisc-lits))
    (store-clause1 clause (cdr undisc-lits) tree))
   (t (mv-let (with-lst without-lst)
              (filter-with-and-without (car undisc-lits) (cdr tree) nil nil)
              (store-clause1
               clause undisc-lits
               (list 'node (car undisc-lits)
                     (cons 'tip with-lst)
                     (cons 'tip without-lst)))))))

(defun store-clause (cl tree)

; Store-clause implements a specialized discrimination network for
; storing clauses during the subsumption/replacement phase of
; clausify.  Here the tree is either of the form:

; (NODE lit with-tree without-tree)

; or

; (TIP . clauses)

; A tree is said to contain a clause if that clause is a member of the clause
; list at some TIP in the tree.  Every clause in the with-tree of a NODE
; contains the node's lit either positively or negatively as an element.  No
; clause in the without-tree of a NODE contains the lit.

  (store-clause1 cl cl tree))

(defun substitute1-ac (new old seq acc)
  (declare (xargs :guard (and (true-listp acc)
                              (true-listp seq)
                              (member-equal old seq))))
  (cond
   ((endp seq)
    (er hard 'substitute
        "Attempted to substitute ~x0 for ~x1 into a sequence in which the ~
         latter was not an element."
        new old))
   ((equal old (car seq))
    (revappend acc (cons new (cdr seq))))
   (t
    (substitute1-ac new old (cdr seq) (cons (car seq) acc)))))

(defun substitute1 (new old seq)
  (declare (xargs :guard (and (true-listp seq)
                              (member-equal old seq))))
  (substitute1-ac new old seq nil))

(defun replace-clause1 (clause undisc-lits new-clause tree)
  (declare (xargs :guard (and (pseudo-term-listp clause)
                              (pseudo-term-listp undisc-lits)
                              (disc-tree tree))))
  (cond
   ((eq (car tree) 'node)
    (cond ((member-equal-+- (cadr tree) clause)
           (list 'node
                 (cadr tree)
                 (replace-clause1 clause
                                  (remove-one-+- (cadr tree) undisc-lits)
                                  new-clause
                                  (caddr tree))
                 (cadddr tree)))
          (t (list 'node
                   (cadr tree)
                   (caddr tree)
                   (replace-clause1 clause
                                    undisc-lits
                                    new-clause
                                    (cadddr tree))))))
   ((member-equal clause (cdr tree))
    (cons (car tree) ; 'tip
          (substitute1 new-clause clause (cdr tree))))
   (t tree)))

(defun replace-clause (clause new-clause tree)
  (declare (xargs :guard (and (pseudo-term-listp clause)
                              (disc-tree tree))))
  (replace-clause1 clause clause new-clause tree))

(defun extra-info-lits (cl acc)
  (cond ((endp cl) acc)
        ((extra-info-lit-p (car cl))
         (extra-info-lits (cdr cl) (cons (car cl) acc)))
        (t (extra-info-lits (cdr cl) acc))))

(defun merge-extra-info-lits (cl cl0 tree)

; cl0 is in tree.  We want to merge the extra-info-lit elements of cl into cl0.

  (let ((lits (extra-info-lits cl nil)))
    (cond (lits (replace-clause cl0 (rev-union-equal lits cl0) tree))
          (t tree))))

(defun subsumption-replacement-loop (todo done-tree again-flg)
  (declare (xargs :guard (and (pseudo-term-list-listp todo)
                              (disc-tree done-tree))))

; Precondition:  todo should have the shortest clauses first in order for this
; code to catch all possible subsumptions.  Use merge-sort-length to sort the
; input todo.

; Caution:  If there are tautologies in the input clause set, todo, then the
; output clause set may not be propositionally equivalent.  The output clause
; set will imply the input.  For example, let todo be
; ((A (NOT B) B)   ; c1
;  (A B))          ; c2
; Then c1 is a tautology.  However, it is used to replace c2 by (A), which
; then subsumes c1.  The output is thus ((A)).  But the input set is
; propositionally equivalent to ((A B)).

  (cond ((null todo)
         (cond
          (again-flg
           (cond
            ((time-limit5-reached-p ; nil, or throws
              "Out of time in subsumption (subsumption-replacement-loop).")
             nil)
            (t
             (subsumption-replacement-loop
              (merge-sort-length (sweep-clauses done-tree)) nil nil))))
          (t (sweep-clauses done-tree))))
        (t (mv-let (x cl0)
                   (find-subsumer-replacement
                    (car todo)
                    (find-clauses (car todo) done-tree))
                   (cond ((null x)
                          (subsumption-replacement-loop
                           (cdr todo)
                           (store-clause (car todo) done-tree)
                           again-flg))
                         ((eq x 'subsumed)
                          (subsumption-replacement-loop
                           (cdr todo)
                           (merge-extra-info-lits (car todo) cl0 done-tree)
                           again-flg))
                         (t (subsumption-replacement-loop
                             (cdr todo)
                             (store-clause (remove-one-complement (car x)
                                                                  (car todo))
                                           done-tree)
                             t)))))))

; Rockwell Addition: Same old lambda-exp arg.  Clausify is called in
; many places and now has a new last arg.  This will show up many
; times.

(defun clausify (term assumptions lambda-exp sr-limit)

; We return a conjunction of clauses equivalent to term under the assumptions
; given.  Assumptions must be nil (meaning no assumptions) or something
; generated by convert-clause-to-assumptions.  In the latter case, assumptions
; will start with the mark :ignore-when-converting-to-clause, which means that
; the assumptions in assumptions do not get transferred into the clauses built.

; If context is nil, then (bar (if test a b)) would clausify to two clauses,
; ((not test) (bar a)) and (test (bar b)).  But if (bar a) is assumed true in
; assumptions, e.g., assumptions is (:ignore-when-converting-to-clause (bar a))
; then the first clause above is recognized as true.  While the initial
; assumptions filter out literals and clauses they do not otherwise contribute;
; in particular, our answer is not a set of clauses representing context ->
; term.

; It would be nice for clausify to know all sorts of things, like type-set and
; the removal of trivial equivalences.  The trouble is that if we do that, we
; need to track what was done with ttrees.  But if clausify returns a ttree
; many of its callers have great difficulty accommodating it.  For example, in
; the translation of :by hints, there is no provision for recording or
; reporting the rules used to "translate" the hint into a clause.  For this
; reason, we've left clausify "dumb."

; Lambda-exp indicates whether we should go inside of lambdas.

  (declare (xargs :guard (pseudo-termp term)))
  (let ((clauses (pstk
                  (strip-branches term assumptions lambda-exp))))
    (cond
     ((or (null sr-limit) (<= (length clauses) sr-limit))
      (pstk
       (subsumption-replacement-loop
        (merge-sort-length
         clauses)
        nil
        nil)))
     (t clauses))))

; Now we get into the immediate subroutines of rewrite itself.

(defun find-rewriting-equivalence (lhs type-alist geneqv wrld ttree)

; We search type-alist for a binding to *ts-t* of a term of the form
; (equiv lhs rhs), where equiv is a refinement of geneqv and lhs is as
; given in the arguments.  If we find it, we return the entire binding
; and a ttree in which we have added the name of the :CONGRUENCE rule
; as a 'lemma.  Equiv is known to be an equivalence relation and as
; such we know that lhs is bigger than rhs in the term-order.

; A heuristic question arises.  Suppose we have several such
; equiv-terms for lhs, all different refinements of geneqv.  What do
; we do?  Well, we will chose the first we find.  Ugh.  But suppose
; they are refinements of each other.  E.g., we have three hypotheses,
; (set-equal b a1), (list-equal b a2) and (equal b a3), where
; list-equal is a refinement of set-equal.  Then because we know, for
; every equivalence relation equiv, that iff is preserved by equiv in
; both slots of equiv, we will eventually rewrite the b in each of the
; hypotheses above, maintaining the equivalence relation concerned.
; Thus, in (set-equal b a1) we will rewrite b maintaining set-equal
; and will choose either to replace b by a2 or a3, since list-equal
; and equal are both refinements.  The point is that ultimately in the
; rewriting process the three hypotheses will become (set-equal b a3),
; (list-equal b a3) and (equal b a3) because the finest refinement
; will ultimately get to rewrite each of the others.

; No Change Loser on the ttree

  (cond ((null type-alist) (mv nil nil ttree))
        (t (let ((entry (car type-alist)))
             (cond
              ((not (variablep (car entry)))

; This code is a bit contorted because we have found (specifically, in
; (verify-guards exec-send ...) in community book
; books/workshops/2000/lusk-mccune/lusk-mccune-final/stepproc1.lisp) that the
; ts= call below is noticeably more efficient than the (ts-disjointp ...).

               (let ((rw-equivp (cond ((and (eq (ffn-symb (car entry))
                                                'hide)
                                            (not (variablep (fargn (car entry)
                                                                   1)))
                                            (eq (ffn-symb (fargn (car entry)
                                                                 1))
                                                'rewrite-equiv))
                                       (car entry)))))
                 (cond
                  ((if rw-equivp
                       (ts-disjointp (cadr entry) *ts-nil*)
                     (ts= (cadr entry) *ts-t*))
                   (let* ((equiv-term
                           (cond (rw-equivp (fargn (fargn (car entry) 1)
                                                   1))
                                 (t (car entry))))
                          (rune (and (not (flambdap (ffn-symb equiv-term)))
                                     (geneqv-refinementp (ffn-symb equiv-term)
                                                         geneqv wrld))))
                     (cond ((and rune
                                 (equal (fargn equiv-term 1) lhs))
                            (mv rw-equivp
                                equiv-term
                                (cons-tag-trees
                                 (cddr entry)
                                 (push-lemma rune ttree))))
                           (t (find-rewriting-equivalence
                               lhs (cdr type-alist) geneqv wrld ttree)))))
                  (t (find-rewriting-equivalence
                      lhs (cdr type-alist) geneqv wrld ttree)))))
              (t (find-rewriting-equivalence
                  lhs (cdr type-alist) geneqv wrld ttree)))))))

(defun obj-table (term ts ts-ttree obj geneqv wrld ttree)

; This function is (mv term' ttree'), where term' is equivalent modulo geneqv
; (see the essay on Equivalence, Refinements and Congruence- based Rewriting)
; to term and ttree' includes ttree and may include additional stuff.
; Depending on ts, the type-set of term (which is supported by the ts-ttree),
; we may coerce term to 0, 1, t, or nil.

; Note: This function used to depend on the objective, obj, of the rewrite.
; When obj was nil, that dependency prevented obj-table from reducing term to t
; when term was known to have non-nil type-set.  That, in turn, caused
; relieve-hyp to force (not term), even though (not term) was known nil.  We
; now reduce term to t, nil or 0 as appropriate by the geneqv and ts,
; regardless of obj.  However, we have left the obj parameter in place, in case
; we someday want to restore dependency on it.

  (declare (ignore obj))
  (cond
   ((ts= ts *ts-t*)
    (mv *t*

; At one time we tested whether (equal term *t*), so that when this holds we
; can avoid a call of cons-tag-trees.  However, we only call obj-table on
; non-quotep terms, so we know that this test will be false.

        (cons-tag-trees ts-ttree ttree)))
   ((ts= ts *ts-nil*)
    (mv *nil*
        (cons-tag-trees ts-ttree ttree)))
   ((ts= ts *ts-zero*)
    (mv *0*
        (cons-tag-trees ts-ttree ttree)))

; After a new type-set bit for the set {1}, we considered adding a case for
; (ts= ts *ts-one*), to return (mv *1* (cons-tag-trees ts-ttree ttree)) in that
; case to coerce the term to '1.  However, some books failed.  For example, a
; problem in community book books/demos/proofs/tightness-lemma-proof.lisp
; simplifies to the following example.

;   (defun i-from (n len)
;     (cond ((zp len) nil)
;           (t (cons n
;                    (i-from (1+ n) (1- len))))))
;   (defthm <-0-+-negative-1
;     (iff (< 0 (+ (- y) x)) (< y x)))
;   (defthm consp-i-from
;     (equal (consp (i-from i len))
;            (not (zp len))))

; The problem was presumably that under a proof by induction, obj-table was
; replacing the goal

;   (IMPLIES (AND (NOT (ZP LEN)) (ZP (+ -1 LEN)))
;            (CONSP (I-FROM I LEN)))

; by the goal

;   (IMPLIES (AND (NOT (ZP LEN)) (<= LEN 1))
;            (CONSP (I-FROM I 1)))

; and although the term (I-FROM I LEN) was a term to be expanded under
; induction, (I-FROM I 1) was not.  We had 27 other failures that might have
; been due to this same problem, but we didn't investigate them.  Instead, we
; are omitting a case here for *ts-one*.

; We have also had problems when including this (deleted) case, depending on
; other heuristics involving *ts-one*, for the lemma symbolic-computation in
; models/jvm/m5/demo.lisp, projects/symbolic/m5/demo.lisp, and
; books/workshops/2003/moore_vcg/support/.  Sol Swords noticed that a
; forward-chaining lemma, (implies (and (integerp (+ 1 k)) (acl2-numberp k))
; (integerp k)), solves that problem; but without this case, we don't need that
; lemma.

; For more discussion regarding *ts-one*, see the Essay on Strong Handling of
; *ts-one*.

   (t (let ((rune (geneqv-refinementp 'iff geneqv wrld)))
        (cond
         (rune
          (cond
           ((ts-subsetp *ts-nil* ts)
            (mv term ttree))
           (t (mv *t*
                  (push-lemma rune
                              (cons-tag-trees ts-ttree
                                              ttree))))))
         (t (mv term ttree)))))))

(defun rewrite-solidify-rec (bound term type-alist obj geneqv ens wrld ttree
                                   pot-lst pt)
  (declare (type #.*fixnat-type* bound))
  (cond
   ((quotep term)
    (cond ((equal term *nil*) (mv *nil* ttree))
          (t (let ((rune (geneqv-refinementp 'iff geneqv wrld)))
               (cond (rune
                      (mv *t* (push-lemma rune ttree)))
                     (t (mv term ttree)))))))
   ((ffn-symb-p term 'if)

; Is this case important?  It doesn't seem so, and we were tempted to delete it
; when we modified find-rewriting-equivalence after Version_3.0.1 to look for
; calls of (hide ('rewrite-equiv ..)).  But at one time, deletion caused
; failure of lemma lop3-34 in community book
; books/rtl/rel5/support/lop3-proofs.lisp, so we leave this case for backward
; compatibility.

    (mv term ttree))
   ((and (ffn-symb-p term 'hide)
         (let ((e (fargn term 1)))
           (case-match e
             (('rewrite-equiv (equiv x x))
              (prog2$ x ; avoid "not used" error
                      (equivalence-relationp equiv wrld)))
             (& nil))))

; Here we rewrite terms of the form (hide (rewrite-equiv (equiv x x))) to true,
; where equiv is a known equivalence relation.  This is clearly sound.  It
; avoids some loops.  The following example, based closely on one sent by Dave
; Greve, loops in ACL2 Version_3.2 but not in later versions (which have this
; fix).  If you trace rewrite and rewrite-solidify in TEST below, you'll see
; that where formerly (HIDE (REWRITE-EQUIV (EQUAL RES (GOO X)))) rewrote (with
; RES bound to (GOO X), and thanks to running BETA-REDUCE-HIDE-WRAPPER), to
; (HIDE (REWRITE-EQUIV (EQUAL (GOO X) (GOO X)))) now instead it rewrites to
; *T*.


;     (DEFEVALUATOR UNHIDE-EVAL UNHIDE-EVAL-LIST
;       ((IF X Y Z) (HIDE X)))
;
;     (DEFUN BETA-REDUCE-HIDE-WRAPPER (X)
;       (IF (EQUAL X '(HIDE ((LAMBDA (RES X)
;                                    (REWRITE-EQUIV (EQUAL RES (GOO X))))
;                            (GOO X)
;                            X)))
;           '(HIDE (REWRITE-EQUIV (EQUAL (GOO X) (GOO X))))
;           X))
;
;     (DEFTHM
;       *META*-BETA-REDUCE-HIDE
;       (IMPLIES (PSEUDO-TERMP TERM)
;                (EQUAL (UNHIDE-EVAL TERM A)
;                       (UNHIDE-EVAL (BETA-REDUCE-HIDE-WRAPPER TERM)
;                                    A)))
;       :HINTS (("Goal" :EXPAND (:FREE (X) (HIDE X))
;                :IN-THEORY (ENABLE UNHIDE-EVAL-CONSTRAINT-0)))
;       :RULE-CLASSES ((:META :TRIGGER-FNS (HIDE))))
;
;     (DEFUN GOO (X) X)
;     (DEFUN FOO (X) (GOO X))
;     (IN-THEORY (DISABLE FOO GOO))
;
;     (DEFUN CONCLUSION (X)
;       (LET ((RES (FOO X)))
;            (AND
;             (HIDE (REWRITE-EQUIV (EQUAL RES (GOO X))))
;             (INTEGERP RES))))
;
;     (DEFTHM TEST
;       (IMPLIES
;        (HIDE (REWRITE-EQUIV (EQUAL (FOO X) (GOO X))))
;        (CONCLUSION X))
;       :HINTS (("GOAL" :IN-THEORY (DISABLE CONCLUSION)
;                :DO-NOT '(PREPROCESS))
;               (AND STABLE-UNDER-SIMPLIFICATIONP
;                    '(:IN-THEORY (ENABLE CONCLUSION)))))

    (mv *t* (push-lemma
             (fn-rune-nume 'hide nil nil wrld)
             (push-lemma
              (fn-rune-nume 'rewrite-equiv nil nil wrld)

; We do not track the use of equivalence relations; see comment in
; equivalence-relationp.

              ttree))))
   (t
    (mv-let (rw-equivp eterm ttree)
            (find-rewriting-equivalence term type-alist geneqv wrld ttree)
            (cond
             (eterm

; If rw-equivp is true, then the equivalence is from a call of rewrite-equiv.
; The following recursive call is guaranteed to be made on a term that is
; smaller according to term-order, by the Third invariant on type-alists.  See
; the Essay on the Invariants on Type-alists, and Canonicality.

              (let ((new-bound
                     (cond
                      ((not rw-equivp)
                       bound)
                      ((zpf bound)
                       (prog2$ (er hard 'rewrite-solidify
                                   "You appear to have hit the unusual case ~
                                    of a loop in the replacement of terms by ~
                                    equivalent terms using rewrite-equiv.  ~
                                    The term ~x0 is involved in the loop."
                                   rw-equivp)
                               0))
                      (t (1-f bound)))))
                (declare (type #.*fixnat-type* new-bound))
                (rewrite-solidify-rec new-bound (fargn eterm 2) type-alist
                                      obj geneqv ens wrld ttree
                                      pot-lst pt)))
             (t (mv-let (ts ts-ttree)

; See the comment just after rewrite-solidify for some historical waffling.

                        (cond ((not (eq obj '?))
                               (type-set term nil t type-alist
                                         ens wrld nil pot-lst pt))
                              (t (assoc-type-alist term type-alist wrld)))
                        (if (null ts)
                            (mv term ttree)
                          (obj-table term ts ts-ttree
                                     obj geneqv wrld ttree)))))))))

(defconst *rewrite-equiv-solidify-iteration-bound*

; The number below is pretty generous, since it bounds the number of recursive
; calls of rewrite-solidify-rec on behalf of rewrite-equiv.

  100)

(defun rewrite-solidify (term type-alist obj geneqv ens wrld ttree
                               pot-lst pt)
  (rewrite-solidify-rec *rewrite-equiv-solidify-iteration-bound* term
                        type-alist obj geneqv ens wrld ttree pot-lst pt))

; Comment on Historical Waffling over Calling Type-Set in Rewrite-Solidify
;
; Back in v1-7 we called
; (type-set term nil force-flg type-alist nil ens wrld nil)
; here, where force-flg was passed into rewrite-solidify.
;
; We abandoned that in v1-8 and most of v1-9 and replaced it with a simple
; lookup of term in the type-alist,
;
; (assoc-type-alist term type-alist wrld)
;
; and marked the occasion by writing the following comment:
;
; ; At one time we called type-set here.  As a result, the prover could simplify
; ;
; ; (thm (implies (and (not (< y 0))
; ;                    (rationalp y)
; ;                    (not (equal 0 y)))
; ;               (equal aaa (< 0 y))))
; ;
; ; to
; ;
; ; (implies (and (not (< y 0))
; ;               (rationalp y)
; ;               (not (equal 0 y)))
; ;          (equal aaa t))
; ;
; ; However, in the interest of performance we have decided to avoid a full-blown
; ; call of type-set here.  You get what you pay for, perhaps.
;
; However, then Rich Cohen observed that when trying to relieve a hypothesis in
; a lemma, if the hyp rewrote to an explicit cons expression then we failed to
; recognize that it is non-nil!  Here is a thm that failed for that reason:
;
;  (defstub foo (x a) t)
;  (defaxiom lemma
;   (implies (member x a) (equal (foo x a) x)))
;  (thm (equal (foo x (cons x y)) x))
;
; We have decided to revert to the use of type-set in rewrite-solidify, but
; only when we have an objective of t or nil.  Under this condition we use
; force-flg nil and dwp t.  We tried the div proofs with force-flg t here
; and found premature forcing killed us.

; On 1/17/2019, after Version_8.1, we tried modifying rewrite-solidify-rec to
; call type-set unconditionally, not merely when (not (eq obj '?)).  There were
; 46 failures in the "everything" regression, which we killed before it
; completed since there were three very-long running certifications still in
; progress (about 3 hours each).  Among those, we noticed
; books/nonstd/workshops/2017/cayley/cayley1c.lisp, whose certification went
; far enough for us to see the proof of 8-COMPOSITION-LAW completed but
; took 7560.97 seconds, far exceeding the 6.49 seconds taken in a recent run.
; It thus seemed obvious that such a change would likely cause massive changes
; to be necessary not only in the community books, but also in proprietary
; books elsewhere.

(defun rewrite-if11 (term type-alist geneqv wrld ttree)
  (mv-let (ts ts-ttree)
    (look-in-type-alist term type-alist wrld)
    (cond ((ts= ts *ts-nil*)
           (mv *nil* (cons-tag-trees ts-ttree ttree)))
          ((and (equal geneqv *geneqv-iff*)
                (ts-disjointp ts *ts-nil*))
           (mv *t* (cons-tag-trees ts-ttree ttree)))
          (t
           (mv term ttree)))))

(defstub rewrite-if-avoid-swap () => *)

(defattach (rewrite-if-avoid-swap constant-nil-function-arity-0))

(defun rewrite-if1 (test left right swapped-p type-alist geneqv ens ok-to-force
                         wrld ttree)

; Test, left and right are rewritten terms.  They were rewritten under
; appropriate extensions of type-alist.  We implement the following
; rules here:

; (if x y y) = y
; (if x x nil) = x
; (if x t nil) = x, if x is Boolean

; Note: In Version  2-5 days, the following comment was in type-set:
; Note: Because IF's are not bound on the type-alist, we need not ....

; This was not true then, nor is it true now (Version  2-7).  Therefore,
; when the above three rules fail we try looking up `(if ,test ,left ,right)
; on the type-alist.  This is done in rewrite-if11.

; Once upon a time we used known-whether-nil to determine if right was
; nil under type-alist and wrld.  But since right is the result of
; rewriting, we claim that if it is known to be nil then it is in fact
; *nil* because of rewrite-solidify.  So we no longer use
; known-whether-nil here.

  (flet ((if-call (test left right swapped-p)
                  (cond ((and swapped-p (rewrite-if-avoid-swap))
                         (mcons-term* 'if (dumb-negate-lit test) right left))
                        (t (mcons-term* 'if test left right)))))
    (cond ((equal left right) (mv left ttree))
          ((equal right *nil*)
           (cond
            ((equal test left)
             (mv test ttree))
            ((equal left *t*)
             (mv-let (ts ts-ttree)
               (type-set test ok-to-force nil type-alist ens wrld ttree nil nil)
               (cond ((ts-subsetp ts *ts-boolean*)
                      (mv test ts-ttree))
                     (t (rewrite-if11 (if-call test left right swapped-p)
                                      type-alist geneqv wrld ttree)))))
            (t (rewrite-if11 (if-call test left right swapped-p)
                             type-alist geneqv wrld ttree))))
          ((and swapped-p
                (equal left *nil*)
                (equal right *t*)
                (rewrite-if-avoid-swap))
           (mv (fcons-term* 'not test) ttree))
          (t (rewrite-if11 (if-call test left right swapped-p)
                           type-alist geneqv wrld ttree)))))

; Rockwell Addition: In the not-to-be-rewritten test below, we used to
; create an instantiation with sublis-var.  Now we chase var bindings.
; But there is a subtlety with constants created by sublis-var.

(defun member-equal-mod-alist (term1 alist1 term2-lst)
  (cond ((endp term2-lst) nil)
        ((equal-mod-alist term1 alist1 (car term2-lst))
         t)
        (t (member-equal-mod-alist term1 alist1 (cdr term2-lst)))))

(defun not-to-be-rewrittenp1 (fn lst)

; This function determines whether fn is the ffn-symb of any term on
; lst.  We assume lst is a true list of non-variablep non-quotep
; terms.

  (cond ((null lst)
         nil)
        ((equal fn (ffn-symb (car lst))) ; Both may be LAMBDAs.
         t)
        (t (not-to-be-rewrittenp1 fn (cdr lst)))))

(defun not-to-be-rewrittenp (term alist terms-to-be-ignored-by-rewrite)

; We assume term is a nonvariable non-quotep and that
; terms-to-be-ignored-by-rewrite contains no vars or quoteps.  Let
; term' be (sublis-var alist term).  If term' is a member of
; terms-to-be-ignored-by-rewrite we return term' else nil.  We have
; a faster preliminary check, namely, whether terms-to-be-ignored-
; by-rewrite contains any terms with the same top-level function
; symbol as term.

  (cond ((not-to-be-rewrittenp1 (ffn-symb term)
                                terms-to-be-ignored-by-rewrite)
         (member-equal-mod-alist term alist
                                 terms-to-be-ignored-by-rewrite))
        (t nil)))

(defun rewrite-recognizer (recog-tuple arg type-alist ens force-flg wrld ttree
                           pot-lst pt)

; This function returns (mv term' ttree'), where term' is equivalent
; to (fn arg), where fn is the fn field of recog-tuple, and ttree' is
; an extension of ttree that supports whatever was done to reduce (fn
; arg) to term'.  (We use ``ttree+'' for ttree' below.  Observe that we
; sometimes return ttree+ and other times return ttree.)

  (mv-let (ts ttree+)
          (type-set arg force-flg nil type-alist ens wrld ttree pot-lst pt)
    (cond
     ((ts-intersectp ts (access recognizer-tuple recog-tuple :true-ts))
      (cond ((ts-intersectp ts (access recognizer-tuple recog-tuple :false-ts))
             (mv (mcons-term* (access recognizer-tuple recog-tuple :fn)
                              arg)
                 ttree))
            (t (mv *t*
                   (push-lemma (access recognizer-tuple recog-tuple :rune)
                               ttree+)))))

; Once upon a time we had:

;    ((ts-intersectp ts (access recognizer-tuple recog-tuple :false-ts))
;     (mv *nil* ttree+))
;    (t
;     (mv (mcons-term* (access recognizer-tuple recog-tuple :fn)
;                      arg)
;         ttree))

; here.  But we noticed that if the type-set of arg, ts, does not
; intersect true-ts then we know that (not (fn arg)):  either (fn arg)
; or (not (fn arg)) and we know the former implies that ts a subset of
; true-ts.  Since it is not, the latter must hold.  A consequence of
; this insight is that we can see that if ts does not intersect
; true-ts then it MUST intersect false-ts.

     (t (mv *nil*
            (push-lemma (access recognizer-tuple recog-tuple :rune)
                        ttree+))))))

; In a departure from Nqthm, we use a lexicographic order on lists of
; terms for the loop-stopping algorithm.  This change was motivated by
; an example in which there were two variables involved in the
; loop-stopper, and one of the corresponding actuals was unchanged.
; Consider for example a rewrite rule like

; (equal
;  (variable-update var1
;                   val1 (variable-update var2 val2 vs))
;  (variable-update var2
;                   val2 (variable-update var1 val1 vs)))

; which has a loop-stopper of ((val1 . val2) (var1 . var2)), and could
; be applied where val1 and val2 are both x but var2 is instantiated
; by a term that precedes the instantiation of var1 in the term-order.
; Nqthm's loop stopper would prevent this application of the rule, but
; the implementation below allows it.

(defun remove-invisible-fncalls (term invisible-fns)

; Given a term and a list of unary function symbols considered invisible,
; strip off all the invisible outermost function symbols from the term.

  (cond
   ((or (variablep term)
        (fquotep term)
        (flambda-applicationp term))
    term)
   ((member-eq (ffn-symb term) invisible-fns)
    (remove-invisible-fncalls (fargn term 1) invisible-fns))
   (t term)))

(defun term-order+ (x1 x2 invisible-fns)

; See the doc string for loop-stopper to find an implicit description
; of this function.  See the comment below for a proof that this
; function is a total order, provided term-order is a total order.

  (let ((x1-guts (remove-invisible-fncalls x1 invisible-fns))
        (x2-guts (remove-invisible-fncalls x2 invisible-fns)))
    (cond
     ((equal x1-guts x2-guts)
      (term-order x1 x2))
     (t
      (term-order x1-guts x2-guts)))))

; We wish to prove that term-order+ is a total ordering on terms, which,
; recall, means that it is antisymmetric, transitive, and enjoys the trichotomy
; property.  However, because term-order+ and its main subroutine, term-order,
; are :program functions we cannot do this directly without reclassifying them.
; In addition, we would first need to prove the lemma that term-order is a
; total ordering.  Rather than undertake such a large proof effort, we attack a
; slightly different problem.  The basic idea is to constrain the new functions
; xtermp, xterm-order, and xremove-invisible-fncalls to have the properties we
; are willing to assume about the corresponding :program functions.  In
; particular, we assume that xterm-order is a total ordering on xtermps and
; that xremove-invisible-fncalls preserves xtermp.  Then we define xterm-order+
; analogously to the definition above of term-order+ and we prove that
; xterm-order+ is a total ordering on xterms.


; Introduce xtermp, xterm-order and xremove-invisible-fncalls by constraint.
; Observe that in the three properties characterizing xterm-order as a total
; ordering we restrict our claims to the cases where only xtermps are involved.
; We also require that xremove-invisible-fncalls preserve xtermp.

;   (encapsulate (((xtermp *) => *)
;                 ((xterm-order * *) => *)
;                 ((xremove-invisible-fncalls * *) => *))

; We witness xtermp with rationalp, xterm-order with <= on the rationals,
; and xremove-invisible-fncalls by the identify function.

;    (local (defun xtermp (x) (rationalp x)))
;    (local (defun xterm-order (x y)
;             (and (xtermp x) (xtermp y) (<= x y))))
;    (local (defun xremove-invisible-fncalls (x lst) (declare (ignore lst)) x))

; Here we establish that xremove-invisible-fncalls preserves xtermp.

;    (defthm xtermp-xremove-invisible-fncalls
;      (implies (xtermp x) (xtermp (xremove-invisible-fncalls x lst))))

; We now prove the three total ordering properties.  In each case we
; state the property elegantly and then store it as an effective
; rewrite rule.

;    (defthm antisymmetry-of-xterm-order
;      (implies (and (xtermp x)
;                    (xtermp y)
;                    (xterm-order x y)
;                    (xterm-order y x))
;               (equal x y))
;
;      :rule-classes
;      ((:rewrite :corollary
;                 (implies (and (xtermp x)
;                               (xtermp y)
;                               (xterm-order x y)
;                               (xterm-order y x))
;                          (equal (equal x y) t)))))
;
;    (defthm transitivity-of-xterm-order
;      (implies (and (xtermp x)
;                    (xtermp y)
;                    (xtermp z)
;                    (xterm-order x y)
;                    (xterm-order y z))
;               (xterm-order x z))
;
;      :rule-classes
;      ((:rewrite :corollary
;                 (implies (and (xtermp x)
;                               (xterm-order x y)
;                               (xtermp y)
;                               (xtermp z)
;                               (xterm-order y z))
;                          (xterm-order x z)))))
;
;    (defthm trichotomy-of-xterm-order
;      (implies (and (xtermp x)
;                    (xtermp y))
;               (or (xterm-order x y) (xterm-order y x)))
;
;      :rule-classes
;      ((:rewrite :corollary
;                 (implies (and (xtermp x)
;                               (xtermp y)
;                               (not (xterm-order x y)))
;                          (xterm-order y x))))))

; Introduce the derived order, xterm-order+, that transduces with
; xremove-invisible-fncalls.  This is exactly analogous to the definition
; of term-order+ above.

;    (defun xterm-order+ (x1 x2 invisible-fns)
;     (let ((x1-guts (xremove-invisible-fncalls x1 invisible-fns))
;           (x2-guts (xremove-invisible-fncalls x2 invisible-fns)))
;       (cond
;        ((equal x1-guts x2-guts)
;         (xterm-order x1 x2))
;        (t
;         (xterm-order x1-guts x2-guts)))))

; Prove the three properties of xterm-order+, restricted to the xtermp cases.

;    (defthm antisymmetry-of-xterm-order+
;     (implies (and (xtermp x)
;                   (xtermp y)
;                   (xterm-order+ x y invisible-fns)
;                   (xterm-order+ y x invisible-fns))
;              (equal x y))
;     :rule-classes nil)
;
;    (defthm transitivity-of-xterm-order+
;     (implies (and (xtermp x)
;                   (xtermp y)
;                   (xtermp z)
;                   (xterm-order+ x y invisible-fns)
;                   (xterm-order+ y z invisible-fns))
;              (xterm-order+ x z invisible-fns)))
;
;    (defthm trichotomy-of-xterm-order+
;     (implies (and (xtermp x)
;                   (xtermp y))
;              (or (xterm-order+ x y invisible-fns)
;                  (xterm-order+ y x invisible-fns)))
;     :rule-classes nil)

(defun invisible-fns (fns alist acc)

; Fns is a list of function symbols.  Alist is an alist that maps each function
; symbol to a (possibly empty) list of corresponding invisible unary function
; symbols.  Acc should be t initially.  We return the intersection of the lists
; of invisible functions associated with each function in the list fns.

; We understand "intersection" to mean NIL when intersecting the empty list of
; lists; recall the set-theoretic definition of the intersection of a family of
; sets as containing those elements of the union of that family that belong to
; every set in that family.

  (declare (xargs :guard (and (symbol-listp fns)
                              (or (true-listp acc)
                                  (eq acc t)))))
  (cond
   ((null fns)
    (if (eq acc t) nil acc))
   ((eq acc t)
    (invisible-fns (cdr fns)
                   alist
                   (cdr (assoc-eq (car fns) alist))))
   ((null acc)

; This case is a minor optimization that could be omitted.

    nil)
   (t
    (invisible-fns (cdr fns)
                   alist
                   (intersection-eq (cdr (assoc-eq (car fns) alist))
                                    acc)))))

(defun loop-stopperp-rec (loop-stopper sbst wrld)

; Only call this at the top level when loop-stopper is non-nil.

  (cond
   ((null loop-stopper) nil)
   (t
    (let ((pre (cdr (assoc-eq (car (car loop-stopper)) sbst)))
          (post (cdr (assoc-eq (cadr (car loop-stopper)) sbst))))
      (cond
       ((equal pre post)
        (loop-stopperp-rec (cdr loop-stopper) sbst wrld))
       (t (term-order+ post pre
                       (invisible-fns
                        (cddr (car loop-stopper))
                        (invisible-fns-table wrld)
                        t))))))))

(defun loop-stopperp (loop-stopper sbst wrld)
  (or (null loop-stopper)
      (loop-stopperp-rec loop-stopper sbst wrld)))

(defrec rewrite-rule (rune nume hyps equiv lhs rhs
                           subclass heuristic-info

; Warning: Do not change the cheap flag, currently nil, without revisiting
; macro get-rule-field.

; The backchain-limit-lst must be nil, a natp, or a list of these of the same
; length as hyps.  For subclass 'meta, only the first two of these are legal.
; Otherwise, only the first and third of these are legal.

                           backchain-limit-lst

; For subclass 'backchain or 'abbreviation, var-info is t or nil according to
; whether or not there are free variables on the left-hand side of the rule.
; For subclass 'definition, var-info is a list that positionally associates
; each argument of lhs with the number of its occurrences in rhs.  Var-info is
; ignored for subclass 'meta.

                           var-info
                           .

; The match-free field should be :all or :once if there are free variables in
; the hypotheses, else nil.

                           match-free)

; See the warning above.

  nil)

; There are five subclasses of rewrite rule, distinguished by the :subclass
; slot.

; 'backchain - the traditional rewrite rule.  In this case, :heuristic-info is
;   the loop-stopper for the rule: a list of elements of the form (x y . fns),
;   indicating that in replacing lhs by rhs (the binding of) y moves forward to
;   the spot occupied by (the binding of) x, and that x and y only appear on
;   the left-hand side as arguments to functions in fns.  Thus, to prevent
;   loops we adopt the heuristic convention of replacing lhs by rhs only if
;   each y is smaller than the corresponding x, with respect to functions that
;   are considered "invisible" if they are invisible with respect to every
;   function in fns.

; 'abbreviation - the special case where there are no hyps, a nil loop-stopper,
;   and the rhs satisfies the abbreviationp predicate.  Heuristic-info is
;   irrelevant here.  Non-recursive definitions whose bodies are abbreviationps
;   are stored this way rather than as :subclass 'definition.

; 'meta - a rule justified by a metatheorem.  In this case, the lhs is the
;   metafunction symbol to be applied, and hyps is a function of one (term)
;   argument that generates a hypothesis for the metatheorem.  In this case the
;   :heuristic-info is of the form (name fn thm-name1 hyp-fn thm-name2)
;   . combined-arities-alist); see rewrite-with-lemma.

;   Rockwell Addition: The recursivep property used to be the fn name if the
;   fn in question was singly recursive.  Now it is a singleton list (fn).

; 'definition - a rule implementing a non-abbreviational definitional equation.
; In this case :heuristic-info is the pair (recursivep . controller-alist)
; where recursivep is nil (if this is a nonrec definition) or a truelist of
; symbols naming all the fns in the ``clique'' (singly recursive functions have
; a singleton list as their recursivep property); and controller-alist is an
; alist pairing each fn named in recursivep to a mask of t's and nil's in 1:1
; correspondence with the formals of the fn and indicating with t's which
; arguments control the recursion for this definition.

; 'rewrite-quoted-constant - rewrite rules that only apply to evgs.  See the
;  Essay on Rewriting Quoted Constants.  In this case, :heuristic-information
;  is a list (n . loop-stopper), where n is a natural number that the rule is of
;  Form [n] as discussed in the essay.

(defun relevant-ground-lemmas (hyp wrld)
  (mv-let (not-flg hyp)
          (strip-not hyp)
          (declare (ignore not-flg))
          (cond
           ((variablep hyp) nil)
           ((fquotep hyp) nil)
           ((flambda-applicationp hyp) nil)
           (t (getpropc (ffn-symb hyp) 'lemmas nil wrld)))))

(defun search-ground-units1
  (hyp unify-subst lemmas type-alist ens force-flg wrld ttree)
  (cond ((null lemmas) (mv nil unify-subst ttree nil))
        ((and (enabled-numep (access rewrite-rule (car lemmas) :nume) ens)
              (not (eq (access rewrite-rule (car lemmas) :subclass) 'meta))
              (null (access rewrite-rule (car lemmas) :hyps))
              (not (access rewrite-rule (car lemmas) :var-info))
              (geneqv-refinementp (access rewrite-rule (car lemmas) :equiv)
                                  *geneqv-iff*
                                  wrld))

; The tests above select enabled, non-meta, unconditional lemmas of
; the form (equiv lhs rhs), where equiv is a refinement of iff and lhs
; has no variables in it.  We do not know that rhs has no variables in
; it, but if it does, they can clearly be instantiated to whatever we
; wish and we will act as though they are instantiated with the
; corresponding variables of our current problem.  We now want to know
; if rhs is non-nil.  If it is, this lemma may be a way to establish
; hyp.

         (mv-let
          (knownp nilp nilp-ttree)
          (known-whether-nil (access rewrite-rule (car lemmas) :rhs)
                             type-alist
                             ens
                             force-flg
                             nil ; dwp
                             wrld
                             ttree)

; Observe that nilp-ttree extends ttree.  We may use either, depending on
; how things work out.

          (cond
           ((and knownp (not nilp))
            (mv-let (ans unify-subst)
                    (one-way-unify1 hyp
                                    (access rewrite-rule (car lemmas) :lhs)
                                    unify-subst)
                    (cond (ans
                           (let ((rune (access rewrite-rule (car lemmas) :rune)))
                             (with-accumulated-persistence
                              rune
                              (flg final-unify-subst final-ttree final-lemmas)
                              t
                              (mv t
                                  unify-subst
                                  (push-lemma (geneqv-refinementp
                                               (access rewrite-rule (car lemmas) :equiv)
                                               *geneqv-iff*
                                               wrld)
                                              (push-lemma rune nilp-ttree))
                                  (cdr lemmas)))))
                          (t (search-ground-units1
                              hyp unify-subst
                              (cdr lemmas)
                              type-alist ens force-flg wrld ttree)))))
           (t (search-ground-units1 hyp unify-subst
                                    (cdr lemmas)
                                    type-alist ens force-flg wrld ttree)))))
        (t (search-ground-units1 hyp unify-subst
                                 (cdr lemmas)
                                 type-alist ens force-flg wrld ttree))))

(defun search-ground-units
  (hyp unify-subst type-alist ens force-flg wrld ttree)

; This function is like lookup-hyp except we search through the ground unit
; rewrite lemmas.  We are a No-Change Loser with three values: the win flag,
; the new unify-subst, and a new ttree.

  (let ((lemmas (relevant-ground-lemmas hyp wrld)))
    (mv-let (winp unify-subst ttree rest-lemmas)
            (search-ground-units1
             hyp unify-subst lemmas type-alist ens force-flg wrld ttree)
            (declare (ignore rest-lemmas))
            (mv winp unify-subst ttree))))

(defun if-tautologyp (term)
  (declare (xargs :guard (pseudo-termp term)))

; This function returns T or NIL according to whether TERM is or is
; not an if-tautologyp.  A term is an if-tautology provided that under
; all (a) assignments of functions to the non-IF function symbols in
; the term and (b) assignments of objects to the variables in the
; term, the value of the term, (using the usual interpretation of IF
; and QUOTE and any Boolean commutative interpretations for EQUAL and
; IFF) is non-NIL. Every if-tautology is true, but one cannot conclude
; from the fact that a term is not an if-tautologyp that it is not
; true!  Note that we do not attach any ``semantics'' to the built-ins
; besides IF, QUOTEd objects, and the little we know about EQUAL and
; IFF.  For example, (IF (EQUAL A B) (EQUAL B A) 'T) is an
; if-tautology, but (IF (equiv A B) (equiv B A) 'T) for any symbol
; equiv other than EQUAL and IFF is not.

  (posp (if-interp (splice-instrs (if-compile term t nil nil))
                   nil nil nil nil

; The choice of 100000 below is rather arbitrary, determined by
; experimentation.  It is the limit for the number of if-interp steps.  It is
; probably fair to view this limit as a hack, but after all, Boolean
; decidability is NP-hard.

                   100000)))

(mutual-recursion

; Warning: For both functions in this nest, fns should be a subset of
; the keys of *bbody-alist*.  See the error related to
; *bbody-alist* in chk-acceptable-definition-install-body.

(defun expand-some-non-rec-fns (fns term wrld)

; We forcibly expand all calls in term of the fns in fns.  They better
; all be non-recursive or this may take a while.

; We assume that fns is a subset of the keys of *bbody-alist*.

  (cond ((variablep term) term)
        ((fquotep term) term)
        (t (let ((args (expand-some-non-rec-fns-lst fns (fargs term) wrld)))
             (cond ((member-equal (ffn-symb term) fns)
                    (subcor-var (formals (ffn-symb term) wrld)
                                args
                                (bbody (ffn-symb term))))
                   (t (cons-term (ffn-symb term) args)))))))

(defun expand-some-non-rec-fns-lst (fns lst wrld)
  (cond ((null lst) nil)
        (t (cons (expand-some-non-rec-fns fns (car lst) wrld)
                 (expand-some-non-rec-fns-lst fns (cdr lst) wrld)))))

)

(defun tautologyp (term wrld)

; Warning: Keep this list below of function names in sync with those in
; possible-trivial-clause-p.

; If this function returns t, then term is a theorem.  With the intended
; application in mind, namely the recognition of "trivial corollaries" while
; processing rule classes, we check for the "most common" tautology, (implies p
; p).  Otherwise, we expand certain non-recursive fns and see if the result is
; an if-tautology.  This function can be made as fancy as you want, as long as
; it recognizes theorems.

  (cond ((and (ffn-symb-p term 'implies)
              (equal (fargn term 1) (fargn term 2)))
         t)
        (t (if-tautologyp
            (expand-some-non-rec-fns

; The list of functions expanded is arbitrary, but they must all be
; non-recursively defined; indeed, because of the use of bbody in the
; definition of expand-some-non-rec-fns, these function must all belong to
; *definition-minimal-theory*.  Guards are permitted but of course it is the
; guarded body that we substitute.  The IF tautology checker doesn't know
; anything about any function symbol besides IF and NOT (and QUOTEd constants).
; The list below pretty obviously has to include IMPLIES and IFF.  It should
; not include NOT.

; The list is in fact *expandable-boot-strap-non-rec-fns* with NOT deleted and
; IFF added.  The main idea here is to include non-rec functions that users
; typically put into the elegant statements of theorems.  If functions are
; added to this list, consider changing the quoted constant in
; expand-abbreviations and, if the functions are not also added to
; *expandable-boot-strap-non-rec-fns*, the constant
; *definition-minimal-theory*, used in translate-in-theory-hint.  Consider also
; preprocess-clause and the error pertaining to *definition-minimal-theory* in
; chk-acceptable-definition-install-body.

             '(iff
               ;not
               implies eq atom eql = /= null

; If we ever make 1+ and 1- functions again, they should go back on this list.

               zerop synp return-last plusp minusp listp mv-list cons-with-hint
               wormhole-eval force case-split double-rewrite)
             term wrld)))))

; Rockwell Addition: The reason we changed the recursivep property is
; that we frequently ask whether there is a recursive fn on the
; fnstack and now we don't have to go to the property list to answer.
; Read the comment below.

(defun being-openedp-rec (fn fnstack)

; We determine whether fn is ``on'' fnstack (including being a member of a
; mutually recursive clique).

; The fnstack used by the rewriter is a list.  Each element is one of four
; shapes:

; (1) a function symbol -- we are expanding a definition of that symbol and the
; symbol is non-recursively defined.

; (2) a list of function symbols -- we are expanding a singly or mutually
; recursive function.  (In fact, the fnstack element is the recursivep flag of
; the function we're expanding.)

; (3) a list of the form (:term . term) for some term, term -- we are rewriting
; the indicated term (through the recursive dive in the rewriter that rewrites
; the just-rewritten term).  See the extended comment in fnstack-term-member
; for an explanation and example.

; (4) the symbol :rewrite-lambda-object -- we are in the process of rewriting a
; lambda object.

; Lambda-expressions are never pushed onto the fnstack even though fn may be a
; lambda-expression.

  (cond ((null fnstack) nil)
        ((consp (car fnstack))
         (or (eq fn (caar fnstack)) ; and hence (not (eq (caar fnstack) :term))
             (being-openedp-rec fn (cdr fnstack))))
        (t (or (eq fn (car fnstack))
               (being-openedp-rec fn (cdr fnstack))))))

(defstub being-openedp-limited-for-nonrec () t)
(defattach being-openedp-limited-for-nonrec constant-t-function-arity-0)

(defmacro being-openedp (fn fnstack clique settled-down-p)

; We found a 1.8% slowdown when we modified the code, in a preliminary cut at
; Version_2.7, to improve the speed of being-openedp when large cliques are on
; the fnstack by looking up the representative of fn on the fnstack, rather
; than looking up fn itself.  Presumably that slowdown resulted from the new
; calls to getprop to get the 'recursivep property (back when we used it for
; this purpose, through Version_2.9.4).  Here we avoid computing that getprop
; (in the case that clique is a getprop expression) in a case we suspect is
; pretty common: fnstack is empty.  The fnstack argument will always be a
; symbolp expression, so we do not need to let-bind it below.

  (declare (xargs :guard (symbolp fnstack)))
  `(and ,fnstack
        (let ((clique ,clique))
          (and (or clique

; At one time this fnstack check could completely stop the opening up of a
; non-recursive function call.  After Version_8.3 we decided that we would like
; to avoid making that stop (based on an example that arose), but for backward
; compatibility we defeat this fnstack check only when "desperate": when
; simplification of the clause has just settled down (before attempting to
; eliminate destructors).  An attachable function allows the original, full
; being-openedp check to take place after all.

                   (not ,settled-down-p)
                   (not (being-openedp-limited-for-nonrec)))
               (being-openedp-rec (if clique
                                      (car clique)
                                    ,fn)
                                  ,fnstack)))))

(defun recursive-fn-on-fnstackp (fnstack)

; We return t iff there is an element of fnstack that is recursively
; defined.  We assume that any mutually recursive clique on the stack
; is truly indicative of mutual recursion.  See the description of the
; fnstack in being-openedp.

  (cond ((null fnstack) nil)
        ((and (consp (car fnstack))
              (not (eq (caar fnstack) :term)))
         t)
        (t (recursive-fn-on-fnstackp (cdr fnstack)))))

(defun fnstack-term-member (term fnstack)

; If we are not careful, the call (rewrite rewritten-body ...) in
; rewrite-fncall can cause an infinite loop.  Here we describe a mechanism for
; avoiding such loops.  This mechanism is enforced by the call to
; fnstack-term-member in rewrite-fncall, which must return nil before opening
; up a function call.

; The problem is the interaction between opening up function definitions and
; use of equalities on the type-alist.  Suppose that (foo x) is defined to be
; (bar (foo (cdr x))) in a certain case.  But imagine that on the type-alist we
; have (foo (cdr x)) = (foo x).  Then rewritten-body, here, is (bar (foo x)).
; Because it contains a rewritable call we rewrite it again.  If we do so with
; the old fnstack, we will open (foo x) to (bar (foo x)) again and infinitely
; regress.

; The following event list illustrates the problem we wish to avoid.
; (defun bar (x) (declare (ignore x)) 7)
; (in-theory (disable bar))
; (defun foo (x)
;  (if (consp x) (bar (foo (cdr x))) t))
; :brr t
; :monitor (:definition foo) t
; (thm (implies (and (consp x) (equal (foo x) (foo uuu))) (not (equal (foo (cdr x)) (foo x)))))
; :eval
; :eval
; :eval
; ...

; Doing a :path after the :evals shows an infinite regress rewriting (foo x).
; The problem is that lit 3 is on the type-alist and causes (foo (cdr x)) to
; rewrite to (foo x).  Thus, when (foo x) in lit 2 is rewritten it first goes
; to (bar (foo (cdr x))) and thence to (bar (foo x)).

; This same loop occurs in Nqthm, though it has never been fired in anger, as
; far as we know.

; In Version 2.5 and before we handled this rare loop in a very non-rugged way,
; using fnstack unchanged in the aforementioned recursive call (rewrite
; rewritten-body ...): If the term we're expanding reoccurs in the rewritten
; body, we won't rewrite the rewritten body.  In that approach, if we're
; expanding (foo x a) and it rewrites to (bar (foo (cdr x) a)) and thence to
; (bar (foo x a)), we'll break the loop.  BUT if it goes instead to (bar (foo x
; a')), we'll just naively go around the loop.

; Starting with Version_2.6, we extended fnstack with (:term . term) in that
; recursive call to rewrite.  Through Version_2.8, before making that recursive
; call we first checked the fnstack to see if an entry (:term . x) was already
; there for some subterm x of rewritten-body.  This was the only place that we
; paid attention to elements of fnstack of the form (:term . x).

; Starting with Version_2.9, we do a simpler check for membership of (:term
; . term) in the fnstack.  (The present function implements that membership
; check without the need to cons up (:term . term).)  The unique such check is
; done where it makes the most sense: just before we open up a function call in
; rewrite-fncall.

; Here is an example based on a script sent by Andrew Feist that causes an
; infinite loop in Version 2.5 but not in Version 2.6 (but using :dir :system
; as introduced in 2.8).

;  (include-book "arithmetic/top-with-meta" :dir :system)
;
;  (defun a (x)
;    (cond
;     ((not (integerp x)) nil)
;     ((< x 1) nil)
;     ((= x 1) 1)
;     ((= x 2) 2)
;     ((= x 3) 24)
;     (t (/ (- (* 6 (expt (a (1- x)) 2) (a (- x 3)))
;              (* 8 (a (1- x)) (expt (a (- x 2)) 2)))
;           (* (a (- x 2)) (a (- x 3)))))))
;
;  (defun e (x) ; product from i=1 to x-1 of 2^i - 1
;    (if (not (integerp x))
;        0
;      (if (< x 2)
;          1
;        (* (+ (expt 2 x) (- 1)) (e (1- x))))))
;
;  (defun d (x)
;    (cond
;     ((not (integerp x)) nil)
;     ((< x 1) nil)
;     (t (* (expt 2 (/ (* x (1- x)) 2)) (e (1- x))))))
;
;  ; Added to Andrew's script:
;  (in-theory (disable exponents-add))
;
;  (defthm lemma-a-is-d ; doesn't prove, but at least it avoids the loop
;    (= (a x) (d x)))

; We can execute the following trace forms if in GCL, in which case we should see
; the trace output shown below in Version  2.5 and before.

;  (trace (rewrite-fncall
;          :cond (eq (cadr (access rewrite-rule (car si::arglist) :rune)) 'expt)
;          :entry (list (cadr si::arglist) (nth 7 si::arglist))
;          :exit (car si::values)))

;  (trace (rewrite
;          :entry (list (car si::arglist) (nth 8 si::arglist))
;          :exit (car si::values)))
;
;                     114> (REWRITE-FNCALL (EXPT '2 (BINARY-+ '-2 X))
;                                     (E))>
;                     115> (REWRITE
;                          (IF (ZIP I)
;                              '1
;                              (IF (EQUAL (FIX R) '0)
;                                  '0
;                                  (IF (< '0 I)
;                                      (BINARY-* R (EXPT R (BINARY-+ I '-1)))
;                                      (BINARY-* (UNARY-/ R)
;                                                (EXPT R (BINARY-+ I '1))))))
;                          (EXPT E))>
; ...............................
;                     120> (REWRITE-FNCALL (EXPT '2 (BINARY-+ '-1 X))
;                                     (EXPT E))>
;                     <120 (REWRITE-FNCALL EXPT '2
;                                     (BINARY-+ '-1 X))>
; ...............................
;                     <115 (REWRITE BINARY-* '1/2
;                              (EXPT '2 (BINARY-+ '-1 X)))>
;                     115> (REWRITE (BINARY-* '1/2
;                                        (EXPT '2 (BINARY-+ '-1 X)))
;                              (E))>
; [never returns from this final 115, hence never returns from 114]

; But our solution at that point (described above for Version_2.6) did not
; prevent an infinite loop in Version_2.8 for the following example, sent by
; Fares Fraij.

;  (defun get-constant (n classfile)
;    (let ((temp (assoc n classfile)))
;      (cond ((null temp) nil)
;            ((stringp (cadr temp)) (cadr temp))
;            ((or (not (natp n))
;                 (not (natp (cadr temp)))
;                 (<= n (cadr temp)))
;             nil)
;            (t (get-constant (cadr temp) classfile)))))

;  (defun get-constant-path (n classfile)
;    (let ((temp (assoc n classfile)))
;      (cond ((null temp) nil)
;            (t   (if (or (stringp (cadr temp))
;                         (not (natp n))
;                         (not (natp (cadr temp)))
;                         (<= n (cadr temp)))
;                     (list n)
;                   (cons n (get-constant-path (cadr temp) classfile)))))))

;  (defthm member-position-path-get-constant-n-1
;    (implies (member position (get-constant-path n classfile))
;             (equal (get-constant n classfile)
;                    (get-constant position classfile))))

; The final defthm above caused an infinite loop.  The fnstack had plenty of
; copies of (:TERM GET-CONSTANT N CLASSFILE), yet the loop was caused by
; repeated opening up of (GET-CONSTANT N CLASSFILE)!  How could this happen?
; The rewritten-body was (GET-CONSTANT POSITION CLASSFILE), so our test for
; membership in fnstack returned nil, and we went ahead and rewrote the
; rewritten-body.  That rewrite was in a context where POSITION is known to
; equal N, so POSITION rewrote to N, and we found ourselves with a new call of
; (GET-CONSTANT N CLASSFILE).

; So now we do the fnstack check for (:term . term) even before opening up the
; function call.

  (cond ((null fnstack) nil)
        ((and (consp (car fnstack))
              (eq (caar fnstack) :term)
              (equal (cdar fnstack) term))
         t)
        (t (fnstack-term-member term (cdr fnstack)))))

; Essay on Too-many-ifs

; The discussion below applies to a long-standing "too-many-ifs" heuristic that
; is used only for nonrecursive function applications when no recursive
; function application is on the stack.  Up through Version_3.6.1, we always
; rewrote the body of nonrecursive function calls and then applied this
; heuristic.  After Version_3.6.1, we modified this heuristic to avoid
; rewriting the bodies of some such calls, by calling a version of the function
; first on unrewritten bodies and then, possibly again, after rewriting.  This
; gives rise to two functions, too-many-ifs-pre-rewrite and
; too-many-ifs-post-rewrite.

; Let args be the list of actuals to a nonrec fn.  We wish to determine whether
; the expansion of the fn call introduces too many IFs all at once into the
; rewritten body of fn.  Our motivation comes from an example like (M2 (ZTAK &
; & &) (ZTAK & & &) (ZTAK & & &)) where the careless opening up of everybody
; produces a formula with several hundred IFs in it because of M2's duplication
; of the IFs coming from the simplification of the ZTAKs.  An early thought was
; never to expand a nonrec fn -- at the top level of the clause -- if it had
; some IFs in its args and to wait till CLAUSIFY has cleaned things up.  That
; slowed a proveall down by a factor of 2 -- and by a factor of 13 in
; PRIME-LIST-TIMES-LIST -- because of the ridiculously slow expansion of such
; basic nonrec fns as AND, OR, NOT, and NLISTP.

; This heuristic originally took ARGS and the rewritten right-hand side of fn,
; VAL, and computed something like

; (> (ITERATE FOR ARG IN ARGS SUM (* (COUNT-IFS ARG) (OCCUR-CNT ARG VAL)))
;    (ITERATE FOR ARG IN ARGS SUM (COUNT-IFS ARG)))

; where the OCCUR-CNT counted the number of times ARG occurred in VAL.  The
; heuristic was slightly optimized by observing that if no IFs occur in any arg
; then there is no point in doing the OCCUR-CNTs and that once the left hand
; side has been pushed beyond the right there is no point in continuing.  (We
; say "something like" because the code, at least as of Version_3.6.1,
; double-counted an ARG when it was a subterm of some other arg in ARGS.)

; However, when Sol Swords profiled some book certification typically done at
; Centaur, his results suggested that nearly half of the rewriting and 15% of
; the total time (where 45% of the total time seemed to be in include-book-fn)
; was spent in too-many-ifs.  It turns out that we can save most of the
; too-many-ifs time by doing a preliminary check, before rewriting the
; right-hand-side, to see if it is "expected" (in some very inexact sense) that
; the right-hand-side would have too-many-ifs.  The function
; too-many-ifs-pre-rewrite does this check using the unrewritten body, which
; not only saves potential rewriting but also can be faster because the unrewritten
; body is often much smaller than the rewritten body.

; At one point we avoided too-many-ifs-post-rewrite entirely, which pushed our
; savings above 20%.  But we had failures in the regression suite:
; collect-times-1d in books/arithmetic-2/meta/common-meta.lisp and
; sum-pp4-reduce-to in books/rtl/rel7/support/lib1.delta1/mult-proofs.lisp.  In
; these cases, the proof failed because the new heuristic stopped fix from
; opening up, while the original heuristic allowed (fix x) to open up for the
; particular x at hand because (acl2-numberp x) simplified to t.  We solved
; that problem: at first we made an exception for fix, but now we simply
; ignored occurrences in test positions of calls of IF when counting argument
; occurrences in right-hand-sides of definition rules (see var-counts).

; Lemma make-shared-variables-dag-as-term-l-lemma in community book
; books/defexec/dag-unification/terms-as-dag.lisp is a good test case: it
; proves using the old heuristic but seems difficult to prove using the new
; heuristic (too-many-ifs-pre-rewrite) alone.  It is also notable in that if
; memory serves, the new heuristic specifically fails on lambdas.  We are
; pretty happy with our current implementation, which is a compromise: Use
; too-many-ifs-pre-rewrite to avoid opening up the right-hand side of a
; definition at all in some cases, but even if we do open it up, use
; too-many-ifs-post-rewrite to apply the old too-many-ifs heuristic.

(mutual-recursion

(defun var-counts1 (arg rhs acc)

; See the comment in var-counts.

  (declare (xargs :guard (and (pseudo-termp rhs)
                              (natp acc))
                  :verify-guards nil))
  (cond ((equal arg rhs)
         (1+ acc))
        ((variablep rhs)
         acc)
        ((fquotep rhs)
         acc)
        ((eq (ffn-symb rhs) 'if)
         (max (var-counts1 arg (fargn rhs 2) acc)
              (var-counts1 arg (fargn rhs 3) acc)))
        (t (var-counts1-lst arg (fargs rhs) acc))))

(defun var-counts1-lst (arg lst acc)
  (declare (xargs :guard (and (pseudo-term-listp lst)
                              (natp acc))))
  (cond ((endp lst) acc)
        (t (var-counts1-lst arg
                            (cdr lst)
                            (var-counts1 arg (car lst) acc)))))
)

(defun var-counts (lhs-args rhs)

; Return a list of natural numbers that corresponds positionally to lhs-args,
; where the nth element of the returned list is an approximation to the number
; of occurrences of the nth element of lhs-args in rhs.  Normally lhs-args will
; be a list of variables -- hence the name -- though it can be the arguments to
; any call on the left-hand side of a definition rule.

; More precisely, the return value is used in the too-many-ifs-pre-rewrite
; heuristic, as a list of possible occurrences of each arg (formal) in the rhs
; of a given definition.  Larger elements of var-counts make it more likely
; that the given definition will not be opened up (or if it is, then that it
; will be closed back up again).

; Our algorithm ignores occurrences of elements of lhs-args in test positions
; of calls of IF, and for such calls, it takes maxima for the true and false
; branches; see var-counts1.  These decisions are merely heuristic, and might
; benefit from further experimentation, though we are pretty happy with current
; performance based on tests to date.  But our decisions deserve some remarks:

; Note that the var-counts are used before attempting to rewrite the rhs.  If
; we wished, var-counts could return a trivial result consisting of a list of
; zeroes from var-counts; as a result we will always rewrite the rhs.  But we
; want to short-circuit that rewrite when it seems reasonable to do so, such as
; when we have pretty good reason to believe that the too-many-ifs heuristic
; used _after_ rewriting would reject opening up the definition anyhow.

; For us to have good reason, we should be careful not to have the returned
; var-counts be too large, which could make it too easy to reject the
; opening-up.  For this reason, we ignore occurrences in test positions of
; calls of IF, since we can imagine those may disappear after the instantiated
; rhs is simplified.  But we don't want the var-counts to be too small, since
; then we might miss opportunities for efficiencies in early termination.  We
; might for example get all zeroes if we always take the minimum of var-counts
; in the two branches of any IF call, since it could often be the case that a
; formal parameter only occurs in one of the two branches.

; So, we take the maximum of two branches of any IF call.  In an early
; experiment we had good results taking the sum rather than the maximum: only a
; couple of proofs failed during ACL2 regression, and we got a 20% speed-up on
; a test provided by Sol Swords on certification done at Centaur.  But the sum
; is too large if we really imagine the IF tests simplifying away, so we take
; the maximum as a sort of compromise between the sum and the minimum (which
; could easily be too small, as explained above).

  (declare (xargs :guard (and (true-listp lhs-args)
                              (pseudo-termp rhs))))

  (cond ((endp lhs-args) nil)
        (t (cons (var-counts1 (car lhs-args) rhs 0)
                 (var-counts (cdr lhs-args) rhs)))))

(mutual-recursion

(defun count-ifs (term)
  (declare (xargs :guard (pseudo-termp term)))
  (cond ((variablep term) 0)
        ((fquotep term) 0)
        ((eq (ffn-symb term) 'hide) 0)
        ((eq (ffn-symb term) 'if)
         (+ 1
            (count-ifs (fargn term 1))
            (count-ifs (fargn term 2))
            (count-ifs (fargn term 3))))
        (t (count-ifs-lst (fargs term)))))

(defun count-ifs-lst (lst)
  (declare (xargs :guard (pseudo-term-listp lst)))
  (cond ((endp lst) 0)
        (t (+ (count-ifs (car lst))
              (count-ifs-lst (cdr lst))))))

)

; We originally defined nat-listp here and used it in the guards of
; too-many-ifs0 and too-many-ifs-pre-rewrite, but several community books had
; conflicts with this definition of nat-listp, as follows:

; workshops/2004/ruiz-et-al/support/terms-as-dag.lisp
; workshops/2003/sumners/support/n2n.lisp
; workshops/2009/kaufmann-kornerup-reitblatt/support/preliminaries.lisp
; concurrent-programs/bakery/measures.lisp
; unicode/nat-listp.lisp
; defexec/dag-unification/terms-as-dag.lisp

; So we have commented out this definition.  If we decide to use it after all,
; change integer-listp to nat-listp in the two guards mentioned above and also
; in community book books/system/too-many-ifs.lisp, as indicated there.

; (defun nat-listp (x)
;   (declare (xargs :guard t))
;   (cond ((atom x)
;          (equal x nil))
;         (t (and (natp (car x))
;                 (nat-listp (cdr x))))))

(defun too-many-ifs0 (args counts diff ctx)

; See also too-many-ifs-pre-rewrite.

; Diff is (- dot-product count-ifs), where count-ifs is the sum of the
; count-ifs of the args already processed and dot-product is the dot-product of
; the vector of those count-ifs and the counts already processed.

  (declare (type #.*fixnum-type* diff)
           (xargs :guard (and (pseudo-term-listp args)
                              (integer-listp counts)
                              (equal (len args) (len counts)))))
  (cond ((endp args) (> diff 0))
        ((eql (car counts) 1)

; Then (count-ifs (car args)) will contribute nothing to diff.

         (too-many-ifs0 (cdr args) (cdr counts) diff ctx))
        (t
         (let ((count1 (the-fixnum! (count-ifs (car args)) ctx)))
           (declare (type #.*fixnat-type* count1))
           (too-many-ifs0 (cdr args)
                          (cdr counts)
                          (the-fixnum! (+ (the-fixnum! (* count1
                                                          (1- (car counts)))
                                                       ctx)
                                          diff)
                                       ctx)
                          ctx)))))

(defproxy too-many-ifs-pre-rewrite (* *) => *)

(defun too-many-ifs-pre-rewrite-builtin (args counts)

; See the Essay on Too-many-ifs.

; Args is the left-hand-side of a definition rule, hence most commonly the
; formal parameters of some function.  Counts is a list that corresponds
; positionally to args, and represents the number of occurrences of each
; element of args in the right-hand-side of the implicit definition rule.
; (For details on how counts is computed, see var-counts.)

  (declare (xargs :guard (and (pseudo-term-listp args)
                              (integer-listp counts)
                              (equal (len args) (len counts)))))

  (too-many-ifs0 args counts 0 'too-many-ifs-pre-rewrite))

(defattach (too-many-ifs-pre-rewrite too-many-ifs-pre-rewrite-builtin)
  :skip-checks t)

; This dead code could be deleted, but we leave it as documentation for
; occur-cnt-bounded.

; (mutual-recursion
;
; (defun occur-cnt-rec (term1 term2 acc)
;
; ; Return a lower bound on the number of times term1 occurs in term2.
; ; We do not go inside of quotes.
;
;   (cond ((equal term1 term2) (1+ acc))
;         ((variablep term2) acc)
;         ((fquotep term2) acc)
;         (t (occur-cnt-lst term1 (fargs term2) acc))))
;
; (defun occur-cnt-lst (term1 lst acc)
;   (cond ((null lst) acc)
;         (t (occur-cnt-rec term1
;                           (car lst)
;                           (occur-cnt-lst term1 (cdr lst) acc)))))
; )
;
; (defun occur-cnt (term1 term2)
;   (occur-cnt-rec term1 term2 0))

(mutual-recursion

(defun occur-cnt-bounded (term1 term2 a m bound-m)

; Let bound = (+ m bound-m).  Return (+ a (* m (occur-cnt term1 term2))) unless
; it exceeds bound, in which case return -1.  We assume (<= a bound).

; Occur-cnt is no longer defined, but was defined (as is this function) so as
; not to go inside of quotes, returning a lower bound on the number of times
; term1 occurs in term2.

  (declare (type #.*fixnum-type* a m bound-m)
           (xargs :measure (acl2-count term2)
                  :ruler-extenders (:lambdas)
                  :guard (and (pseudo-termp term2)
                              (signed-byte-p *fixnum-bits* (+ bound-m m))
                              (<= 0 a)
                              (<= 0 m)
                              (<= 0 bound-m)
                              (<= a (+ bound-m m)))
                  :verify-guards nil))
  (the-fixnum
   (cond ((equal term1 term2)
          (if (<= a bound-m)
              (the-fixnum (+ a m))
            -1))
         ((variablep term2) a)
         ((fquotep term2) a)
         (t (occur-cnt-bounded-lst term1 (fargs term2) a m bound-m)))))

(defun occur-cnt-bounded-lst (term1 lst a m bound-m)
  (declare (type #.*fixnum-type* a m bound-m)
           (xargs :measure (acl2-count lst)
                  :ruler-extenders (:lambdas)
                  :guard (and (pseudo-term-listp lst)
                              (signed-byte-p *fixnum-bits* (+ bound-m m))
                              (<= 0 a)
                              (<= 0 m)
                              (<= 0 bound-m)
                              (<= a (+ bound-m m)))))
  (the-fixnum
   (cond ((endp lst) a)
         (t (let ((new (occur-cnt-bounded term1 (car lst) a m bound-m)))
              (declare (type #.*fixnum-type* new))
              (if (eql new -1)
                  -1
                (occur-cnt-bounded-lst term1 (cdr lst) new m bound-m)))))))
)

(defun too-many-ifs1 (args val lhs rhs ctx)

; See also too-many-ifs-post-rewrite-builtin.

; We assume (<= lhs rhs).

  (declare (type #.*fixnum-type* lhs rhs)
           (xargs :guard (and (pseudo-term-listp args)
                              (pseudo-termp val)
                              (<= 0 lhs)
                              (<= lhs rhs)
                              (<= (count-ifs-lst args) rhs))))
  (cond
   ((endp args) nil)
   (t (let ((x (the-fixnum! (count-ifs (car args)) ctx)))
        (declare (type #.*fixnum-type* x))
        (cond ((eql x 0)
               (too-many-ifs1 (cdr args) val lhs rhs ctx))
              (t (let ((lhs
                        (occur-cnt-bounded (car args) val lhs x
                                           (the-fixnum (- rhs x)))))
                   (declare (type #.*fixnum-type* lhs))
                   (if (eql lhs -1)
                       -1
                     (too-many-ifs1 (cdr args) val lhs rhs ctx)))))))))

(defproxy too-many-ifs-post-rewrite (* *) => *)

(defun too-many-ifs-post-rewrite-builtin (args val)

; This function implements the part of the too-many-ifs heuristic after the
; right-hand-side of a definition has been rewritten, to see if that expansion
; is to be kept or thrown away.  See the Essay on Too-many-ifs.

  (declare (xargs :guard (and (pseudo-term-listp args)
                              (pseudo-termp val))))

  (let* ((ctx 'too-many-ifs-post-rewrite-builtin)
         (rhs (the-fixnum! (count-ifs-lst args) ctx)))
    (cond ((int= rhs 0) nil)
          (t (too-many-ifs1 args val 0 rhs ctx)))))

(defattach (too-many-ifs-post-rewrite too-many-ifs-post-rewrite-builtin)
  :skip-checks t)

(defun all-args-occur-in-top-clausep (args top-clause)
  (cond ((null args) t)
        (t (and (dumb-occur-lst (car args) top-clause)
                (all-args-occur-in-top-clausep (cdr args) top-clause)))))

(mutual-recursion

(defun max-form-count (term)

; This function is used in the control of recursive fn expansion.  Many years
; ago, we used the fn count part of var-fn-count in this role.  Then we decided
; that for controlling expansion we should not count (IF x y z) to have size
; 1+|x|+|y|+|z| because the IF will be distributed and the y or the z will rest
; in the argument position of the recursive call.  So we started to compute the
; maximum fn count in the branches.  Then we added explicit values (this really
; was years ago!) and decided not to consider 1000 to be better than 999, since
; otherwise (< x 1000) would open.  So we measure quoted constants by their
; Lisp size.

; But with the advent of the HONS version of ACL2, our concern mounted about
; the ability of ACL2 to handle very large ("galactic") objects.  Consider the
; following example, which caused ACL2 Version_3.4 to hang.

;    (defun big (n)
;      (cond ((posp n) (let ((x (big (1- n))))
;                        (cons x x)))
;            (t nil)))
;
;    (defun foo (x) (if (consp x) (foo (cdr x)) x))
;
;    (set-gag-mode nil)
;    (set-inhibit-output-lst '(prove proof-tree summary))
;
;    (thm (consp (foo (big 50)))
;         :hints (("Goal"
;                  :in-theory
;                  (disable (foo) (:type-prescription foo)))))
;

; Our solution is to bound the computation of size of explicit values, unlike
; the unbounded computation done through ACL2 Version_3.4.  There, we used a
; function, cons-count, that ignored the sizes of numeric explicit values,
; counting only conses.

; But just how should we bound the size computation for explicit values?

; It seems odd that the existing approach only counted conses, since there
; seems to be no obvious reason to treat the number of conses in a list
; differently from the number of (implicit) successor calls in a natural
; number.  Our first change was to ignore completely the sizes of explicit
; values, returning 0 in the fquotep case below.  Unfortunately, we then
; observed a failure in the event (verify-guards meta-integerp ...) in
; community book books/arithmetic-3/bind-free/integerp-meta.lisp.  We have
; extracted the following from that failure: This succeeded when using
; (cons-count (cadr term)) in the case (fquotep term) below, but not when using
; 0 in that case instead.

;  (thm (IMPLIES
;        (AND (PSEUDO-TERM-LISTP (CDR TERM))
;             (MEMBER-EQ (CAADR TERM)
;                        '(BINARY-+ BINARY-*)))
;        (PSEUDO-TERM-LISTP (LEAVES (CADDAR (CDR TERM))
;                                   (CAADR TERM)))))

; Our first fix was simply to count size of explicit values just as we do in
; some other places, using fn-count-evg in the fquotep case.  Unfortunately we
; got a failure in (verify-guards subtract-bag ...) in the same file as above,
; apparently because (mv-nth 1 x) now opens up to (cadr x).

; So for backward compatibility we now define a bounded version of cons-count.

; Notice that our bounded size computation can cause the "wrong" term to be
; viewed as the smaller, so we need to be confident that this is not a problem,
; and indeed it is not when we call max-form-count in smallest-common-subterms.

  (the #.*fixnat-type*
    (cond ((variablep term) 0)
          ((fquotep term) (cons-count-bounded (cadr term)))
          ((eq (ffn-symb term) 'if)
           (max (max-form-count (fargn term 2))
                (max-form-count (fargn term 3))))
          (t (max-form-count-lst (fargs term) 1)))))

(defun max-form-count-lst (lst acc)
  (declare (type #.*fixnat-type* acc))
  (the #.*fixnat-type*
    (cond ((>= acc (fn-count-evg-max-val))
           (fn-count-evg-max-val))
          ((null lst) acc)
          (t (max-form-count-lst (cdr lst)
                                 (+f acc (max-form-count (car lst))))))))

)

(defun controller-complexity1 (flg args controller-pocket)

; Flg is either t (meaning we measure the controllers) or nil
; (meaning we measure the non-controllers).  Args is the arg list
; to a call of a fn with the given controller pocket.

; In this implementation a controller pocket is a list of
; Booleans in 1:1 correspondence with the formals.  A t in an
; argument position indicates that the formal is a controller.

; We sum the max-form-counts of the arguments in controller (or
; non-controller, according to flg) positions.

  (cond ((null args) 0)
        ((eq (car controller-pocket) flg)
         (+ (max-form-count (car args))
            (controller-complexity1 flg
                                    (cdr args)
                                    (cdr controller-pocket))))
        (t (controller-complexity1 flg
                                   (cdr args)
                                   (cdr controller-pocket)))))

(defun controller-complexity (flg term controller-alist)

; Term is a call of some recursive fn in a mutually recursive clique.
; Controller-alist is an alist that assigns to each fn in the clique a
; controller-pocket.  We compute the controller complexity (or
; non-controller complexity, according to flg being t or nil) of term
; for the controller pocket assigned fn in the alist.

  (controller-complexity1 flg
                          (fargs term)
                          (cdr (assoc-eq (ffn-symb term)
                                         controller-alist))))

(defun controller-pocket-simplerp (call result controller-alist)

; Call has rewritten to something involving result.  Both call and
; result are applications of functions in the same mutually recursive
; clique.

; Controller-alist associates a fn in the clique to a controller
; pocket.  A controller pocket is a list in 1:1 correspondence with
; the formals of the fn with a t in those slots that are controllers
; and a nil in the others.  Thus, this alist assigns a complexity to
; both call and to result.

; We determine whether there controller-alist assigns a lower
; complexity to result than to call.

  (< (controller-complexity t result controller-alist)
     (controller-complexity t call controller-alist)))

(defun constant-controller-pocketp1 (args controller-pocket)
  (cond ((null args) t)
        ((car controller-pocket)
         (and (quotep (car args))
              (constant-controller-pocketp1 (cdr args)
                                            (cdr controller-pocket))))
        (t (constant-controller-pocketp1 (cdr args)
                                         (cdr controller-pocket)))))

(defun constant-controller-pocketp (term controller-alist)

; Term is a call of some fn in the clique for which controller-alist is
; a controller alist.  That alist assigns a controller-pocket to fn.
; We determine whether the controller arguments to fn in term are all
; quoted.

  (constant-controller-pocketp1 (fargs term)
                                (cdr (assoc-eq (ffn-symb term)
                                               controller-alist))))

(defun some-controller-pocket-constant-and-non-controller-simplerp
  (call result controller-alist)

; Call and result are both applications of functions in the same
; mutually recursive clique.  Controller-alist is an alist that assigns
; to each fn in the clique a controller pocket.  We determine whether
; that alist assigns controllers in such a way that the controllers of
; result are constant and the complexity of the non-controllers in
; result is less than that of the non-controllers in call.

  (and (constant-controller-pocketp result controller-alist)
       (< (controller-complexity nil result controller-alist)
          (controller-complexity nil call controller-alist))))

(mutual-recursion

(defun rewrite-fncallp (call result cliquep top-clause current-clause
                             controller-alist)

; Call has rewritten to (some term involving) result.  We want to know
; if we should replace call by result or leave the call unopened.  The
; ffn-symb of call is known to be a recursive function symbol, fn.  It
; is not a lambda-expression.  Cliquep is nil if fn is singly
; recursive and is the list of functions in fn's clique if it is
; mutually recursive.  Top-clause and current-clause are two clauses
; from simplify-clause0 (the input clause there and the result of
; removing trivial equations).  Controller-alist is the
; :controller-alist field of the def-body of fn.

; Controller-alist pairs every function in fn's mutually recursive
; clique with a controller pocket.  Thus, if fn is singly recursive,
; controller-alist looks like this:
; ((fn . controller-pocket)).
; But if fn is mutually recursive with clique fn1...fnm, then this
; alist assigns a controller pocket to each fni.

  (cond
   ((variablep result) t)
   ((fquotep result) t)
   ((flambda-applicationp result)

; This should not normally happen.  The only time we refuse to open a
; lambda-application is (a) we are at the top level of the clause and
; it has too many ifs, or (b) we were told not to open it by the user.
; But (a) can't have happened while we were constructing result
; because we were opening up a recursive fn.  Of course, the worry is
; that the body of this lambda-expression contains a recursive call
; that will somehow get loose and we will indefinitely recur.  But if
; the only way we get here is via case (b) above, we won't ever open
; this lambda and so we're safe.  We therefore act as though this
; lambda were just some ordinary function symbol.

    (rewrite-fncallp-listp call (fargs result)
                           cliquep
                           top-clause
                           current-clause
                           controller-alist))
   ((if cliquep
        (member-eq (ffn-symb result) cliquep)
      (eq (ffn-symb result) (ffn-symb call)))
    (and (or (all-args-occur-in-top-clausep (fargs result)
                                            top-clause)
             (dumb-occur-lst result current-clause)
             (controller-pocket-simplerp
              call
              result
              controller-alist)
             (some-controller-pocket-constant-and-non-controller-simplerp
              call
              result
              controller-alist))
         (rewrite-fncallp-listp call (fargs result)
                                cliquep
                                top-clause
                                current-clause
                                controller-alist)))
   (t (rewrite-fncallp-listp call (fargs result)
                             cliquep
                             top-clause
                             current-clause
                             controller-alist))))

(defun rewrite-fncallp-listp (call lst cliquep top-clause current-clause
                                   controller-alist)
  (cond ((null lst) t)
        (t (and (rewrite-fncallp call (car lst)
                                 cliquep
                                 top-clause
                                 current-clause
                                 controller-alist)
                (rewrite-fncallp-listp call (cdr lst)
                                       cliquep
                                       top-clause
                                       current-clause
                                       controller-alist)))))

)

(mutual-recursion

(defun contains-rewritable-callp (fn term cliquep
                                     terms-to-be-ignored-by-rewrite)

; This function scans the non-quote part of term and determines
; whether it contains a call, t, of any fn in the mutually recursive
; clique of fn, such that t is not on terms-to-be-ignored-by-rewrite.
; Fn is known to be a symbol, not a lambda-expression.  If cliquep is
; nil, fn is singly recursive.  Otherwise, cliquep is the list of
; functions in the clique (including fn).

  (cond ((variablep term) nil)
        ((fquotep term) nil)
        ((flambda-applicationp term)

; If term is a lambda-application then we know that it contains no recursive
; calls of fns in the clique, as described in the comment on the subject
; in rewrite-fncallp above.

         (contains-rewritable-callp-lst fn (fargs term)
                                        cliquep
                                        terms-to-be-ignored-by-rewrite))
        ((and (if cliquep
                  (member-eq (ffn-symb term) cliquep)
                (eq (ffn-symb term) fn))
              (not (member-equal term terms-to-be-ignored-by-rewrite)))
         t)
        (t (contains-rewritable-callp-lst fn (fargs term)
                                          cliquep
                                          terms-to-be-ignored-by-rewrite))))

(defun contains-rewritable-callp-lst (fn lst cliquep
                                         terms-to-be-ignored-by-rewrite)
  (cond ((null lst) nil)
        (t (or (contains-rewritable-callp fn (car lst)
                                          cliquep
                                          terms-to-be-ignored-by-rewrite)
               (contains-rewritable-callp-lst
                fn (cdr lst)
                cliquep
                terms-to-be-ignored-by-rewrite)))))

)

(defrec linear-lemma

; Warning: Do not change the cheap flag, currently nil, without revisiting
; macro get-rule-field.

  ((nume . hyps) max-term concl
   backchain-limit-lst rune
   .

; The match-free field should be :all or :once if there are free variables in
; the hypotheses, else nil.

   match-free)

; See the warning above.

  nil)

; Finally the Rewriter

(defrec current-literal (not-flg . atm) t)

(defrec rewrite-constant

; WARNING: If you change the layout of the rewrite-constant in a way that
; affects the position of :current-clause -- e.g., add a field -- you MUST
; change the definition in axioms.lisp of the function |Access REWRITE-CONSTANT
; record field CURRENT-CLAUSE|.  If you don't, however, the build will fail
; loudly (via a redefinition error).

; WARNING: If you change the layout of the rewrite-constant in a way that
; affects the position on :nonlinearp, you must change the guard on the
; definitions of nonlinearp-default-hint in (at least) the following
; community books:

; books/arithmetic-5/lib/basic-ops/default-hint.lisp  -- one occurrence
; books/hints/basic-tests.lisp -- two occurrences

; At the default-hint.lisp occurrence there is a handy comment explaining
; how to get the new guard.

; WARNING: The name "rewrite-constant" is a misnomer because it is not really
; constant during rewriting.  For example, the active-theory is frequently
; toggled.

; The Rewriter's ``Constant Argument'' -- rcnst

; In Nqthm the rewriter accessed many "special variables" -- variables
; bound outside the rewriter.  Some of these were true specials in the
; rewriter, in the sense that the rewriter sometimes re-bound them in its
; recursion.  An example of such a variable is fnstack, which is nil
; outside the rewriter and re-bound inside the rewriter only when we
; tentatively expand a function call.  But other Nqthm special variables
; were just constants -- as far as the rewriter was concerned.  For example,
; current-lit, the literal on which rewrite-clause called rewrite, is
; set outside the call of rewrite and read but never written inside.

; We package up these "rewrite constants" as a single record so that
; we can pass all of them in one argument.

; We list below some of the "constants" in question and where they are set.  We
; then give the meaning of each field.

;    field                           where set        soundness
; pt                               rewrite-clause         *
; current-literal                  rewrite-clause

; top-clause                       simplify-clause1
; current-clause                   simplify-clause1

; terms-to-be-ignored-by-rewrite   simplify-clause
; expand-lst                       simplify-clause

; fns-to-be-ignored-by-rewrite     prove

; rewriter-state                   add-linear-lemma

; The fields marked with *'s are involved in the soundness of the result
; of rewriting.  The rest are of heuristic use only.

; This is a balanced binary tree of depth 4 (first 12 fields) and 5 (last 8
; fields), constructed by the utility in books/tools/btree.lisp. The order in
; this record is based on a heuristic (syntactic, not dynamic) judgement of the
; frequency and cost of access and change (assuming change is about 3 times
; more expensive than access.  But changes to this ordering of tips has had
; almost insignificant impact on the time to do full regressions.  So don't
; overthink this.  Indeed, we adopted the balanced tree approach simply because
; it is just rational and doesn't strongly suggest that we've dynamically
; determined the frequency of access and change (as an ad hoc layout might).

  ((((CURRENT-ENABLED-STRUCTURE . PT)
     NONLINEARP . FORBIDDEN-FNS)
    (HEAVY-LINEARP . ONCEP-OVERRIDE)
    REWRITER-STATE . BACKCHAIN-LIMIT-RW)
   ((RESTRICTIONS-ALIST . CURRENT-LITERAL)
    CASE-SPLIT-LIMITATIONS . EXPAND-LST)
   ((TERMS-TO-BE-IGNORED-BY-REWRITE . ACTIVE-THEORY)
    FNS-TO-BE-IGNORED-BY-REWRITE
    . TOP-CLAUSE)
   (FORCE-INFO . CURRENT-CLAUSE)
   RW-CACHE-STATE . SPLITTER-OUTPUT)
  t)

; Active-theory is either :standard or :arithmetic.  (It was added first to
; Version_2.7.)  It is used to determine whether we are in the middle of
; rewriting arithmetic expressions in support of non-linear arithmetic.  This
; field is toggled during rewriting.  Thus, we put it at the front of the data
; structure.

; Current-enabled-structure is an enabled-structure that contains the theory
; which specifies which rules are to be considered enabled.

; Pt -- a parent tree (see Essay on Parent Trees) denoting a set of literals in
; current-clause and containing the one we are working on in rewrite-clause and
; all the others that have rewritten to false.  Any poly in the
; simplify-clause-pot-lst that depends on one of these literals is considered
; "inactive."  To avoid tail biting we do not use inactive polys.

; Restrictions-alist is used for :restrict hints.  (Someday we should flesh out
; this explanation.)

; Expand-lst -- a list of expand-hint structures used heuristically.  We
; automatically expand any term on this list when encountered.  It is set from
; the user's hint settings and by simplify-clause to force the expansion of the
; induction conclusion in post-induction, pre-settled down rewriting.

; Case-split-limitations -- typically (sr-limit (w state)), but can be set with
; a :case-split-limitations hint to override that default in the simplifier.

; Force-info -- t if there are no calls of IF in the :top-clause, else 'weak.

; Fns-to-be-ignored-by-rewrite -- a list of function symbols used
; heuristically.  If a term begins with one of these, we do not rewrite it.
; This is set from the user's hint settings.

; Terms-to-be-ignored-by-rewrite -- a list of terms used heuristically.  We do
; not rewrite any term on this list.  Simplify-clause sets it during the
; initial post-induction rewriting to prevent us from looking prematurely at
; the induction hypotheses (see simplify-clause for details).

; Top-clause -- the clause on which simplify-clause was called.  This is used
; heuristically only, to decide whether to expand function calls.  The
; difference between top-clause and current-clause is that current-clause has
; been subjected to remove-trivial-equations.

; Current-clause -- Top-clause with remove-trivial-equations.  This is used
; heuristically only.

; Current-literal -- a pair containing the not-flg and atm of the literal on
; which rewrite-clause is currently working.  It was probably used at one time
; to avoid biting our tail (see below), but parent trees now perform that
; function.  We leave :current-literal in the rewrite-constant in case there
; are tools that use it.

; Nonlinearp -- A boolean indicating whether nonlinear arithmetic should be
; considered to be active.

; Heavy-linearp -- Indicates whether linear arithmetic should rewrite terms to
; turn into polys and add linear lemmas.  When :heavy, do extra work when
; rewriting IF calls.

; We always obtain our rewrite-constant by loading relevant information into
; the following empty constant.  Warning: The constant below is dangerously
; useless less the current-enabled-structure is set to an enabled-structure.

(defconst *default-rw-cache-state*
  :atom)

(defconst *empty-rewrite-constant*
  (make rewrite-constant
        :active-theory :standard
        :rewriter-state nil
        :case-split-limitations nil
        :forbidden-fns nil
        :splitter-output t ; initial value of state global splitter-output
        :current-clause nil
        :current-enabled-structure nil
        :current-literal nil
        :expand-lst nil
        :fns-to-be-ignored-by-rewrite nil
        :force-info nil
        :nonlinearp nil
        :heavy-linearp t
        :oncep-override :clear
        :pt nil
        :restrictions-alist nil
        :rw-cache-state *default-rw-cache-state*
        :terms-to-be-ignored-by-rewrite nil
        :top-clause nil
        :backchain-limit-rw nil))

(defstub heavy-linear-p () t)
(defattach heavy-linear-p constant-nil-function-arity-0)

; So much for the rcnst.

(defrec metafunction-context

; WARNING: If you change the layout of this record you must change the PROGN in
; axioms.lisp that defines |Access METAFUNCTION-CONTEXT record field
; TYPE-ALIST| and the other record functions, because that form comes about by
; macroexpanding this defrec.  But if you don't change that PROGN, however, the
; build will fail loudly (via a redefinition error).

; WARNING: You must also change (at least) the definition of mfc-obj in
; books/arithmetic-5/lib/basic-ops/building-blocks.lisp.  Note that mfc-obj is
; guard-verifiable because it builds in the proper guard for (access
; metafunction-context mfc :obj) and then uses (cadr mfc) instead of the access
; form.  Similar issues arise around the rewrite-constant.  See the warning
; there about nonlinearp-default-hint.

; See the Essay on Metafunction Support, Part 1 for an explanation of the use
; of this record.

  (rdepth type-alist obj geneqv wrld fnstack ancestors backchain-limit
          simplify-clause-pot-lst rcnst gstack ttree unify-subst)
  t)

(defun ok-to-force (rcnst)

; Warning: In function push-warrants, we rely on the return value of
; ok-to-force being t or nil.

; We normally use the rewrite constant to determine whether forcing is enabled.
; At one time we experimented with a heuristic that allows the "force-flg" to
; be 'weak, meaning:  do not force if the resulting assumption has a variable
; that does not appear in its type-alist.  (Recall that its type-alist is used
; for the hypotheses of the corresponding goal in the forcing round.)  We still
; allow 'weak to be stored in the rewrite constant, and at the time of this
; writing, the heuristic just described is still implemented in
; force-assumption.  However, we found an example where this heuristic is too
; weak:  the presence of IF terms in the top-level clause is enough to cause
; bad assumptions to be forced, even though our heuristic permits does not
; filter out those bad assumptions.  So we have decided for now that the value
; 'weak from the :force-info field of the rewrite-constant, which is generated
; when there is an IF in the top-level clause, means:  do not force, period.
; (Note that forcing may still be used heuristically, for example by
; type-alist-clause; but, assumptions will not "get out" of such uses.)

  (let ((force-info (access rewrite-constant rcnst :force-info)))
    (cond
     ((eq force-info t)
      (and (enabled-numep *force-xnume*
                          (access rewrite-constant
                                  rcnst
                                  :current-enabled-structure))
           t))
     ((eq force-info 'weak)

; See comment above.

      nil)
     (t
      (er hard 'ok-to-force
          "OK-TO-FORCE called on apparently uninitialized rewrite constant, ~
           ~x0."
          rcnst)))))

; The next major concern is the fact that rewrite takes so many
; arguments.

; Rewrite takes so many arguments that we introduce a macro for
; calling it.  Many functions that call rewrite also take a lot of
; rewrite-type arguments and this macro can be used to call them too.
; Because all of these functions are mutually recursive with rewrite,
; we consider the use of this macro as an indication that we are
; entering the rewriter and have given it the name "rewrite-entry".

; For example, if you write:
;    (rewrite-entry (rewrite-if test left right alist))
; you get
;    (rewrite-if test left right alist type-alist ... rcnst ttree)

; And if you write:
;    (rewrite-entry (rewrite left alist 2)
;                   :ttree new-ttree)
; you get
;    (rewrite left alist 2 ... rcnst new-ttree)

; Note that in specifying which extra arguments you wish to set
; you must use the keyword form of the formal.  This implementation
; decision was made just to bring rewrite-entry into the same style
; as CLTL keyword args, which it resembles.

; The macro extends the given call by adding 12 extra arguments.
; The arguments used are the "extra formals" of rewrite, namely

;    ; &extra formals
;    rdepth type-alist obj geneqv wrld state fnstack ancestors
;    backchain-limit step-limit simplify-clause-pot-lst rcnst gstack ttree

; Important Note:  The string "&extra formals" is included where ever
; this list has been copied.

; However, for every extra formal for which the macro invocation
; specifies a value, that value is used instead.  Any function to be
; called via rewrite-entry should include the extra formals above
; explicitly in its defun, as the last 12 formals.

; Convention: Not every function uses all 12 of the extra formals.
; Ignored formals are so declared.  It is our convention when calling
; a function with an ignored formal to pass it nil in that slot.  That
; explains some (rewrite-entry (add-poly...) :obj nil...).  We could have
; just passed obj's current value, but that suffers from making the
; caller look like it uses obj when in fact obj might be ignored by it
; too.  This convention means that if one of these functions does
; begin to use a currently ignored formal, it will be necessary to
; remove the formal from the (declare (ignore ...)) and might cause us
; to think about the incoming value.

(defun plist-to-alist (lst)

; Convert '(key1 val1 key2 val2 ...) to '((key1 . val1) (key2 . val2) ...).
; In use here, the keys are all in the keyword package.

  (cond ((null lst) nil)
        (t (cons (cons (car lst) (cadr lst))
                 (plist-to-alist (cddr lst))))))

(defmacro adjust-rdepth (rdepth)

; Keep the following in sync with zero-depthp.

  #+acl2-rewrite-meter ; for stats on rewriter depth
  `(1+f ,rdepth)
  #-acl2-rewrite-meter ; normal case (no stats)
  `(1-f ,rdepth))

(defun add-rewrite-args (extra-formals keyword-extra-formals alist)

; extra-formals is '(type-alist ...)
; keyword-extra-formals is '(:type-alist ...)
; alist pairs keyword extra formals to terms

; We return a list in 1:1 correspondence with extra-formals.  The
; element corresponding to an extra-formal is the value specified by
; the alist if one is so specified, otherwise it is the extra-formal
; itself.

  (cond ((null extra-formals) nil)
        (t (cons (let ((pair (assoc-eq (car keyword-extra-formals)
                                       alist)))
                   (cond (pair (cdr pair))
                         (t (car extra-formals))))
                 (add-rewrite-args (cdr extra-formals)
                                   (cdr keyword-extra-formals)
                                   alist)))))

(defrec step-limit-record

; See the Essay on Step-limits.

; The state global 'step-limit-record is bound to one of these records at the
; start of an event by with-ctx-summarized (specifically, by the call of
; with-prover-step-limit in save-event-state-globals).  Then, :start is the
; initial value of state global 'last-step-limit for that event; :strictp
; indicates whether an error should occur if the step-limit is exceeded; and
; :sub-limit is the step-limit to use for sub-events, if any, where nil
; indicates that the sub-limit should be limited by the current step-limit.

  (start strictp . sub-limit)
  t)

(defun step-limit-start (state)

; Return the starting value of step-limit in the present context.  See defrec
; step-limit-record.

  (let ((rec (f-get-global 'step-limit-record state)))
    (cond (rec (access step-limit-record rec :start))
          (t (step-limit-from-table (w state))))))

(defun step-limit-strictp (state)

; Warning: Keep this in sync with code in with-prover-step-limit-fn near the
; comment there about step-limit-strictp.

; Return true if in the present context, we are to cause an error if the
; step-limit is exceeded.  See defrec step-limit-record.

  (let ((rec (f-get-global 'step-limit-record state)))
    (cond (rec (access step-limit-record rec :strictp))
          (t nil))))

(defun initial-step-limit (wrld state)

; Warning: Keep this in sync with code in with-prover-step-limit-fn near the
; comment there about initial-step-limit.

; See the Essay on Step-limits.

; This function returns the current step limit.  If 'step-limit-record has a
; non-nil value (see defrec step-limit-record), then we are already tracking
; step-limits in the state, so we return the value of 'last-step-limit.
; Otherwise the acl2-defaults-table is consulted for the step-limit.

  (declare (xargs :guard ; also needs rec, bound below, to be suitable
                  (and (plist-worldp wrld)
                       (alistp (table-alist 'acl2-defaults-table wrld))
                       (let ((val (cdr (assoc-eq :step-limit
                                                 (table-alist 'acl2-defaults-table
                                                              wrld)))))
                         (or (null val)
                             (and (natp val)
                                  (<= val *default-step-limit*))))
                       (state-p state)
                       (boundp-global 'step-limit-record state)
                       (boundp-global 'last-step-limit state))))
  (let ((rec (f-get-global 'step-limit-record state)))
    (cond (rec (or (access step-limit-record rec :sub-limit)
                   (f-get-global 'last-step-limit state)))
          (t (step-limit-from-table wrld)))))

(defun step-limit-error1 (ctx str start where state)
  (declare (ignorable state)) ; only used in raw Lisp
  #-acl2-loop-only
  (when *step-limit-error-p*
    (er-soft ctx "Step-limit" str start where)
    (setq *step-limit-error-p* 'error)
    (throw 'step-limit-tag ; irrelevant value
           t))
  (the #.*fixnum-type*
    (prog2$ (er hard? ctx str start where)
            -1)))

(defmacro step-limit-error (superior-context-p)

; If superior-context-p is t then we return an error triple; if it is nil, we
; return -1, possibly causing a hard error or a throw.

  (let ((str "The prover step-limit, which is ~x0 in the ~@1, has been ~
              exceeded.  See :DOC set-prover-step-limit.")
        (ctx ''step-limit))
    (cond
     (superior-context-p
      `(er-soft ,ctx "Step-limit"
                ,str
                (step-limit-start state)
                "context immediately above the one just completed"))
     (t
      `(the-fixnum
        (step-limit-error1 ,ctx
                           ,str
                           (step-limit-start state)
                           "current context"
                           state))))))

(defmacro decrement-step-limit (step-limit)

; We make this event a macro for improved performance.

  (declare (xargs :guard

; By insisting that the formal is a symbol, we guarantee that its repeated
; reference below does not result in repeated evaluation of other than the
; current binding of a symbol.

                  (symbolp step-limit)))
  `(the #.*fixnum-type*
        (cond
         ((< 0 (the-fixnum ,step-limit))
          (1-f ,step-limit))
         ((eql -1 (the-fixnum ,step-limit))
          -1)
         (t (assert$ (eql 0 (the-fixnum ,step-limit))
                     (cond ((step-limit-strictp state)
                            (step-limit-error nil))
                           (t -1)))))))

(defmacro rewrite-entry (&rest args)
  (declare (xargs :guard (and (true-listp args)
                              (consp (car args))
                              (keyword-value-listp (cdr args)))))
  (let* ((call0
          (append (car args)
                  (add-rewrite-args '( ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info
                                      wrld state
                                      fnstack ancestors
                                      backchain-limit
                                      simplify-clause-pot-lst
                                      rcnst gstack ttree)
                                    '( ; &extra formals -- keyword versions
                                      :rdepth :step-limit
                                      :type-alist :obj :geneqv :pequiv-info
                                      :wrld :state
                                      :fnstack :ancestors
                                      :backchain-limit
                                      :simplify-clause-pot-lst
                                      :rcnst :gstack :ttree)
                                    (plist-to-alist
                                     (if (eq (caar args) 'rewrite)
                                         (remove-keyword
                                          :step-limit ; dealt with below
                                          (cdr args))
                                       (cdr args))))))
         (call
          (cond
           ((not (eq (caar args) 'rewrite))
            call0)
           (t (let ((call1
                     `(let ((step-limit
                             (decrement-step-limit step-limit)))
                        (declare (type #.*fixnum-type* step-limit))
                        ,call0))
                    (step-limit-tail (assoc-keyword :step-limit (cdr args))))
                (cond (step-limit-tail
                       `(let ((step-limit ,(cadr step-limit-tail)))
                          ,call1))
                      (t call1)))))))
    #+acl2-loop-only
    call
    #-acl2-loop-only
    (if (member-eq (caar args)

; We could omit relieve-hyp-synp in the list below, even though it too calls
; push-gframe, because relieve-hyp-synp is not called under rewrite-entry.  But
; we add it just in case that changes.

                   '(rewrite rewrite-with-lemma add-terms-and-lemmas
                             add-linear-lemma non-linear-arithmetic
                             relieve-hyp-synp))

; We restore *deep-gstack* to its value from before the call.  We really only
; need to do that for dmr monitoring, so that there aren't stale frames on
; *deep-gstack* when printing both the gstack and pstk (see dmr-string).  But
; the prog1 and setq seem cheap so we clean up after ourselves in all cases.

; WARNING: Gstack must be bound where rewrite-entry is called for the above
; values of (caar args).

        `(cond ((or (f-get-global 'gstackp state)
                    (f-get-global 'dmrp state))

; We could call our-multiple-value-prog1 instead of multiple-value-prog1 in the
; #+cltl2 case below, which would avoid the need for a separate #-cltl2 case.
; However, for non-ANSI GCL we want to take advantage of the fact that all
; functions in the rewrite nest return a first argument (the new step-limit)
; that is a fixnum, but the compiler doesn't use that information when a prog1
; call is used.  So we manage the non-ANSI case (including non-ANSI GCL)
; ourselves.

                #+cltl2
                (multiple-value-prog1
                 ,call
                 (setq *deep-gstack* gstack))
                #-cltl2
                ,(let ((var (gensym)))
                   `(let ((,var ,call))
                      (declare (type #.*fixnum-type* ,var))
                      (setq *deep-gstack* gstack)
                      ,var)))
               (t ,call))
      call)))

(defconst *fake-rune-for-linear*

; This object, a fake rune, will be pushed as a 'lemma to indicate that the
; "linear arithmetic rule" was used.

  '(:FAKE-RUNE-FOR-LINEAR nil))

(defconst *fake-rune-for-linear-equalities*

; This fake rune indicates whether complementary linear inequalities in the
; clause have been used to generate an equality hypothesis; see ACL2 source
; function find-equational-poly.  Such use is evidenced by the phrase "equality
; generation from inequalities" found in proof output; see *fake-rune-alist*.
; By default, only 5 levels of such equality generation are allowed (see the
; table event introducing equational-polyp-limit-table), when proof goals are
; viewed as a tree where the root is either the original goal or a clause
; generated by induction -- each proof by induction starts a new such tree.

  '(:FAKE-RUNE-FOR-LINEAR-EQUALITIES nil))

; We now develop the code used in path maintenance and monitor.

; The goal stack is a list of frames, each of the form

(defrec gframe (sys-fn bkptr . args) t)

; where sys-fn is a system function name, e.g., REWRITE, bkptr is an
; arbitrary object supplied by the caller to the sys-fn that indicates
; why the call was made (and must be interpreted by the caller, not
; the called sys-fn), and args are some subset of the args to sys-fn.

; WARNING: We use bkptr as a "hash index" uniquely identifying a hypothesis
; among the hypotheses of a rewrite rule when we are memoizing relieve-hyp.
; Thus, bkptr is a positive integer inside the functions relieve-hyps1 and
; relieve-hyp and their peers.

; Note: Nqthm included a count in each frame which was the number of
; frames generated so far and could be used to determine the
; "persistence" of each frame.  I am skipping that for the present
; because it means linearizing the code to pass the incremented count
; across args, etc., unless it is done in an extra-logical style.  A
; better idea would be to connect the goal stack to the comment window
; and actually display it so that persistence became visual again.

#-acl2-loop-only
(defparameter *deep-gstack* nil)

(defmacro push-gframe (sys-fn bkptr &rest args)

; This macro allows us to write
; (let ((gstack (push-gframe 'rewrite bkptr term alist obj ...)))
;   ...)
; without actually doing any conses if we are not maintaining the goal stack.
; Notice that it conses the new frame onto the value of the variable gstack, so
; to use this macro that variable must be the gstack.

; Observe the use of list* below.  Thus, the :args component of the frame built
; is a DOTTED list of the args provided, i.e., the last arg is in the final
; cdr, not the final cadr.  Thus, (push-gframe 'rewrite 3 'a ... 'z) builds a
; frame with :args '(a ... . z).  Note in particular the effect when only one
; arg is provided: (push-gframe 'rewrite 3 'a) builds a frame with :args 'a.
; One might wish in this case that the field name were :arg.

  #+acl2-loop-only
  `(cond ((or (f-get-global 'gstackp state)
              (f-get-global 'dmrp state))
          (cons (make gframe
                      :sys-fn ,sys-fn
                      :bkptr ,bkptr
                      :args (list* ,@args))
                gstack))
         (t nil))
  #-acl2-loop-only
  `(progn (when (or (f-get-global 'gstackp state)
                    (f-get-global 'dmrp state))
            (setq *deep-gstack*
                  (cons (make gframe
                              :sys-fn ,sys-fn
                              :bkptr ,bkptr
                              :args (list* ,@args))
                        gstack))
            (when (f-get-global 'dmrp state)
              (dmr-display))
            *deep-gstack*)))

(defmacro initial-gstack (sys-fn bkptr &rest args)

; This macro is just (push-gframe sys-fn bkptr ,@args) except it is done on an
; empty gstack.  Thus, it builds an initial gstack with the top-most frame as
; specified.  The frame is built by push-gframe, so all frames are built by
; that macro.

; This is also a convenient place to reset *add-polys-counter*, which is used
; by dmr-string.

  `(let ((gstack nil))
     #-acl2-loop-only (setq *add-polys-counter* 0)
     (push-gframe ,sys-fn ,bkptr ,@args)))

(defun tilde-@-bkptr-phrase (calling-sys-fn called-sys-fn bkptr)

; Warning: Keep this in sync with tilde-@-bkptr-string.

; This function builds a ~@ phrase explaining how two adjacent frames
; are related, given the calling sys-fn, the called sys-fn and the
; bkptr supplied by the caller.  See cw-gframe for the use of this
; phrase.

  (case called-sys-fn
    (rewrite
     (cond ((integerp bkptr)
            (cond ((member-eq calling-sys-fn
                              '(rewrite-with-lemma
                                rewrite-quoted-constant-with-lemma
                                add-linear-lemma))
                   (msg " the atom of the ~n0 hypothesis" (list bkptr)))
                  ((eq calling-sys-fn 'simplify-clause)
                   (msg " the atom of the ~n0 literal" (list bkptr)))
                  (t (msg " the ~n0 argument" (list bkptr)))))
           ((consp bkptr)
            (msg " the rhs of the ~n0 hypothesis"
                 (list (cdr bkptr))))
           ((symbolp bkptr)
            (case bkptr
              (body " the body")
              (lambda-body " the lambda body")
              (lambda-object-body " the body of the lambda object")
              (rewritten-body " the rewritten body")
              (expansion " the expansion")
              (equal-consp-hack-car " the equality of the cars")
              (equal-consp-hack-cdr " the equality of the cdrs")
              (rhs " the rhs of the conclusion")
              (meta " the result of the metafunction")
              (nth-update " the result of the nth/update rewriter")
              (multiply-alists2 " the product of two polys")
              (forced-assumption " a forced assumption")
              (proof-builder " proof-builder top level")
              (otherwise (er hard 'tilde-@-bkptr-phrase
                             "When ~x0 calls ~x1 we get an unrecognized ~
                                      bkptr, ~x2."
                             calling-sys-fn called-sys-fn bkptr))))
           (t (er hard 'tilde-@-bkptr-phrase
                  "When ~x0 calls ~x1 we get an unrecognized bkptr, ~x2."
                  calling-sys-fn called-sys-fn bkptr))))
    ((rewrite-with-lemma setup-simplify-clause-pot-lst simplify-clause
                         add-terms-and-lemmas add-linear-lemma
                         non-linear-arithmetic synp)
     "")
    (t (er hard 'tilde-@-bkptr-phrase
           "When ~x0 calls ~x1 we get an unrecognized bkptr, ~x2."
           calling-sys-fn called-sys-fn bkptr))))

(defmacro get-rule-field (x field)

; X is a rewrite-rule or linear-lemma record.  If the field is inappropriate
; but the field is one as expected by the guard, then we return the special
; value :get-rule-field-none.  Caveat: If x is a rewrite-rule of subclass
; rewrite-quoted-constant of form [2], we switch the interpretation of :lhs and
; :rhs!

  (declare (xargs :guard (let ((fields '(:rune :hyps :lhs :rhs :max-term)))
                           (and (not (member-eq x fields))
                                (member-eq field fields)))))
  `(let ((x ,x))
     (cond ((eq (record-type x) 'rewrite-rule)
            ,(cond ((member-eq field '(:lhs :rhs))
                    `(cond ((and (eq (access rewrite-rule x :subclass)
                                     'rewrite-quoted-constant)
                                 (eql (car (access rewrite-rule x
                                                   :heuristic-info))
                                      2))
                            (access rewrite-rule x
                                    ,(if (eq field :lhs) :rhs :lhs)))
                           (t (access rewrite-rule x ,field))))
                   ((eq field ':max-term) :get-rule-field-none)
                   (t `(access rewrite-rule x ,field))))
           ((eq (record-type x) 'linear-lemma)
            ,(cond ((member-eq field '(:lhs :rhs)) :get-rule-field-none)
                   (t `(access linear-lemma x ,field))))
           (t
            (er hard 'get-rule-field
                "The object ~x0 is neither a rewrite-rule record nor a ~
                 linear-lemma record."
                x)))))

(defun show-geneqv (x with-runes-p)
  (cond ((endp x) nil)
        (t (cons (cond
                  ((eq with-runes-p t)
                   (list (access congruence-rule (car x) :equiv)
                         (access congruence-rule (car x) :rune)))
                  ((eq with-runes-p 'non-prims)
                   (cond
                    ((or (eq (car (access congruence-rule (car x) :rune))
                             :FAKE-RUNE-FOR-ANONYMOUS-ENABLED-RULE)
                         (equal (access congruence-rule (car x) :rune)
                                '(:EQUIVALENCE IFF-IS-AN-EQUIVALENCE)))
                     (access congruence-rule (car x) :equiv))
                    ((eq (car (access congruence-rule (car x) :rune))
                         :congruence)
                     (list (access congruence-rule (car x) :equiv)
                           (cadr (access congruence-rule (car x) :rune))))
                    (t
                     (list (access congruence-rule (car x) :equiv)
                           (access congruence-rule (car x) :rune)))))
                  (t (access congruence-rule (car x) :equiv)))
                 (show-geneqv (cdr x) with-runes-p)))))

(defun cw-gframe (i calling-sys-fn frame evisc-tuple)

; Warning: Keep this in sync with dmr-interp.

; This prints a gframe, frame, which is known to be frame number i and
; was called by calling-sys-fn.

  (case (access gframe frame :sys-fn)
        (simplify-clause

; We are tempted to ignore evisc-tuple in this case and print the whole clause.
; We have seen situations where we print ellipses after the 4th literal of the
; clause and then say that the next frame is simplifying the "fifth literal."
; On the other hand, we have seen huge clauses bring cw-gframe to its knees.
; So we compromise by using the evisc-tuple supplied.

         (cw "~x0. Simplifying the clause~%     ~Y12"
             i
             (access gframe frame :args)
             evisc-tuple))
        (setup-simplify-clause-pot-lst
         (cw "~x0. Setting up the linear pot list for the clause~%     ~Y12"
             i
             (access gframe frame :args)
             evisc-tuple))
        (rewrite
         (let ((term (car (access gframe frame :args)))
               (alist (cadr (access gframe frame :args)))
               (obj (caddr (access gframe frame :args)))
               (geneqv (cdddr (access gframe frame :args))))
           (cw "~x0. Rewriting (to ~@6)~@1,~%     ~Y23,~#4~[~/   under the ~
                substitution~%~*5~]~#7~[~/~|   Geneqv: ~y8~]"
               i
               (tilde-@-bkptr-phrase calling-sys-fn
                                     'rewrite
                                     (access gframe frame :bkptr))
               term
               evisc-tuple
               (if alist 1 0)
               (tilde-*-alist-phrase alist evisc-tuple 5)
               (cond ((eq obj nil) "falsify")
                     ((eq obj t) "establish")
                     (t "simplify"))
               (if geneqv 1 0)
               (show-geneqv geneqv 'non-prims))))
        ((rewrite-with-lemma
          rewrite-quoted-constant-with-lemma)
         (let ((term (car (access gframe frame :args)))
               (lemma (cadr (access gframe frame :args)))
               (geneqv (cddr (access gframe frame :args))))
           (cw "~x0. Attempting to apply ~F1 to~%     ~Y23~|~#4~[~/   Preserving: ~x5~]~|~#6~[~/   Geneqv: ~y7~]"
               i
               (get-rule-field lemma :rune)
               term
               evisc-tuple
               (if (eq (access rewrite-rule lemma :equiv) 'equal)
                   0
                   1)
               (access rewrite-rule lemma :equiv)
               (if geneqv
                   1
                   0)
               (show-geneqv geneqv 'non-prims))))
        (add-linear-lemma
         (let ((term (car (access gframe frame :args)))
               (lemma (cdr (access gframe frame :args))))
           (cw "~x0. Attempting to apply ~F1 to~%     ~Y23"
               i
               (get-rule-field lemma :rune)
               term
               evisc-tuple)))
        (add-terms-and-lemmas
         (cw "~x0. Attempting to apply linear arithmetic to ~@1~%     ~Y23"
             i
             (let ((obj (cdr (access gframe frame :args))))
               (cond ((eq obj nil) (msg "falsify the term list"))
                     ((eq obj t) "establish the term list")
                     (t ; '?, a special mark for setting up the pot-lst
                      "the clause")))
             (car (access gframe frame :args))
             evisc-tuple))
        (non-linear-arithmetic
         (cw "~x0. Attempting to apply non-linear arithmetic to the list of ~
              ~x1 var~#2~[~/s~]:~%     ~Y23"
             i
             (length (access gframe frame :args))
             (access gframe frame :args)
             evisc-tuple))
        (synp
         (let ((synp-fn (access gframe frame :args)))
           (cw "~x0. Entering ~x1 for hypothesis ~x2~%"
               i synp-fn (access gframe frame :bkptr))))
        (otherwise (er hard 'cw-gframe
                       "Unrecognized sys-fn, ~x0"
                       (access gframe frame :sys-fn)))))

(defun cw-gstack1 (i calling-sys-fn lst evisc-tuple)
  (cond ((null lst) nil)
        (t (prog2$ (cw-gframe i calling-sys-fn (car lst) evisc-tuple)
                   (cw-gstack1 (1+ i)
                               (access gframe (car lst) :sys-fn)
                               (cdr lst) evisc-tuple)))))

(defun cw-gstack-fn (evisc-tuple frames)

; And here is how we print the whole goal stack to the comment window.

; Note: I am unhappy about the use of the comment window here.  It pre-dates
; the invention of wormhole and its undoable changes to state.  I sometimes
; think I should make this function just print the stack to an arbitrary
; channel and in wormhole that can be *standard-co*.  But I have bigger fish to
; fry right now, namely the use of wormhole to implement an apparently (but not
; actually) recursive break-lemma.  So I'm leaving this little wart to think
; about later.

; Since this function is a hack anyhow, we implicitly refer to *deep-gstack*
; without passing it in.

  (let ((gstack #-acl2-loop-only *deep-gstack*
                #+acl2-loop-only nil)
        (ctx 'cw-gstack))
    (cond
     ((null gstack)
      (cw "There is no gstack to print.  If you have enabled stack monitoring ~
           with ``:BRR t'' this is likely due to the loop you wish to ~
           investigate occurring in so-called preprocessing, where monitoring ~
           is not done, rather than in the rewriter proper.  You may obtain ~
           better results by replaying the problematic event with a hint ~
           of:~%((\"Goal\" :DO-NOT '(preprocess)).~%See :DOC hints, in ~
           particular the discussion of :DO-NOT.~%"))
     ((and evisc-tuple
           (not (standard-evisc-tuplep evisc-tuple)))
      (er hard ctx
          "Illegal :evisc-tuple argument to ~x0: ~x1.  See :DOC cw-gstack."
          'cw-gstack evisc-tuple))
     ((not (or (null frames)
               (and (integerp frames) (< 0 frames))
               (and (true-listp frames)
                    (eql (length frames) 2)
                    (natp (car frames))
                    (natp (cadr frames))
                    (<= (car frames) (cadr frames)))))
      (er hard ctx
          "Illegal :frames argument to ~x0: ~x1.  See :DOC cw-gstack."
          'cw-gstack frames))
     (t
      (let ((start (cond ((or (null frames)
                              (integerp frames))
                          1)
                         ((<= (car frames) (length gstack))
                          (car frames))
                         (t (length gstack)))))
        (cw-gstack1 start nil
                    (cond ((null frames)
                           (reverse gstack))
                          (t
                           (let* ((rev-gstack (reverse gstack))
                                  (len (length gstack))
                                  (n (min (if (integerp frames)
                                              frames
                                            (cadr frames))
                                          len)))
                             (nthcdr (1- start) (take n rev-gstack)))))
                    evisc-tuple))))))

(defmacro cw-gstack (&key (evisc-tuple 'nil evisc-tuplep) (frames 'nil))
  (declare (xargs :guard t))
  `(cw-gstack-fn ,(if evisc-tuplep
                      evisc-tuple
                    '(term-evisc-tuple t state))
                 ,frames))

; Essay on Break-Rewrite
; Essay on BRR

; The ``interactive rewriter,'' break-rewrite or brr, is an illusion created by
; the use of a wormhole to maintain a state machine and to interact with the
; user without influencing the ultimate behavior of the rewriter.  We implement
; it this way, rather than directly in rewrite, to make it obvious that
; interacting with break-rewrite will not change the behavior of rewrite.

; This essay describes the implementation of brr.  However, before reading this
; essay we recommend that you familiarize yourself how to use brr by reading
; :doc break-rewrite and :doc monitor.

; Since break-rewrite is implemented via a wormhole, to add or correct the
; functionality of break-rewrite you have to be a ``wormhole programmer.''
; Please read :doc wormhole-programming-tips.  In addition, you should be
; familiar with the user's view of break-rewrite.  To that end, read :doc
; break-rewrite and its subtopics including :doc brr-commands and :doc monitor.

; To help you explore break-rewrite for yourself we have provided a sample
; script, at the end of this essay, together with a line-by-line commentary on
; what is going on.  The sample script can also be found as Scenario 1 in
; books/demos/brr-test-input.lsp.  The file books/demos/brr-test-log.txt
; contains the output produced by running that script.  But we suggest not
; playing with the sample script until you've read through the material below.

; The break-rewrite wormhole is named brr.  The status of the wormhole is
; maintained as a defrec named brr-status.  The fields of that record are
; described below and we then give an example that actually comes from the
; sample script.

; entry-code -- :skip or :enter as normal for wormholes

; brr-monitored-runes -- list of monitored runes and their break criteria

; brr-gstack: a representation of the rewriter's call stack leading to the
;    current application of the monitored rune that caused the current break.
;    When you execute the brr-command :path (e.g., command [2] in the script)
;    in a brr interactive break you are seeing a display of the gstack as
;    printed by cw-gstack.  By the way, it should be the case that when in raw
;    Lisp under a brr break, the value of the :brr-gstack component of the
;    brr-status is equal to the value of the raw Lisp special var
;    *deep-gstack*.

; brr-local-alist -- an alist binding variables that rewrite passed to the brr
;    wormhole.  These variables are all related to the current break, e.g.,
;    the LEMMA being applied, the TARGET, etc.

; brr-previous-status -- the brr-status from the previous (immediately
;    superior) call of (the fictitious) break-rewrite.  Thus, you can think of
;    a brr-status record as a stack of frames, each frame containing
;    :brr-monitored-runes, :brr-gstack, and :brr-local-alist.

; See the (defrec brr-status ...) event below for the actual layout of the
; record.

; Here is an example brr-status object.  Actually, this is not the object
; itself but a term that constructs a brr-status record.  The record itself is
; hard to read and is, in fact, often huge because of the values of the RCNST
; bindings in the :BRR-LOCAL-ALISTs.  The text below was printed by the
; (print-brr-status t) command at line [ 3] of the sample brr script.  That
; function substitutes the symbol |some-rewrite-constant| for each RCNST
; binding in the brr-status stack.  In addition, it substitutes |some-nume| for
; the :nume field of each rewrite-rule and linear-lemma.  The latter
; substitution is done so that we can use print-brr-status in run-script books
; (like books/demo/brr-test-book.lisp) which record in a -log.txt file the
; correct output.  But numes change from one build of ACL2 to another if the
; number of ACL2 system functions or lemmas are changed.  If you want to
; actually see the RCNST bindings and NUME values, use (print-brr-status nil).

; (MAKE BRR-STATUS
;       :ENTRY-CODE ':ENTER
;       :BRR-MONITORED-RUNES '(((:REWRITE A) (:CONDITION QUOTE T)))
;       :BRR-GSTACK '((REWRITE-WITH-LEMMA NIL (AFN X)
;                                         REWRITE-RULE (:REWRITE A)
;                                         |some-nume| ((BFN X))
;                                         IFF (AFN X)
;                                         'T
;                                         BACKCHAIN NIL NIL T)
;                     (REWRITE 2 (AFN X) NIL . ?)
;                     (SIMPLIFY-CLAUSE NIL (NOT (EFN X))
;                                      (AFN X)))
;       :BRR-LOCAL-ALIST '((LEMMA REWRITE-RULE (:REWRITE A)
;                                 |some-nume| ((BFN X))
;                                 IFF (AFN X)
;                                 'T
;                                 BACKCHAIN NIL NIL T)
;                          (TARGET AFN X)
;                          (UNIFY-SUBST (X . X))
;                          (TYPE-ALIST ((EFN X) -129))
;                          (POT-LIST)
;                          (ANCESTORS)
;                          (RCNST . |some-rewrite-constant|)
;                          (INITIAL-TTREE))
;       :BRR-PREVIOUS-STATUS
;       (MAKE BRR-STATUS
;             :ENTRY-CODE ':ENTER
;             :BRR-MONITORED-RUNES '(((:REWRITE A) (:CONDITION QUOTE T)))
;             :BRR-GSTACK 'NIL
;             :BRR-LOCAL-ALIST 'NIL
;             :BRR-PREVIOUS-STATUS NIL))

; This ``stack'' has two ``frames,'' the top-most frame being the frame in
; which the rewriter is about to try to apply the :rewrite rule A to the target
; (AFN X), and the deeper one being the status of brr at the top-level of ACL2.

; Break-rewrite is implemented by sprinkling calls of three ``break point
; handlers'' into the rewrite clique.  (As of this writing -- May, 2023 --
; there are 30 such calls in the clique.)  In each call, rewrite passes input
; into the brr wormhole and that wormhole interprets the input and the current
; status and decides whether to enter a read-eval-print loop.

; The three break point handlers are functions named near-miss-brkpt1, brkpt1,
; and brkpt2.  All three use a macro named brr-wormhole which is just a call of
; wormhole, except that brr-wormhole puts a certain wrapper around the
; wormhole's ``first form.''  Before wormhole evaluates that elaborated first
; form, it sets the state global variables WORMHOLE-INPUT and WORMHOLE-STATUS.
; All calls of the break-point handlers supply the rewriter's current gstack
; and relevant variable bindings, to be assigned to wormhole-input by wormhole.
; Wormhole also sets state global 'wormhole-status to the brr persistent-whs.

; (Quick review of wormhole terminology from the Essay on Wormholes: the
; ``persistent-whs'' of a wormhole named name is the last remembered wormhole
; status of name and is kept in that part of raw Lisp's memory best thought of
; as outside the reach of normal ACL2 terms.  The raw Lisp variable
; *wormhole-status-alist* holds the persistent-whs of every known wormhole but
; is only accessible in raw Lisp.  To get the persistent-whs of a wormhole from
; inside ACL2 (as opposed to raw Lisp) involves reading the ACL2 oracle.  When
; inside the name wormhole, its status is stored in the state global variable
; 'wormhole-status.  That copy of the status is called the ``ephemeral-whs''
; because it disappears when the wormhole is exited.  :Doc
; wormhole-programming-tips discusses several issues related to these two
; concepts, namely ``wormhole coherence,'' whether to care about it, and how to
; maintain it.  The brr wormhole is always coherent: the persistent-whs and
; ephemeral-whs are equal whenever you look.)

; The wrapper supplied by brr-wormhole sets the prompt to be the brr prompt and
; gives special meaning to the value component of the error triple returned by
; the first form.  If the first form returns (value t) the interactive loop is
; started and if the first form returns (value nil) the wormhole is silently
; exited.  (Note that brr-wormhole, like wormhole, also has an entry-lambda and
; so it is possible for the entry lambda to say :enter and then the first form
; to exit silently.)

; The near-miss-brkpt1 and brkpt1 are similar in that if they :ENTER they look
; at the wormhole-input (containing a gstack and an alist of rewrite variables)
; and the wormhole-status (the old brr-status) and ``push'' a new frame onto
; the old one.  See push-brr-status.

; The third handler, brkpt2, prints information, possibly interacts with the
; user, and then pops the status stack, setting it to the :brr-previous-status.
; See pop-brr-status.

; Every near-miss-brkpt1 call in the rewrite clique is balanced by a brkpt2
; call.  Similarly, every brkpt1 call is balanced by brkpt2 call.  (Weird
; clarification: There are 3 calls of near-miss-brkpt1, 4 calls of brkpt1, and
; 23 calls of brkpt2.  So we mean ``balanced'' in the dynamic sense.  Typically
; after a call of brkpt1, the rewrite code case splits as it tries to apply the
; lemma and on each exit from that case split there will be a call of brkpt2
; reporting the results.  Only one of those many brkpt2 calls is executed.)
; Near-miss-brkpt1 and brkpt1 print a banner indicating a new ``call'' into the
; fictitious break-rewrite and brkpt2 prints a final message indicating a
; ``return'' from break-rewrite.  The first two interpret keyword commands as
; per *brkpt1-aliases* and the last interprets them as per *brkpt2-aliases*.

; Near-miss-brkpt1 is called every time the rewriter attempts to unify a rule's
; pattern with the rewriter's target but unification fails.  (By a rule's
; ``pattern'' we mean, for example, the left-hand side of a :rewrite rule.)
; The entry-lambda in near-miss-brkpt1 determines whether the rule's pattern is
; a near miss to the target according to the break criteria, if any, associated
; with the rule's rune in :brr-monitored-runes.  If so, we :ENTER the wormhole.
; The first form of the wormhole assembles and pushes the new status onto the
; old status (via push-brr-status), prints an ``entry to break-rewrite'' banner
; with a near-miss message, and returns (value t), which means additional
; interactive input from the user is read.  What happens after that is
; the same as in brkpt1, so just read on.

; Brkpt1 is called every time a rule's pattern successfully unifies.  The
; entry-lambda just checks whether the rule's rune has an entry on
; :brr-monitored-runes and if so :ENTERs.  The first form assembles and pushes
; the new status (via push-brr-status) and then evals the rune's :condition
; expression to see if it is satisfied.  If so, it prints the break-rewrite
; entry banner and returns (value t), soliciting further input from the user.
; If not, it pops the status (via pop-brr-status) and returns (value nil),
; silently exiting the wormhole.

; So now let's suppose we're in either near-miss-brkpt1 or brkpt1 and reading
; input from the user.  Keyword commands are interpreted as specified by
; *brkpt1-aliases*.  See :doc brr-commands.  Most commands just display
; information like the :target being rewritten, the :path rewrite took to reach
; this target, etc.  Typically the user will inspect the current state of the
; rewriter with these commands.  But ultimately the user will either want to
; abort the proof attempt because he or she finally understands what's going
; wrong, or will want to allow the rewriter to proceed to try to use the rule.
; Proceeding here means to try to relieve the rule's hypotheses, rewrite the
; right-hand side, etc.  To abort the user types the command :a!.  To proceed
; the user types one several commands (:ok, :go, :eval, or their variants)
; depending on the user's interest in seeing the
; results of the current attempt to apply the rule.  See :doc brr-commands.

; If the user aborts, the cleanup form in wormhole1 will set the brr
; persistent-whs back to the status brr had at the top-level.  In particular,
; it pops the brr-status stack all the way back to the first frame and saves
; that frame to persistent-whs.  This behavior by the cleanup form is unique to
; the brr wormhole.  Aborts from other wormholes just save the current
; ephemeral-whs to persistent-whs.

; If, on the other hand, the user proceeds from near-miss-brkpt1 or brkpt1,
; e.g., with :ok, :go, or :eval, this is what happens: First, we adjust the
; current status by adding two new bindings to the :brr-local-alist.  These
; bindings are intended to tell the eventual brkpt2 handler how to behave when
; it is called on the current brr-status.  The first new binding saves the
; current value of standard-oi so that if the user changes it in an inferior
; break it can be restored when returning to this brr-status.  The second new
; binding adds a value for the symbol ACTION.  The possible values are SILENT
; (if we exited with some form of :ok), PRINT (some form of :go), or BREAK
; (some form of :eval).  The ACTION binding tells brkpt2 what to do when we get
; back to this brr-status.  Then proceed-from-brkpt1 returns (value :q) which
; exits the ld and wormhole.  The cleanup form (in the non-abort situation)
; saves the brr ephemeral-whs to persistent-whs and then undoes all state
; changes that occurred in the wormhole.  Finally, near-miss-brkpt1 or brkpt1,
; appropriately, is exited.

; The rewriter continues to do whatever it was doing.  But eventually (in the
; absence of interrupts and aborts) it reaches the balancing call of brkpt2.

; Of course, in between the exit from the first handler and the entry to the
; second, many more entries and exits of the handlers are encountered but they
; don't do anything if the relevant runes are not being monitored.  So the
; question arises: which calls of brkpt2 match ``open'' calls of brkpt1 (or
; near-miss-brkpt1) and which don't?  That is one reason why :brr-gstack is a
; component of brr-status.  When brkpt2 is called and the current rewrite
; gstack is equal to the :brr-gstack in the current brr-status, it means this
; call of brkpt2 should be :ENTERed and act like it is continuing the earlier
; brkpt1 call.  (We are being sloppy: we should say ``brkpt1 or
; near-miss-brkpt1 call.''  Brkpt2 handles them the same way and so we persist
; now in being sloppy and just talking as though brkpt1 built the status brkpt2
; is seeing.)

; Once inside the resulting brkpt2, the first form augments the bindings in the
; :BRR-LOCAL-ALIST with the alist bindings passed by wormhole from rewrite into
; from wormhole-input.  Those new bindings include whether the rule was
; successfully applied or not (the value of the binding of WONP) and what the
; results were or why it failed.  The first form then inspects the binding of
; ACTION.  If ACTION is bound to SILENT, then the earlier brkpt1 exited with a
; version of :ok and brkpt2 just exits, popping the stack with pop-brr-stack.
; If ACTION is bound to PRINT (i.e., a :go exit), brkpt2 explains what rewrite
; did and then pops the stack and exits.  If ACTION is bound to BREAK (i.e., an
; :eval exit), brkpt2 solicits input from the user.  Keyword commands are
; interpreted as by *brkpt2-aliases* where all the exit commands pop the stack
; and exit (see exit-brr).

; (By the way, if you're looking at a brr-status and there is a binding for
; WONP it means you're in brkpt2.  If you're in brkpt2 and the binding of of
; FAILURE-REASON is NEAR-MISS then this brkpt2 closes a near-miss-brkpt1 and
; otherwise it closes a brkpt1.)

; Changing break-rewrite can require editing several different ACL2 source files.
; Some possibly unexpected places you should definitely look at are:

; * the clean-up code in the #-acl2-loop-only code in wormhole1 treats the brr
;   wormhole differently than all other wormholes

; * from the name brr-evisc-tuple you might think it is a component of the
;   brr-status, but it is not.  It is a state global variable that is mirrored
;   by the raw Lisp special *wormhole-brr-evisc-tuple* and magically set by
;   brr-evisc-tuple-oracle-update which is called in some possibly unexpected
;   places, including ld-read-command and waterfall-step.

; -----------------------------------------------------------------
; A Sample Script to Exercise Break-Rewrite

; So below is the sample script that shows how you might explore break-rewrite.
; See also books/demos/brr-test-input.lsp which is a ``run-script'' book that
; replays several sessions with break-rewrite.  The log file from those sessions
; is books/demos/brr-test-log.txt.

; But we recommend, first, that you replay the following script in a fresh ACL2
; session so you see the interaction ``live.''  First do this setup, which
; introduces some rules, defines a function to check whether the brr wormhole
; is coherent (persistent-whs and ephemeral-whs are equal), and then enables
; brr and installs a monitor on rule a.  By the way, the coherence checker
; below is unnecessary but we want to show you how to get your hands on the
; persistent-whs and ephemeral-whs when you're in the brr wormhole.  Note that
; the persistent-whs is ``read'' via the ACL2 oracle.

; (encapsulate ((afn (x) t)
;               (bfn (x) t)
;               (cfn (x) t)
;               (dfn (x) t)
;               (efn (x) t))
;   (local (defun afn (x) (declare (ignore x)) t))
;   (local (defun bfn (x) (declare (ignore x)) t))
;   (local (defun cfn (x) (declare (ignore x)) t))
;   (local (defun dfn (x) (declare (ignore x)) t))
;   (local (defun efn (x) (declare (ignore x)) t))
;   (defthm a (implies (bfn x)(afn x)))
;   (defthm b (implies (cfn x)(bfn x)))
;   (defthm c (implies (dfn x)(cfn x)))
;   (defthm d (implies (efn x)(dfn x)))
;   )
; (defun brr-coherentp (state)
;   (declare (xargs :mode :program :stobjs (state)))
;   (if (eq (f-get-global 'wormhole-name state) 'brr)
;       (er-let*
;           ((persistent-whs (get-persistent-whs 'brr state))
;            (ephemeral-whs (value (f-get-global 'wormhole-status state))))
;         (value (equal persistent-whs ephemeral-whs)))
;       (value t)))
; (brr t)
; (monitor 'a t)

; Now execute each line below and make sure preserve the commented line
; numbers.  Our description of what happens refers to these commands by the
; line number and you will want to look at your output and compare it to our
; descriptions.

; (thm (implies (efn x) (afn x))) ; [ 0]
; :target                         ; [ 1]
; :path                           ; [ 2]
; (print-brr-status t)            ; [ 3]
; (brr-coherentp state)           ; [ 4]
; (monitor 'b t)                  ; [ 5]
; (print-brr-status t)            ; [ 6]
; (monitored-runes)               ; [ 7]
; :eval                           ; [ 8]
; (print-brr-status t)            ; [ 9]
; :ok                             ; [10]
; (print-brr-status t)            ; [11]
; :ok                             ; [12]
; (print-brr-status t)            ; [13]

; Trying the read the script above and the descriptions below WITHOUT the
; interactive output is quite confusing.  Don't do it.  Replay the script and
; look at the output as you read the following!  Alternatively, look at
; books/demos/brr-test-log.txt (but the line number comments are missing).  (We
; don't want to dump the output into this comment because it just too long!)

; When we executed the thm command at [ 0] the rewriter eventually tried to
; apply the rule A to (AFN X) and caused a break because rule A is monitored.
; So we enter a break.  The prompt printed looks like this:

; (1 Breaking (:REWRITE A) on (AFN X):

; telling us we're at depth 1 in break-rewrite.

; The commands at [ 1] and [ 2] print the target and the path the rewriter took
; to get here.

; The command at [ 3] is the term (print-brr-status t), which is of no interest
; to the user but is an invaluable asset to the developer.  It prints the
; current brr status.  It doesn't actually print the status object itself but
; ``prettyifies'' it into a make brr-status term so it is easier to read.  The
; t argument means ``hide the values of RCNST in the :brr-local-alist.'' We
; advise always using the t argument.  An argument of NIL prints the actual
; RCNST value.  RCNST is a rewrite-constant record that typically includes
; several very large objects including the current enabled structure.  Note
; also that print-brr-status does not return the object or the prettyified
; version.  It just prints it because it has to fetch it from a wormhole and
; works whether you're in a break or not (see the [13] where we call it at the
; top-level).

; Compare the output of the :path command at [ 2] to the :BRR-GSTACK component
; of the status printed by [ 3].

; Also note the value of :BRR-LOCAL-ALIST printed by [ 3].  It's an alist that
; binds variables the rewriter passed into the wormhole via the wormhole-input
; state global.  For example, LEMMA is bound to the actual rewrite-rule object
; that caused the break, TARGET is bound to the target being rewritten (printed
; by the :target command at [ 1], etc.  Note that RCNST's value has been
; skipped in this print out.

; Finally, notice the :BRR-PREVIOUS-STATUS component of [ 3].  It is the
; top-level status, where only (:REWRITE A) is monitored and the other
; components are empty.  As you can see, the brr-status is actually a stack and
; the deepest status in the stack is the one from the top-level of ACL2 when
; this proof started.

; The command at [ 4] checks whether the brr wormhole is coherent.  It is.
; Coherence is discussed in :doc wormhole-programming-tips and the function
; brr-coherentp is not a defined system function but is defined in the sample
; script.  You might study the definition there.  The brr wormhole is always
; coherent.

; At command [ 5] we install a monitor on the rewrite rule B.  It prints the new
; list of monitored runes.  Comparing the print-brr-status at [ 3] to that at
; [ 6] reveals that the only change is the value of :BRR-MONITORED-RUNES.

; The (monitored-runes) command at [ 7] just prints that component of the
; status.

; At command [ 8] we :eval the rule A.

; What happens at this point is that the rewriter proceeds to try to apply the
; rule A to the target.  The rewriter does its thing and eventually tries to
; apply rule B to target (BFN X).  Since we've installed a monitor on rule B,
; that provokes a new break at depth 2.

; (2 Breaking (:REWRITE B) on (BFN X):

; Intuitively, the new break just pushes a new status on top of the old status
; stack.  You can see this by comparing the status printed at [ 6] with the
; status printed at [ 9].  Count the MAKEs.  There were two (meaning we were at
; depth 1) and now there are three (meaning we are at depth 2).

; The top-most status is different: it contains the same :BRR-MONITORED-RUNES
; (although that would change if we monitored or unmonitored runes at this
; depth), but the :BRR-GSTACK is now deeper, showing that we're rewriting (BFN
; X) and trying to apply rule (:REWRITE B).  The :BRR-LOCAL-ALIST has the local
; variables for this application of rewrite, and the :BRR-PREVIOUS-STATUS is --
; ALMOST -- exactly the status shown by [ 6].  We say ``almost'' because note
; that the :BRR-LOCAL-ALIST of the :BRR-PREVIOUS-STATUS differs from that in [
; 6] by the addition of new bindings for SAVED-STANDARD-IO and ACTION.

; Those values were stored when the :eval at [ 8] was executed.  When,
; eventually, we pop back to that earlier status, break-rewrite will restore
; STANDARD-IO to the saved value -- it might be changed in an inferior break --
; and the ACTION tells break-rewrite that when we get back here we are to
; interact with the user again.  Had we proceeded at [ 8] with, say, :ok
; instead of :eval, we would have stored a different ACTION.  In short, when we
; proceed from a break to try the rule, break-rewrite saves information so that
; when it gets back here it knows what to do.

; So now we're at break depth 2 and we issue the :ok command at [10].  That
; releases the break on B and allows the rewriter to continue.  It succeeds and
; we return to the break on A having rewritten the :target, (AFN X), to T.

; Intuitively we just pop the status stack.  But look at the top-most status at
; [11].  It is almost the status we saw just before we :eval'd at [ 8] except
; for the SAVED-STANDARD-IO and ACTION bindings noted above (stored by :eval)
; and bindings for WONP, FAILURE-REASON, BRR-RESULT, and FINAL-TTREE which are
; completely new.

; Those new bindings were put there when we popped the stack from depth 2 back
; to depth 1.  The break at depth 2 is passing information up to the break at
; depth 1.  So now the ACTION tells the us to enter an interactive loop again
; and the new variables tell us rule A successfully applied and rewrote the
; target to whatever BRR-RESULT is (i.e., T).

; At [12] we issue the :ok command which exits depth 1 by popping the stack.
; The proof completes with Q.E.D and the status printed at [13] is the
; top-level one, where only rule A is monitored.

; --- End of Essay on Break-Rewrite ---

; The brr-status must be a cheap record because entry-code must be the car!  If
; you wish to inspect a brr-status object, consider using the function
; prettyify-brr-status, which hides the typically large value of the RCNST
; binding in :brr-local-alist.

(defrec brr-status
  (entry-code (brr-monitored-runes . brr-gstack)
              . (brr-local-alist . brr-previous-status))
  t)

(defun make-initial-brr-status (monitored-runes)
  (make brr-status
        :entry-code :enter
        :brr-monitored-runes monitored-runes
        :brr-gstack nil
        :brr-local-alist nil
        :brr-previous-status nil))

(defun dive-to-deepest-brr-status (whs)
  (let ((prev-whs (access brr-status  whs :brr-previous-status)))
    (if (null prev-whs)
        whs
        (dive-to-deepest-brr-status prev-whs))))

(defun top-level-brr-status (whs)

; Given a brr-status, whs, we construct the corresponding top-level status.
; This function is used by wormhole1 when aborting from whs up to the
; top-level.  The top-level monitored runes are those originally found at the
; top-level when the first break-rewrite frame was entered (which is now the
; deepest brr-previous-status of whs).  All other fields are empty.  We expect
; that the deepest brr-previous-status is exactly same as the status we
; construct below, but we just want to be certain that the other fields are
; empty.

  (make-initial-brr-status
   (access brr-status (dive-to-deepest-brr-status whs) :brr-monitored-runes)))

(defun brr-depth1 (whs)
; Whs is a brr-status.  Notice that it is actually a stack of statuses chained
; through the brr-previous-status component.  We compute its depth.
  (let ((prev-whs (access brr-status whs :brr-previous-status)))
    (cond
     ((null prev-whs)
      0)
     (t (+ 1 (brr-depth1 prev-whs))))))

(defun brr-depth (state)
  (brr-depth1 (f-get-global 'wormhole-status state)))

(defmacro brr-wormhole (entry-lambda input-alist test-form aliases)

; A brr-wormhole is just a wormhole except we put a wrapper around the first
; form (here called the test-form) so that (value t) means enter the
; interactive loop and (value nil) means silently exit.  (By the way, if the
; test-form returns (value nil) it ought to pop-brr-status if it pushed one.)
; The wrapper also sets the ld-keyword-aliases and the ld-prompt appropriately.

  (let ((aliases `(append ,aliases
                          '((:exit
                             0 (lambda nil
                                 (prog2$ (cw "The keyword command :EXIT is ~
                                              disabled inside BRR.  Exit BRR ~
                                              with :ok or :go, or use :a! to ~
                                              abort; or exit ACL2 entirely ~
                                              with ~x0.~%"
                                             '(exit))
                                         (value :invisible))))
                            (:quit
                             0 (lambda nil
                                 (prog2$ (cw "The keyword command :QUIT is ~
                                              disabled inside BRR.  Quit BRR ~
                                              with :ok or :go, or use :a! to ~
                                              abort; or quit ACL2 entirely ~
                                              with ~x0.~%"
                                             '(quit))
                                         (value :invisible))))))))
    `(wormhole 'brr
               ,entry-lambda
               ,input-alist
               `(er-progn
                 (set-ld-keyword-aliases! ,,aliases)
                 (set-ld-prompt 'brr-prompt state)

; The above reference to the function symbol brr-prompt is a little startling
; because we haven't defined it yet.  But we will define it before we use this
; macro.

                 (mv-let (erp val state)
                   ,,test-form
                   (cond
                    (erp

; If an error is signaled by the test-form we've made a programming mistake.
; Check all callers of brr-wormhole!  Every test-form should either return
; (value t) or (value nil).  The form should always clean up the brr-status
; before returning (value nil) -- only the form knows whether it pushed a
; brr-status frame that should be popped or not.

                     (value
                      (er hard 'brr-wormhole
                          "The test-form provided to brr-wormhole has ~
                           signalled an error.  This is a programming error ~
                           by the ACL2 developers.  Please report this.")))
                    (val

; Entering the interactive loop.  All exits are as specified by the aliases, which
; use proceed-from-brkpt1 or exit-brr, cleaning up the brr-status.

                     (er-progn
                      (set-ld-error-action :continue state)
                      (with-output
                        :off :all
                        (disable-ubt
                         (msg "Note that ~x0 was executed when an interactive ~
                               break occurred due to a monitored rule; see ~
                               :DOC break-rewrite."
                              'disable-ubt)))

; We solicit user input now.  The aliases control all exits via
; proceed-from-brkpt1 or exit-brr, appropriately dealing with the brr-status.

                      (value :invisible)))
                    (t

; The test-form returned (value nil) and is assumed to have cleaned up the
; brr-status before doing so.

                       (value :q)))))
               :ld-prompt  nil
               :ld-missing-input-ok nil
               :ld-always-skip-top-level-locals nil
               :ld-pre-eval-filter :all
               :ld-pre-eval-print  nil
               :ld-post-eval-print :command-conventions
;              :ld-evisc-tuple nil ; the ld-evisc-tuple stays the same
               :ld-error-triples  t
               :ld-error-action :error
               :ld-query-control-alist nil
               :ld-verbose nil)))

; This completes the implementation of brr-wormholes, though we must remember
; to use them properly!  E.g., when the test form pushes a new status but
; returns (value nil) it should pop that status, and if it enters the loop it
; must exit via proceed-from-brkpt1 or exit-brr.

; We now move on to the implementation of brr-locals.

(defun get-brr-local (var state)

; We fetch the value of var in the :brr-local-alist of the brr ephemeral-whs.

; Warning: This function should only be used under break-rewrite (i.e., under
; one of the brkpt handlers).  It can't be used in the lambda expressions for
; wormhole-eval (since there may not be an ephemeral-whs there).  If you want
; the value of a local variable in wormhole-eval (where the lambda formal is
; named whs) use (cdr (assoc-eq var (access brr-status whs :brr-local-alist))).

  (let ((whs (f-get-global 'wormhole-status state)))
    (cdr (assoc-eq var (access brr-status whs :brr-local-alist)))))

(defun put-brr-local (var val state)

; Put val as the value of var in :brr-local-alist of the ephemeral-whs.

; Warning: This function should only be used under break-rewrite (i.e., under
; one of the brkpt handlers).

; Expects and ensures Wormhole Coherence.

  (if (eq (f-get-global 'wormhole-name state) 'brr)
      (let* ((whs (f-get-global 'wormhole-status state))
             (alist (access brr-status whs :brr-local-alist))
             (new-whs (change brr-status whs
                              :brr-local-alist
                              (put-assoc-eq var val alist))))
        (set-persistent-whs-and-ephemeral-whs 'brr new-whs state))
      (prog2$
       (illegal 'put-brr-local
                "It is illegal to call put-brr-local unless you are under ~
                 break-rewrite and you are not.  The arguments to ~
                 put-brr-local were ~x0 and ~x1"
                (list (cons #\0 var)
                      (cons #\1 val)))
       state)))

(defun put-brr-locals (alist state)

; We merge the bindings in alist with those in the :brr-local-alist of the
; ephemeral-whs.  This function may overwrite values of locals already bound in
; the :brr-local-alist.  New bindings appear at the end.

; Warning: This function should only be used under break-rewrite (i.e., under
; one of the brkpt handlers).

; Expects and ensures Wormhole Coherence.

  (if (eq (f-get-global 'wormhole-name state) 'brr)
      (let* ((whs (f-get-global 'wormhole-status state))
             (alist1 (access brr-status whs :brr-local-alist))
             (new-whs (change brr-status whs
                              :brr-local-alist
                              (put-assoc-eq-alist alist1 alist))))
        (set-persistent-whs-and-ephemeral-whs 'brr new-whs state))
      (prog2$
       (illegal 'put-brr-locals
                "It is illegal to call put-brr-locals unless you are under ~
                 break-rewrite and you are not.  The alist argument to ~
                 put-brr-locals was ~x0."
                (list (cons #\0 alist)))
       state)))

(defun push-brr-status (state)

; This function is called when either near-miss-brkpt1 or brkpt1 enters the
; wormhole.  At the time this function is called, we have just entered the brr
; wormhole but it is incompletely initialized.  The generic state globals
; wormhole-name, wormhole-input, and wormhole-status have been set by wormhole.
; The wormhole-input is just an alist specifying values for brr-gstack and
; brr-local-alist, where the gstack value is the gstack that rewrite passed to
; the brkpt1 handlers and the alist value is an alist binding variables from
; rewrite that brr might be interested in, e.g., the lemma, target,
; unify-subst, etc.  We push a new brr-status onto the current status and make
; the new status the current one (i.e., this function side-effects
; *wormhole-status-alist*).

; Expects and ensures Wormhole Coherence.

  (let* ((input (f-get-global 'wormhole-input state))
         (gstack (cdr (assoc-eq 'brr-gstack input)))
         (alist (cdr (assoc-eq 'brr-local-alist input)))
         (whs (f-get-global 'wormhole-status state))
         (new-whs
          (change brr-status whs
                  :brr-gstack gstack
                  :brr-local-alist alist
                  :brr-previous-status whs)))
    (set-persistent-whs-and-ephemeral-whs 'brr new-whs state)))

(defun pop-brr-status (state)

; This function sets the brr-status to the :brr-previous-status (unless
; that's nil, in which case we're already at the top-level of ACL2).

; Expects and ensures Wormhole Coherence.

  (let* ((whs (f-get-global 'wormhole-status state))
         (prev-whs (access brr-status whs :brr-previous-status)))
    (if (null prev-whs)
        state
        (set-persistent-whs-and-ephemeral-whs 'brr prev-whs state))))

(defun decode-type-alist (type-alist)

; Once upon a type we untranslated (caar type-alist) below.  But
; tilde-*-substitution-phrase, which is the only function which sees the output
; of this function in our sources, does an untranslate.

  (cond ((null type-alist) nil)
        (t (cons (cons (caar type-alist)
                       (decode-type-set (cadar type-alist)))
                 (decode-type-alist (cdr type-alist))))))

(defun translate-break-condition (xterm ctx state)
  (er-let* ((term (translate xterm '(nil) nil t ctx (w state) state)))

; known-stobjs = t (user interface)

           (let* ((used-vars (all-vars term))
                  (bad-vars (set-difference-eq used-vars '(state))))
             (cond
              (bad-vars
               (er soft ctx
                   "The only variable allowed in a break condition ~
                    is STATE.  Your form, ~x0, contains the ~
                    variable~#1~[~/s~] ~&2."
                   xterm (if (cdr bad-vars) 1 0) (reverse bad-vars)))
              (t (value term))))))

(defun eval-break-condition (rune term ctx state)
  (cond
   ((equal term *t*) (value t))
   ((not (termp term (w state)))
    (er soft ctx
        "The monitored rune ~x0 has a non-trivial break :condition, ~X12, ~
         which is no longer a term.  This is presumably because an undo ~
         erased some critical definition after the monitor was installed.  We ~
         are aborting this proof attempt and suggest you inspect ~
         :monitored-runes."
        rune term nil))
   (t (mv-let (erp okp latches)
        (ev term
            (list (cons 'state (coerce-state-to-object state)))
            state nil nil t)
        (declare (ignore latches))
        (cond
         (erp (pprogn
               (error-fms nil ctx nil (car okp) (cdr okp) state)
               (er soft ctx
                   "The break condition installed on ~x0 could not be ~
                    evaluated.  We are aborting this proof attempt."
                   rune)))
         (t (value okp)))))))

(defconst *default-free-vars-display-limit* 30)

(defmacro set-free-vars-display-limit (n)
  `(let ((n ,n))
     (prog2$ (or (natp n)
                 (er hard 'set-free-vars-display-limit
                     "The argument to set-free-vars-display-limit should ~
                     evaluate to a natural number, but it was given an ~
                     argument that evaluated to ~x0."
                     n))
             (f-put-global 'free-vars-display-limit n state))))

(defun free-vars-display-limit (state)
  (if (f-boundp-global 'free-vars-display-limit state)
      (let ((val (f-get-global 'free-vars-display-limit state)))
        (if (or (natp val) (null val))
            val
          *default-free-vars-display-limit*))
    *default-free-vars-display-limit*))

(mutual-recursion

(defun limit-failure-reason (failures-remaining failure-reason elided-p)
  (declare (xargs :guard (natp failures-remaining)))
  (case-match failure-reason
    ((hyp 'free-vars . alist)
     (cond ((zp failures-remaining)
            (mv 0 (list hyp 'free-vars 'elided) t))
           ((eq (car alist) 'hyp-vars)
            (mv (1- failures-remaining) failure-reason elided-p))
           (t (mv-let (new-failures-remaining new-alist elided-p)
                (limit-failure-reason-alist (1- failures-remaining) alist elided-p)
                (cond ((eql failures-remaining
                            new-failures-remaining) ;optimization
                       (mv failures-remaining failure-reason elided-p))
                      (t (mv new-failures-remaining
                             (list* hyp 'free-vars new-alist)
                             elided-p)))))))
    (& (mv (if (zp failures-remaining)
               failures-remaining
             (1- failures-remaining))
           failure-reason
           elided-p))))

(defun limit-failure-reason-alist (failures-remaining alist elided-p)
  (cond ((null alist)
         (mv failures-remaining alist elided-p))
        (t (mv-let (failures-remaining-1 failure-reason elided-p)
             (limit-failure-reason failures-remaining (cdar alist) elided-p)
             (mv-let (failures-remaining-2 rest-alist elided-p)
               (limit-failure-reason-alist failures-remaining-1 (cdr alist)
                                           elided-p)
               (mv failures-remaining-2
                   (cond ((and (not (zp failures-remaining))
                               (eql failures-remaining
                                    failures-remaining-2))
                          alist) ;optimization
                         (t (cons (cond
                                   ((and (not (zp failures-remaining))
                                         (eql failures-remaining
                                              failures-remaining-1))
                                    (car alist)) ;optimization
                                   (t (cons (caar alist) failure-reason)))
                                  rest-alist)))
                   elided-p))))))
)

(mutual-recursion

(defun fix-free-failure-reason (failure-reason)

; See tilde-@-failure-reason-phrase.

  (case-match failure-reason
    ((& 'free-vars 'hyp-vars . &)
     failure-reason)
    ((bkptr 'free-vars . failure-reason-lst)
     (list* bkptr
            'free-vars
            (fix-free-failure-reason-alist failure-reason-lst nil)))
    (& failure-reason)))

(defun fix-free-failure-reason-alist (x acc)

; We deliberately reverse x as we fix it; see tilde-@-failure-reason-phrase.

  (cond ((endp x) acc)
        (t ; x is (cons (cons unify-subst failure-reason) &)
         (fix-free-failure-reason-alist
          (cdr x)
          (cons (cons (caar x)
                      (fix-free-failure-reason (cdar x)))
                acc)))))
)

(defun ancestor-backchain-rune (ancestor)
  (and (access ancestor ancestor :bkptr)
       (let ((tokens (access ancestor ancestor :tokens)))
         (assert$ (and tokens (null (cdr tokens)))
                  (car tokens)))))

; The function backchain-limit-enforcers calls find-rules-of-rune.  Several
; record structures support the definition of find-rules-of-rune, because they
; support access-x-rule-rune.  We define those structures here, even though
; they might naturally be defined elsewhere (and remain as comments in their
; locations as of Version_8.0).

(defrec forward-chaining-rule
  ((rune . nume) trigger hyps concls . match-free) nil)

(defrec elim-rule
  (((nume . crucial-position) . (destructor-term . destructor-terms))
   (hyps . equiv)
   (lhs . rhs)
   . rune) nil)

(defrec generalize-rule (nume formula . rune) nil)

(defrec induction-rule (nume (pattern . condition) scheme . rune) nil)

(defrec built-in-clause ((nume . all-fnnames) clause . rune) t)

; Decoding Logical Names: decode-logical-name supports the definition of
; find-rules-of-rune, which in turn supports the definition of
; backchain-limit-enforcers; so we turn here to defining decode-logical-name.

(defun scan-to-defpkg (name wrld)

; We wish to give meaning to stringp logical names such as "MY-PKG".  We do it
; in an inefficient way: we scan the whole world looking for an event tuple of
; type DEFPKG and namex name.  We know that name is a known package and that it
; is not one in *initial-known-package-alist*.

  (cond ((null wrld) nil)
        ((and (eq (caar wrld) 'event-landmark)
              (eq (cadar wrld) 'global-value)
              (eq (access-event-tuple-type (cddar wrld)) 'DEFPKG)
              (equal name (access-event-tuple-namex (cddar wrld))))
         wrld)
        (t (scan-to-defpkg name (cdr wrld)))))

(defun multiple-assoc-terminal-substringp1 (x i alist)
  (cond ((null alist) nil)
        ((terminal-substringp x (caar alist) i (1- (length (caar alist))))
         (cons (car alist) (multiple-assoc-terminal-substringp1 x i (cdr alist))))
        (t (multiple-assoc-terminal-substringp1 x i (cdr alist)))))

(defun multiple-assoc-terminal-substringp (x alist)

; X and the keys of the alist are presumed to be strings.  This function
; compares x to the successive keys in the alist, succeeding on any key that
; contains x as a terminal substring.  Unlike assoc, we return the list of all
; pairs in the alist with matching keys.

  (multiple-assoc-terminal-substringp1 x (1- (length x)) alist))

(defun possibly-add-lisp-extension (str)

; String is a string.  If str ends in .lisp, return it.  Otherwise, tack .lisp
; onto the end and return that.

  (let ((len (length str)))
    (cond
     ((and (> len 5)
           (eql (char str (- len 5)) #\.)
           (eql (char str (- len 4)) #\l)
           (eql (char str (- len 3)) #\i)
           (eql (char str (- len 2)) #\s)
           (eql (char str (- len 1)) #\p))
      str)
     (t (string-append str ".lisp")))))

(defun stuff-standard-oi (cmds state)

; This function appends cmds (which must be a true list) onto standard-oi.  We
; act as though the entire system maintains the invariant that when standard-oi
; is a symbol ld-pre-eval-print is nil and when it is a list ld-pre-eval-print
; is t.  We maintain it here.  This has the convenient effect that -- if the
; condition is true now -- then the commands in cmds will be printed before
; they are executed and that when we get back down to *standard-oi* printing
; will be shut off.  There is no guarantee that this condition is invariant.
; The user might set ld-pre-eval-print at will.  The worse that will happen is
; undesirable pre-eval print behavior.

  (declare (xargs :guard (true-listp cmds)))
  (cond
   ((null cmds) state)
   (t (pprogn
       (f-put-global 'ld-pre-eval-print t state)
       (f-put-global 'standard-oi
                     (append cmds
                             (cond ((symbolp (f-get-global 'standard-oi state))
                                    (cons '(set-ld-pre-eval-print nil state)
                                          (f-get-global 'standard-oi state)))
                                   (t (f-get-global 'standard-oi state))))
                     state)))))

(defun defun-mode-prompt-string (state)
  (if (raw-mode-p state)
      "P"
    (case (default-defun-mode (w state))
      (:logic
       (if (gc-off state)
           (if (ld-skip-proofsp state)
               "s"
             "")
         (if (ld-skip-proofsp state)
             "!s"
           "!")))
      (otherwise ; :program
       (if (gc-off state)
           (if (ld-skip-proofsp state)
               "ps"
             "p")
         (if (ld-skip-proofsp state)
             "p!s"
           "p!"))))))

(defun brr-prompt (channel state)
  (the2s
   #.*fixnat-type*
   (fmt1 "~F0 ~s1~sr ~@2>"
         (list (cons #\0 (brr-depth state))
               (cons #\1 (f-get-global 'current-package state))
               (cons #\2 (defun-mode-prompt-string state))
               (cons #\r
                     #+:non-standard-analysis
                     (if (f-get-global 'script-mode state)
                         ""
                       "(r)")
                     #-:non-standard-analysis ""))
         0 channel state nil)))

; We now develop code to display type-alists nicely.

(defun ts< (x y)

; This is just a heuristic order for the type-alist command (proof-builder and
; break-rewrite).  First comes t, then non-nil, then nil, and finally we sort
; by type inclusion.

  (cond
   ((ts= x y)
    nil)
   ((ts= x *ts-t*)
    t)
   ((ts= y *ts-t*)
    nil)
   ((ts= x *ts-non-nil*)
    t)
   ((ts= y *ts-non-nil*)
    nil)
   ((ts= x *ts-nil*)
    t)
   ((ts= y *ts-nil*)
    nil)
   ((ts-subsetp x y)
    t)
   (t
    nil)))

(defun add-to-type-alist-segments (ts term segs)
  (cond
   ((or (endp segs)
        (ts< ts (caar segs)))
    (cons (cons ts (list term))
          segs))
   ((ts= ts (caar segs))
    (cons (cons ts (cons term (cdar segs)))
          (cdr segs)))
   (t
    (cons (car segs)
          (add-to-type-alist-segments ts term (cdr segs))))))

(defun merge-term-order (l1 l2)
  (declare (xargs :guard (and (pseudo-term-listp l1)
                              (pseudo-term-listp l2))))
  (cond ((endp l1) l2)
        ((endp l2) l1)
        ((term-order (car l1) (car l2))
         (cons (car l1) (merge-term-order (cdr l1) l2)))
        (t (cons (car l2) (merge-term-order l1 (cdr l2))))))

(defun merge-sort-term-order (l)
  (declare (xargs :guard (pseudo-term-listp l)))
  (cond ((endp (cdr l)) l)
        (t (merge-term-order (merge-sort-term-order (evens l))
                             (merge-sort-term-order (odds l))))))

(defun sort-type-alist-segments (segs)
  (if (endp segs)
      nil
    (cons (cons (caar segs)

; Unfortunately, term-order does not do a particularly great job from the point
; of view of displaying terms.  However, we use it anyhow here, if for no other
; reason so that the display order is predictable.

                (merge-sort-term-order (cdar segs)))
          (sort-type-alist-segments (cdr segs)))))

(defun type-alist-segments (type-alist acc)
  (if (endp type-alist)
      (sort-type-alist-segments acc)
    (type-alist-segments (cdr type-alist)
                         (add-to-type-alist-segments
                          (cadar type-alist)
                          (caar type-alist)
                          acc))))

(defun print-terms (terms iff-flg wrld evisc-tuple)

; Print untranslations of the given terms with respect to iff-flg, following
; each with a newline.

; We use cw instead of the fmt functions because we want to be able to use this
; function in print-type-alist-segments (used in brkpt1), which does not return
; state.

  (if (endp terms)
      terms
    (prog2$
     (cw "~Y01"
         (untranslate (car terms) iff-flg wrld)
         evisc-tuple)
     (print-terms (cdr terms) iff-flg wrld evisc-tuple))))

(defun print-type-alist-segments (segs wrld evisc-tuple)

; We use cw instead of the fmt functions because we want to be able to use this
; function in brkpt1, which does not return state.

  (if (endp segs)
      segs
    (prog2$ (cw "-----~%Terms with type ~x0:~%"
                (decode-type-set (caar segs)))
            (prog2$ (print-terms (cdar segs)
                                 (member (caar segs)
                                         (list *ts-t*
                                               *ts-non-nil*
                                               *ts-nil*
                                               *ts-boolean*))
                                 wrld
                                 evisc-tuple)
                    (print-type-alist-segments (cdr segs) wrld evisc-tuple)))))

(defun print-type-alist (type-alist wrld evisc-tuple)
  (print-type-alist-segments (type-alist-segments type-alist nil)
                             wrld
                             evisc-tuple))

; End of code for printing type-alists.

(defun print-pot-lst (pot-lst evisc-tuple)
  (cond
   ((null pot-lst) (cw "~%"))
   (t (prog2$
       (cw "-----~|For maximal term ~X02~|the list of polynomials is:~|~X12~|"
           (access linear-pot (car pot-lst) :var)
           (append (show-poly-lst
                    (access linear-pot (car pot-lst) :negatives)
                    nil)
                   (show-poly-lst
                    (access linear-pot (car pot-lst) :positives)
                    nil))
           evisc-tuple)
       (print-pot-lst (cdr pot-lst) evisc-tuple)))))

; Start support for find-rules-of-rune, in support of
; backchain-limit-enforcers.

(defun decode-logical-name (name wrld)

; Given a logical name, i.e., a symbol with an 'absolute-event-number property
; or a string naming a defpkg or include-book, we return the tail of wrld
; starting with the introductory event.  We return nil if name is illegal.

  (cond
   ((symbolp name)
    (cond ((eq name :here)
           (scan-to-event wrld))
          (t
           (let ((n (getpropc name 'absolute-event-number nil wrld)))
             (cond ((null n) nil)
                   (t (lookup-world-index 'event n wrld)))))))
   ((and (stringp name)
         (find-non-hidden-package-entry name
                                        (global-val 'known-package-alist
                                                    wrld)))
    (cond ((find-package-entry name *initial-known-package-alist*)

; These names are not DEFPKGd and so won't be found in a scan.  They
; are introduced by absolute event number 0.

           (lookup-world-index 'event 0 wrld))
          (t (scan-to-defpkg name wrld))))
   (t nil)))

(defun access-x-rule-rune (x rule)

; Given a rule object, rule, of record type x, we return the :rune of rule.
; This is thus typically ``(access x rule :rune).''

; Note: We include with every case the rule-class tokens that create this rule
; so that we can search for any such tokens and find this function when adding
; a new, similar, rule-class.

; There is no record object generated only by        ;;; :refinement
;                                                    ;;; :tau-system
  (case x
        (recognizer-tuple                            ;;; :compound-recognizer
         (access recognizer-tuple rule :rune))
        (type-prescription                           ;;; :type-prescription
         (access type-prescription rule :rune))
        (congruence-rule                             ;;; :congruence
                                                     ;;; :equivalence
         (access congruence-rule rule :rune))
        (pequiv                                      ;;; :congruence
         (access congruence-rule
                 (access pequiv rule :congruence-rule)
                 :rune))
        (rewrite-rule                                ;;; :rewrite
                                                     ;;; :meta
                                                     ;;; :definition
         (access rewrite-rule rule :rune))
        (well-founded-relation-rule                  ;;; :well-founded-relation
; No such record type, but we pretend!
         (cddr rule))
        (linear-lemma                                ;;; :linear
         (access linear-lemma rule :rune))
        (forward-chaining-rule                       ;;; :forward-chaining
         (access forward-chaining-rule rule :rune))
        (built-in-clause                             ;;; :built-in-clause
         (access built-in-clause rule :rune))
        (elim-rule                                   ;;; :elim
         (access elim-rule rule :rune))
        (generalize-rule                             ;;; :generalize
         (access generalize-rule rule :rune))
        (induction-rule                              ;;; :induction
         (access induction-rule rule :rune))
        (type-set-inverter-rule                      ;;; :type-set-inverter
         (access type-set-inverter-rule rule :rune))
        (otherwise (er hard 'access-x-rule-rune
                       "Unrecognized rule class, ~x0."
                       x))))

(defun collect-x-rules-of-rune (x rune lst ans)

; Lst is a list of rules of type x.  We collect all those elements of lst
; with :rune rune.

  (cond ((null lst) ans)
        ((equal rune (access-x-rule-rune x (car lst)))
         (collect-x-rules-of-rune x rune (cdr lst)
                                  (add-to-set-equal (car lst) ans)))
        (t (collect-x-rules-of-rune x rune (cdr lst) ans))))

(defun collect-congruence-rules-of-rune-in-geneqv-lst (geneqv-lst rune ans)

; A geneqv is a list of congruence rules.  Geneqv-lst, above, is a list of
; geneqvs.  We scan every congruence rule in geneqv-lst and collect those with
; the :rune rune.

  (cond
   ((null geneqv-lst) ans)
   (t (collect-congruence-rules-of-rune-in-geneqv-lst
       (cdr geneqv-lst) rune
       (collect-x-rules-of-rune 'congruence-rule rune (car geneqv-lst) ans)))))

(defun collect-congruence-rules-of-rune (congruences rune ans)

; The 'congruences property of an n-ary function symbol is a list of tuples,
; each of which is of the form (equiv geneqv1 ... geneqvn), where each geneqvi
; is a list of congruence rules.  Congruences is the 'congruences property of
; some function.  We scan it and collect every congruence rule in it that has
; :rune rune.

  (cond
   ((null congruences) ans)
   (t (collect-congruence-rules-of-rune
       (cdr congruences) rune
       (collect-congruence-rules-of-rune-in-geneqv-lst (cdr (car congruences))
                                                       rune ans)))))

(defun collect-pequivs-of-rune (alist rune ans)

; Alist has the form of the :deep or :shallow field of the 'pequivs property of
; a function symbol.  Thus, each element of alist is of the form (equiv pequiv1
; ... pequivn), where each pequivi is a pequiv record.  We scan this alist and
; collect every pequiv record in it whose :rune is rune.

  (cond
   ((null alist) ans)
   (t (collect-pequivs-of-rune
       (cdr alist)
       rune
       (collect-x-rules-of-rune 'pequiv rune (cdr (car alist)) ans)))))

(defun find-rules-of-rune2 (rune sym key val ans)

; (sym key . val) is a member of wrld.  We collect all the rules in val with
; :rune rune.  This function is patterned after info-for-x-rules.

; Warning: Keep this function in sync with info-for-x-rules.  In that spirit,
; note that tau rules never store runes and hence are completely ignored
; here, as in info-for-x-rules.

  (let ((token (car rune)))

; As an efficiency, we do not look for rune in places where it cannot occur.
; For example, if token is :elim then there is no point in searching through
; the 'lemmas properties.  In general, each case below insists that token is of
; the appropriate class.  Sometimes there are more than one.  For example, the
; 'lemmas property may contain :rewrite, :definition, and :meta runes, all of
; which are stored as REWRITE-RULEs.

    (cond
     ((eq key 'global-value)
      (case sym
            (well-founded-relation-alist
             (if (eq token :well-founded-relation)
                 (collect-x-rules-of-rune 'well-founded-relation-rule rune
                                          val ans)
                 ans))
            (built-in-clauses
             (if (eq token :built-in-clause)
                 (collect-x-rules-of-rune 'built-in-clause rune val ans)
                 ans))
            (type-set-inverter-rules
             (if (eq token :type-set-inverter)
                 (collect-x-rules-of-rune 'type-set-inverter-rule rune
                                          val ans)
                 ans))
            (generalize-rules
             (if (eq token :generalize)
                 (collect-x-rules-of-rune 'generalize-rule rune val ans)
                 ans))
            (otherwise ans)))
     (t
      (case key
            (lemmas
             (if (member-eq token '(:rewrite :meta :definition))
                 (collect-x-rules-of-rune 'rewrite-rule rune val ans)
                 ans))
            (linear-lemmas
             (if (eq token :linear)
                 (collect-x-rules-of-rune 'linear-lemma rune val ans)
                 ans))
            (eliminate-destructors-rules
             (if (eq token :elim)
                 (collect-x-rules-of-rune 'elim-rule rune val ans)
                 ans))
            (congruences
             (if (member-eq token '(:congruence :equivalence))
                 (collect-congruence-rules-of-rune val rune ans)
                 ans))
            (pequivs
             (if (eq token :congruence)
                 (collect-pequivs-of-rune
                  (access pequivs-property val :deep)
                  rune
                  (collect-pequivs-of-rune
                   (access pequivs-property val :shallow)
                   rune
                   ans))
               ans))
            (coarsenings

; :Refinement rules add to the 'coarsenings property.  If equiv1 is a
; refinement of equiv2, then equiv2 is a coarsening of equiv1 and the lemma
; establishing that fact adds equiv2 to the 'coarsenings property of equiv1.
; There is no rule object corresponding to this fact.  Hence, even if rune is
; the :refinement rune responsible for adding some equiv2 to this list, we
; won't find a rule object here by the name rune.

; Similar comments apply to :equivalence rules.  They add to the 'coarsenings
; property but no rule object exists.  It should be noted that some congruence
; rules are added by lemmas of class :equivalence and those rules are named by
; :equivalence runes and are found among the 'congruences properties.

             ans)
            (forward-chaining-rules
             (if (eq token :forward-chaining)
                 (collect-x-rules-of-rune 'forward-chaining-rule rune val ans)
                 ans))
            (type-prescriptions
             (if (eq token :type-prescription)
                 (collect-x-rules-of-rune 'type-prescription rune val ans)
                 ans))
            (induction-rules
             (if (eq token :induction)
                 (collect-x-rules-of-rune 'induction-rule rune val ans)
                 ans))
            (recognizer-alist
             (if (eq token :compound-recognizer)
                 (collect-x-rules-of-rune 'recognizer-tuple rune val ans)
               ans))
            (otherwise ans))))))

(defun find-rules-of-rune1 (rune props ans)

; Props is a list of triples and can be considered a segment of some wrld.  (It
; is not only because duplicates have been removed.)  We visit every property
; and collect all the rules with :rune rune.

  (cond ((null props) ans)
        ((eq (cddar props) *acl2-property-unbound*)
         (find-rules-of-rune1 rune (cdr props) ans))
        (t (find-rules-of-rune1 rune (cdr props)
                                (find-rules-of-rune2 rune
                                                     (caar props)
                                                     (cadar props)
                                                     (cddar props)
                                                     ans)))))

(defun world-to-next-event (wrld)
  (cond ((null wrld) nil)
        ((and (eq (caar wrld) 'event-landmark)
              (eq (cadar wrld) 'global-value))
         nil)
        (t (cons (car wrld)
                 (world-to-next-event (cdr wrld))))))

(defun actual-props (props seen acc)

; Props is a list whose elements have the form (sym key . val), where val could
; be *acl2-property-unbound*.  Seen is the list containing some (sym key . &)
; for each pair (sym key) that has already been seen.

  (cond
   ((null props)
    (prog2$ (fast-alist-free seen)
            (reverse acc)))
   ((member-eq (cadar props) (cdr (hons-get (caar props) seen)))
    (actual-props (cdr props) seen acc))
   ((eq (cddr (car props)) *acl2-property-unbound*)
    (actual-props (cdr props)
                  (hons-acons (caar props)
                              (cons (cadar props)
                                    (cdr (hons-get (caar props) seen)))
                              seen)
                  acc))
   (t
    (actual-props (cdr props)
                  (hons-acons (caar props)
                              (cons (cadar props)
                                    (cdr (hons-get (caar props) seen)))
                              seen)
                  (cons (car props) acc)))))

(defun find-rules-of-rune (rune wrld)

; Find all the rules in wrld with :rune rune.  We do this by first obtaining
; that segment of wrld consisting of the properties stored by the event
; named by the base symbol of rune.  Then we collect every rule mentioned
; in the segment, provided the rule has :rune rune.

  (declare (xargs :guard (and (plist-worldp wrld)
                              (runep rune wrld))))
  (let ((wrld-tail (decode-logical-name (base-symbol rune) wrld)))
    (find-rules-of-rune1 rune
                         (actual-props
                          (world-to-next-event (cdr wrld-tail))
                          'find-rules-of-rune1
                          nil)
                         nil)))

(defun backchain-limit-enforcers (position ancestors wrld)

; Backchaining has failed due to a backchain-limit, for a rule of class
; :rewrite or :linear.  Find indices of all ancestors whose backchain-limit
; could be the culprit, as reported by the :ANCESTORS break-rewrite command.
; Position is the position in the top-level ancestors, which is 0 at the top
; level; it is a bound on how many times we are allowed to backchain in order
; to avoid the current failure.

  (cond ((endp ancestors) nil)
        (t (let* ((rune (ancestor-backchain-rune (car ancestors)))
                  (rule (and rune
                             (car (find-rules-of-rune rune wrld)))))
             (cond (rule
                    (let* ((linearp (eq (car rune) :linear))
                           (backchain-limit-lst
                            (if linearp
                                (access linear-lemma rule :backchain-limit-lst)
                              (access rewrite-rule rule :backchain-limit-lst)))
                           (bkptr (access ancestor (car ancestors) :bkptr))
                           (hyp-backchain-limit
                            (and backchain-limit-lst
                                 (if (and (not linearp)
                                          (eq (access rewrite-rule rule
                                                      :subclass)
                                              'meta))
                                     backchain-limit-lst ; a numeric limit
                                   (nth (1- bkptr)
                                        backchain-limit-lst)))))
                      (cond ((and hyp-backchain-limit
                                  (>= (1+ position) hyp-backchain-limit))
                             (cons (cons position hyp-backchain-limit)
                                   (backchain-limit-enforcers (1+ position)
                                                              (cdr ancestors)
                                                              wrld)))
                            (t
                             (backchain-limit-enforcers (1+ position)
                                                        (cdr ancestors)
                                                        wrld))))))))))

(defun tilde-*-ancestors-stack-msg1 (i ancestors wrld evisc-tuple)
  (cond ((endp ancestors) nil)
        ((ancestor-binding-hyp-p (car ancestors))
         (cons (msg "~c0. Binding Hyp: ~Q12~|~
                     ~ ~ ~ ~ ~ Unify-subst:  ~Q32~%"
                    (cons i 2)
                    (untranslate (dumb-negate-lit
                                  (ancestor-binding-hyp/hyp (car ancestors)))
                                 t wrld)
                    evisc-tuple
                    (ancestor-binding-hyp/unify-subst (car ancestors)))
               (tilde-*-ancestors-stack-msg1 (+ 1 i) (cdr ancestors)
                                             wrld evisc-tuple)))
        (t (cons (let ((tokens (access ancestor (car ancestors) :tokens)))
                   (msg "~c0. Hyp: ~Q12~|~
                         ~ ~ ~ ~ ~ Rune~#3~[:  ~x4~/s:  ~x3~]~%"
                        (cons i 2)
                        (untranslate (dumb-negate-lit
                                      (access ancestor (car ancestors) :lit))
                                     t wrld)
                        evisc-tuple
                        tokens
                        (car tokens)))
                 (tilde-*-ancestors-stack-msg1 (+ 1 i) (cdr ancestors)
                                               wrld evisc-tuple)))))

(defun tilde-*-ancestors-stack-msg (ancestors wrld evisc-tuple)
  (list "" "~@*" "~@*" "~@*"
         (tilde-*-ancestors-stack-msg1 0 ancestors wrld evisc-tuple)))

(defun semi-initialize-brr-wormhole (state)

; This function (sort of) initializes the persistent-whs for the brr wormhole.
; More precisely, if the brr wormhole has not been set up yet, this function
; initializes it so that all fields are nil.  If it has been set up and we're
; not in the brr wormhole, it preserves the BRR-MONITORED-RUNES of the
; top-level brr-status and nils out the others.  If we are in the brr wormhole
; then the status has already been set up and brr processing in flight is
; depending on it, so we do nothing.  (If we're in the processing of aborting
; and we're in the brr wormhole, the wormhole1 cleanup form will handle this.)

; Before this function is first called, there is no entry for BRR on the
; *wormhole-status-alist*.  That means the persistent-whs for brr is NIL.  That
; is actually ok.  All brr-status fields of NIL are NIL.  According to the
; definition of wormhole1, any non-:SKIP entry code is equivalent to :ENTER.

; Warning: One might be tempted to do this update with
; set-persistent-whs-and-ephemeral-whs but that would be wrong!  If we used
; that function while we're in the brr wormhole we'd overwrite the active
; status!  This is a case where we must use wormhole-eval, make sure we're not
; already in brr, and only write to the persistent-whs.

  (cond
   ((eq (f-get-global 'wormhole-name state) 'brr)
; Brr status is already set up.
    nil)
   (t (wormhole-eval
       'brr
       '(lambda (whs)
          (change brr-status whs
                  :brr-monitored-runes (access brr-status
                                               (top-level-brr-status whs)
                                               :brr-monitored-runes)
                  :brr-gstack nil
                  :brr-local-alist nil
                  :brr-previous-status nil))
       nil))))

(defun show-ancestors-stack-msg (state evisc-tuple)
  (msg "Ancestors stack (most recent entry on top):~%~*0~%Use ~x1 to see ~
        actual ancestors stack.~%"
       (tilde-*-ancestors-stack-msg
        (get-brr-local 'ancestors state)
        (w state)
        evisc-tuple)
       '(get-brr-local 'ancestors state)))

(defun tilde-@-failure-reason-phrase1-backchain-limit (hyp-number
                                                       ancestors
                                                       state
                                                       evisc-tuple)
  (msg
   "a backchain limit was reached while processing :HYP ~x0.  ~@1"
   hyp-number
   (let ((pairs (backchain-limit-enforcers 0 ancestors (w state))))
     (cond
      ((null pairs)
       (let ((str "  Note that the brr command, :ANCESTORS, will show you the ~
                   ancestors stack."))
         (cond ((backchain-limit (w state) :rewrite)
                (msg "This appears to be due to the global backchain-limit of ~
                      ~x0.~@1"
                     (backchain-limit (w state) :rewrite)
                     str))
               (t

; If the global backchain-limit for :rewrite is nil, and no ancestor has a
; relevant backchain-limit (i.e., pairs is nil), then the hypothesis at hand
; must have a backchain-limit of 0.  Through Version_8.3 we did not handle this
; case properly; it seems we assumed that if the hypothesis has a
; backchain-limit of 0 then pairs must be nil, but that is not necessarily the
; case as illustrated by the following example (inspired by a bug report from
; Mihir Mehta).

;   (defun p1 (x) (integerp x))
;   (defun p2 (x) (integerp x))
;   (defun p3 (x) (integerp x))
;   (defthm p1->p2
;     (implies (p1 x) (p2 x))
;     :rule-classes ((:rewrite :backchain-limit-lst (0))))
;   (defthm p2->p3
;     (implies (p2 x) (p3 x)))
;   (in-theory (disable p1 p2 p3))
;   (brr t)
;   (monitor '(:rewrite p1->p2) t)
;   (thm (p3 a))

                (msg "Note that the limit is 0 for that :HYP.")))))
      (t
       (msg "The ancestors stack is below.  The ~#0~[entry~/entries~] at ~
             index ~&0 ~#0~[shows~/each show~] a rune whose ~#0~[~/respective ~
             ~]backchain limit of ~v1 has been reached, for backchaining ~
             through its indicated hypothesis.~|~%~@2"
            (strip-cars pairs)
            (strip-cdrs pairs)
            (show-ancestors-stack-msg state evisc-tuple)))))))

(defun get-evg (q ctx)

; Q is a quotep, or at least we expect it to be.  We cause a hard error if not,
; else we return the "explicit value guts".

  (if (quotep q)
      (cadr q)
    (er hard ctx
        "We expected a quotep in this context, variables, but ~x0 is not a ~
         quotep!"
        q)))

(defun get-brr-one-way-unify-info (lemma rcnst)

; This function returns (mv rune brk-cmd-name pattern restrictions) in
; accordance with how lemma is matched in the rewrite clique.

; This function knows everything there is to know about how one-way-unify is
; used in the rewrite clique!  We need this when we try to explain near-misses
; on monitored rules.  As of this writing, only two classes of rules are
; monitored, namely rewrite-rules (which include definitions and
; rewrite-quoted-constant rules as subclasses) and linear-lemmas.  The former
; access the pattern with :lhs (see caveat) and the latter access pattern with
; :max-term.  (Caveat: when a rewrite-rule is actually of subclass
; rewrite-quoted-constant of form 2, the pattern we attempt to match is
; actually the :rhs!  While that pattern is always a variable, restrictions
; could prevent it from matching.  In any case, the break command :lhs will
; display the pattern.)  Both :lhs and :max-term are set up in *brkpt1-aliases*
; and *brkpt2-aliases*, so we can refer to those field names as brkpt commands
; in our messages, but we must extract the pattern actually used, the
; restrictions, and what the break command used to view the pattern in the
; break environment.  Linear rules don't have restrictions.

  (declare (xargs :guard
                  (and (or (weak-rewrite-rule-p lemma)
                           (weak-linear-lemma-p lemma))
                       (weak-rewrite-constant-p rcnst))))

; Note: The two ``guard issues'' tagged below are guaranteed to be true if
; lemma really is a well-formed rewrite-rule (as all of our stored
; rewrite-rules are).  But we don't want to characterize what that means, so we
; suffer the runtime checks just so we can verify the guards of this function.

  (if (eq (record-type lemma) 'rewrite-rule)
      (mv (access rewrite-rule lemma :rune)
          :lhs
          (if (and (eq (access rewrite-rule lemma :subclass)
                       'rewrite-quoted-constant)
                   (let ((heuristic-info
                          (access rewrite-rule lemma :heuristic-info)))
                     (and (consp heuristic-info) ; guard issue
                          (eql (car heuristic-info) 2))))
              (access rewrite-rule lemma :rhs)
              (access rewrite-rule lemma :lhs))
          (let ((restrictions-alist (access rewrite-constant rcnst
                                            :restrictions-alist)))
            (if (alistp restrictions-alist) ; guard issue
                (cdr (assoc-equal
                      (access rewrite-rule lemma :rune)
                      restrictions-alist))
                nil)))
      (mv (access linear-lemma lemma :rune)
          :max-term
          (access linear-lemma lemma :max-term)
          nil)))

(mutual-recursion

(defun abstract-pat1 (k-flg pat vars)

; K-flg may be a nat, in which case we abstract down to level k-flg, or t, in
; which case we abstract all quoted lambdas.  The lambda abstraction ignores
; ilks.

  (declare (xargs :guard (and (or (eq k-flg t)
                                  (natp k-flg))
                              (pseudo-termp pat)
                              (true-listp vars))
                  :verify-guards nil
                  :measure (acl2-count pat)))
  (cond
   ((eql k-flg 0)
    (let ((new-var (genvar 'brr "GENSYM" 0 vars)))
      (mv new-var (cons new-var vars))))
   ((variablep pat) (mv pat vars))
   ((fquotep pat)
    (cond ((and (eq k-flg t)
                (consp (unquote pat))
                (eq (car (unquote pat)) 'lambda))
           (let ((new-var (genvar 'brr "GENSYM" 0 vars)))
             (mv new-var (cons new-var vars))))
          (t (mv pat vars))))
   (t (mv-let (new-args new-vars)
        (abstract-pat1-lst (if (natp k-flg)
                                   (- k-flg 1)
                                   k-flg)
                               (fargs pat) vars)
        (mv (fcons-term (ffn-symb pat) new-args)
            new-vars)))))

(defun abstract-pat1-lst (k-flg pats vars)
  (declare (xargs :guard (and (or (eq k-flg t)
                                  (natp k-flg))
                              (pseudo-term-listp pats)
                              (true-listp vars))
                  :measure (acl2-count pats)))
  (cond
   ((endp pats) (mv nil vars))
   (t (mv-let (new-arg new-vars)
        (abstract-pat1 k-flg (car pats) vars)
        (mv-let (new-args new-vars)
          (abstract-pat1-lst k-flg (cdr pats) new-vars)
          (mv (cons new-arg new-args) new-vars)))))))

(defun abstract-pat (k-flg pat)
  (declare (xargs :guard (and (or (eq k-flg t) (natp k-flg))
                              (pseudo-termp pat))))
  (mv-let (new-pat vars)
    (abstract-pat1 k-flg pat (all-vars pat))
    (declare (ignore vars))
    new-pat))

(defun alistp-listp (x)
  (declare (xargs :guard t))
  (cond
   ((atom x) (eq x nil))
   (t (and (alistp (car x))
           (alistp-listp (cdr x))))))

(defun one-way-unify-restrictions1 (pat term restrictions)
  (declare (xargs :guard (and (pseudo-termp pat)
                              (pseudo-termp term)
                              (alistp-listp restrictions))))
  (cond
   ((endp restrictions)
    (mv nil nil))
   (t (mv-let (unify-ans unify-subst)
              (one-way-unify1 pat term (car restrictions))
              (cond
               (unify-ans (mv unify-ans unify-subst))
               (t (one-way-unify-restrictions1 pat term (cdr restrictions))))))))

(defun one-way-unify-restrictions (pat term restrictions)
  (declare (xargs :guard (and (pseudo-termp pat)
                              (pseudo-termp term)
                              (alistp-listp restrictions))))
  (cond
   ((null restrictions)
    (one-way-unify pat term))
   (t (one-way-unify-restrictions1 pat term restrictions))))

(defun symbol-alist-to-keyword-value-list (alist)

; We convert a symbol alist to a keyword-value-listp (but showing the full
; translations of terms, not their untranslations).  We assume the keys in
; alist are keywords!

  (declare (xargs :guard (alistp alist)))
  (cond ((endp alist) nil)
        (t (cons (car (car alist))
                 (cons (cdr (car alist))
                       (symbol-alist-to-keyword-value-list (cdr alist)))))))

(defun brr-criteria-alistp (alist)
  (declare (xargs :guard t))
  (cond
   ((atom alist) (equal alist nil))
   ((not (consp (car alist))) nil)
   ((eq (car (car alist)) :depth)
    (and (natp (cdr (car alist)))
         (brr-criteria-alistp (cdr alist))))
   ((eq (car (car alist)) :abstraction)
    (and (pseudo-termp (cdr (car alist)))
         (brr-criteria-alistp (cdr alist))))
   ((eq (car (car alist)) :lambda)
    (and (booleanp (cdr (car alist)))
         (brr-criteria-alistp (cdr alist))))
   (t (brr-criteria-alistp (cdr alist)))))

(defun make-built-in-brr-near-miss-msg (brr-cmd-name
                                        pat alist
                                        depth-criterion-satisfiedp
                                        abstraction-criterion-satisfiedp
                                        lambda-criterion-satisfiedp)

; Pat is the pattern that nearly matched :target and alist is the (translated)
; criteria alist.  Assuming that one or more of the criteria is satisfied, we
; return a message that explains which criteria are satisfied.  We assume the
; message here will be printed as part of a message with an introductory
; sentence like ``Near-Miss of (:REWRITE FOO): The rule's pattern, (F X (G X
; Y)), did not match the current :TARGET, (F aaa (G bbb ccc)) (under the
; restrictions (((X XXX)))), but ...'', where the ... is this message as
; printed with ~@ as part of the introductory sentence produced by the function
; near-miss-brkpt1.

  (declare (xargs :guard (and (pseudo-termp pat)
                              (brr-criteria-alistp alist)
                              (implies depth-criterion-satisfiedp
                                       (natp (cdr (assoc-eq :depth alist)))))))

; We nfix below because :depth must be bound to a natp.  In fact, we know it is,
; by the :guard above, except for the fact that we don't know
  (let* ((depth-msg
          (if depth-criterion-satisfiedp
              (list (msg "* The abstraction of ~x0 to depth ~x1, namely the ~
                          pattern ~X23, matches :TARGET."
                         brr-cmd-name
                         (cdr (assoc-eq :depth alist))
                         (abstract-pat
                          (cdr (assoc-eq :depth alist))
                          pat)
                         nil))
              nil))
         (abstraction-msg
          (if abstraction-criterion-satisfiedp
              (list (msg "* The :ABSTRACTION pattern provided in your ~
                          monitor, ~x0, matches :TARGET."
                         (cdr (assoc-eq :abstraction alist))))
              nil))
         (lambda-msg
          (if lambda-criterion-satisfiedp
              (list (msg "* ~x0 matches :TARGET except at one or more quoted ~
                          LAMBDA constants."
                         brr-cmd-name))
              nil))
         (reasons (append depth-msg
                          abstraction-msg
                          lambda-msg)))
    (msg "However, this is considered a NEAR MISS under the break criteria, ~
          ~X01, specified when this rule was monitored.  The following ~
          ~#2~[criterion is~/criteria are~] satisfied.~%~%~*3"
         (symbol-alist-to-keyword-value-list alist)
         nil
         (if (cdr reasons) 1 0)
         (list "" "~@*~%~%" "~@*~%~%" "~@*~%~%"
               reasons))))

(defun built-in-brr-near-missp (msgp lemma target rcnst criteria-alist)

; We know that the pattern in lemma failed to match the target term to which it
; was applied.  This predicate determines whether it was a near-miss according
; to the criteria-alist.  If so, depending on msgp, we either return t or a
; message explaining the near miss.  To do this we must extract from the lemma
; the component that was (unsuccessfully) matched against target.  That
; information could have been passed down the call hierarchy to here but there
; is a reason we didn't do it that way: we view this function as the built-in
; default value for brr-near-missp, to which we want the user to be able to
; attach more elaborate senses of ``near miss.''  So we designed an interface
; at a slightly higher level than we would have otherwise.

; This built-in function is only checks the criteria :depth, :abstraction, and
; :lambda and ignores all other keys.  We assume that if :depth is specified,
; its value is a natural, if :abstraction is specified, its value is a
; translated term, and if :lambda is specified its value is a Boolean.  Note
; that we try the criteria in the order :depth, :abstraction, :lambda, and quit
; as soon as one is satisfied (provided we are only looking for a Boolean
; answer).  If msgp is t then, of course, we try all the criteria.

  (declare (xargs :guard (and (or (weak-rewrite-rule-p lemma)
                                  (weak-linear-lemma-p lemma))
                              (pseudo-termp target)
                              (weak-rewrite-constant-p rcnst)
                              (brr-criteria-alistp criteria-alist))))
  (mv-let (rune brr-cmd-name pattern restrictions)
    (get-brr-one-way-unify-info lemma rcnst)
    (declare (ignore rune))
    (cond
     ((and (pseudo-termp pattern)
           (alistp-listp restrictions))

; In order to verify the guards on this function we must make sure pattern and
; restrictions are the right shapes.  We know they are when lemma and rcnst are
; actually as maintained by us!  But we don't want to prove that and so we
; suffer the necessary runtime checks to allow guard verification here.  If
; pattern and restrictions are not appropriate, we just indicate that there was
; no near-miss.

      (let* ((depth-arg (assoc-eq :depth criteria-alist))
             (depth-criterion-satisfiedp
              (if (cdr depth-arg)
                  (mv-let (flg unify-subst)
                    (one-way-unify-restrictions
                     (abstract-pat (cdr depth-arg) pattern)
                     target
                     restrictions)
                    (declare (ignore unify-subst))
                    flg)
                  nil))
             (abstraction-arg (if (and (not msgp) depth-criterion-satisfiedp)
                                  nil
                                  (assoc-eq :abstraction criteria-alist)))
             (abstraction-criterion-satisfiedp
              (if (cdr abstraction-arg)
                  (mv-let (flg unify-subst)
                    (one-way-unify-restrictions
                     (cdr abstraction-arg)
                     target
                     restrictions)
                    (declare (ignore unify-subst))
                    flg)
                  nil))
             (lambda-arg (if (and (not msgp)
                                  (or depth-criterion-satisfiedp
                                      abstraction-criterion-satisfiedp))
                             nil
                             (assoc-eq :lambda criteria-alist)))
             (lambda-criterion-satisfiedp
              (if (cdr lambda-arg)
                  (mv-let (flg unify-subst)
                    (one-way-unify-restrictions
                     (abstract-pat (cdr lambda-arg) pattern)
                     target
                     restrictions)
                    (declare (ignore unify-subst))
                    flg)
                  nil)))
        (if (or depth-criterion-satisfiedp
                abstraction-criterion-satisfiedp
                lambda-criterion-satisfiedp)
            (if msgp
                (make-built-in-brr-near-miss-msg brr-cmd-name
                                                     pattern
                                                     criteria-alist
                                                     depth-criterion-satisfiedp
                                                     abstraction-criterion-satisfiedp
                                                     lambda-criterion-satisfiedp)
                t)
            nil)))
     (t nil))))

(defproxy brr-near-missp

; The rewriter has tried to match the pattern in lemma to target under the
; restrictions in rcnst.  The match failed.  We determine whether this
; constitutes a near miss according to the criteria in criteria-alist.  If so,
; we return t or, if msgp is non-nil, a message explaining the near miss.  If
; not, we return nil.

; The alist is a symbol-alist that pairs keywords to their translated values.
; It is the translated version of the keyword-value-list provided to the
; :monitor command when the lemma was monitored.  E.g., it is

; ((:condition . 't) (:depth . 3) (:abstraction . (f '44 (car (cdr z))))),

; rather than

; (:condition t :depth 3 :abstraction (f 44 (cadr z)))!

  (* * * * *) => *)

(defattach (brr-near-missp built-in-brr-near-missp)
  :skip-checks t)

(mutual-recursion

(defun tilde-@-failure-reason-free-phrase (hyp-number alist level unify-subst
                                                      evisc-tuple state)

; Alist is a list of pairs (unify-subst . failure-reason).  Level is initially
; 0 and increases as we dive into failure-reason.

  (cond
   ((null alist) "")
   (t
    (let ((new-unify-subst (caar alist))
          (new-failure-reason (cdar alist)))
      (msg "~t0[~x1]~*2~|~@3~@4~@5"
           (if (< hyp-number 10) (* 4 level) (1- (* 4 level)))
           hyp-number
           (tilde-*-alist-phrase (alist-difference-eq new-unify-subst unify-subst)
                                 evisc-tuple
                                 (+ 4 (* 4 level)))
           (if (let ((fr (if (and (consp new-failure-reason)
                                  (eq (car new-failure-reason) 'cached))
                             (cdr new-failure-reason)
                           new-failure-reason)))
                 (and (consp fr)
                      (integerp (car fr))
                      (or (not (and (consp (cdr fr))
                                    (eq (cadr fr) 'free-vars)))
                          (and (consp (cdr fr))
                               (consp (cddr fr))
                               (member-eq (caddr fr)
                                          '(hyp-vars elided))))))
               "Failed because "
             "")
           (tilde-@-failure-reason-phrase1 new-failure-reason (1+ level)
                                           new-unify-subst evisc-tuple nil
                                           state)
           (tilde-@-failure-reason-free-phrase hyp-number
                                               (cdr alist) level unify-subst
                                               evisc-tuple state))))))

(defun tilde-@-failure-reason-phrase1 (failure-reason level unify-subst
                                                      evisc-tuple
                                                      free-vars-display-limit
                                                      state)
  (cond ((eq failure-reason 'time-out)
         "we ran out of time.")
        ((eq failure-reason 'refinement-failure)
         "the rule's equivalence relation is not a refinement of the geneqv.")
        ((eq failure-reason 'near-miss)
         "the pattern (:LHS or :MAX-TERM) did not match the :TARGET.")
        ((eq failure-reason 'loop-stopper)
         "it permutes a big term forward.")
        ((eq failure-reason 'too-many-ifs-pre-rewrite)
         "the unrewritten :RHS contains too many IFs for the given args.")
        ((eq failure-reason 'too-many-ifs-post-rewrite)
         "the rewritten :RHS contains too many IFs for the given args.")
        ((eq failure-reason 'rewrite-fncallp)
         "the :REWRITTEN-RHS is judged heuristically unattractive.")
        ((member-eq failure-reason '(linearize-unrewritten-produced-disjunction
                                     linearize-rewritten-produced-disjunction))
         (msg "the ~@0 term generated a disjunction of two conjunctions of ~
               polynomials."
              (if (eq failure-reason 'linearize-rewritten-produced-disjunction)
                  'rewritten
                'unrewritten)))
        ((eq failure-reason 'linear-possible-loop)
         "the rewritten term was judged to have the potential to cause a loop ~
          related to linear arithmetic.")
        ((and (consp failure-reason)
              (integerp (car failure-reason)))
         (let ((n (car failure-reason)))
           (case
             (cdr failure-reason)
             (time-out (msg "we ran out of time while processing :HYP ~x0."
                            n))
             (ancestors (msg ":HYP ~x0 is judged more complicated than its ~
                              ancestors (type :ANCESTORS to see the ancestors ~
                              and :PATH to see how we got to this point)."
                             n))
             (known-nil (msg ":HYP ~x0 is known nil by type-set."
                             n))
             (otherwise
              (cond
               ((eq (cadr failure-reason) 'free-vars)
                (mv-let
                 (failures-remaining failure-reason elided-p)
                 (if free-vars-display-limit
                     (limit-failure-reason free-vars-display-limit
                                           failure-reason
                                           nil)
                   (mv nil failure-reason nil))
                 (declare (ignore failures-remaining))
                 (cond
                  ((eq (caddr failure-reason) 'hyp-vars)
                   (msg ":HYP ~x0 contains free variable~#1~[~/s~] ~&1, for ~
                         which no suitable ~#1~[binding was~/bindings were~] ~
                         found."
                        n
                        (set-difference-equal (cdddr failure-reason)
                                              (strip-cars unify-subst))))
                  ((eq (caddr failure-reason) 'elided)
                   (msg ":HYP ~x0 contains free variables (further reasons ~
                         elided, as noted above)."
                        n))
                  (t
                   (msg
                    "~@0~@1"
                    (if (eql level 1)
                        (msg ":HYP ~x0 ~@1.  The following display summarizes ~
                              the attempts to relieve hypotheses by binding ~
                              free variables; see :DOC free-variables.~|~@2~%"
                             n
                             (if (let* ((hyp
                                         (nth (1- n)
                                              (get-rule-field
                                               (get-brr-local 'lemma state)
                                               :hyps)))
                                        (evg
                                         (and (ffn-symb-p hyp 'synp)
                                              (quotep (fargn hyp 2))
                                              (unquote (fargn hyp 2)))))
                                   (and evg
                                        (consp evg)
                                        (eq (car evg) 'bind-free)))
                                 (msg "uses ~x0 to produce unsuccessful free ~
                                       variable bindings"
                                      'bind-free)
                               "contains free variables")
                             (if elided-p
                                 (msg
                                  "     Also, if you want to avoid ~
                                     ``reasons elided'' notes below, then ~
                                     evaluate (assign free-vars-display-limit ~
                                     k) for larger k (currently ~x0, default ~
                                     ~x1); then :failure-reason will show the ~
                                     first k or so failure sub-reasons before ~
                                     eliding.  Note that you may want to do ~
                                     this evaluation outside break-rewrite, ~
                                     so that it persists.~|"
                                  free-vars-display-limit
                                  *default-free-vars-display-limit*)
                               ""))
                      "")
                    (tilde-@-failure-reason-free-phrase
                     n
                     (cddr failure-reason)
                     level unify-subst evisc-tuple state))))))
               ((eq (cadr failure-reason) 'backchain-limit)
                (tilde-@-failure-reason-phrase1-backchain-limit
                 n
                 (cddr failure-reason)
                 state
                 evisc-tuple))
               ((eq (cadr failure-reason) 'rewrote-to)
                (msg ":HYP ~x0 rewrote to ~X12.~@3"
                     n
                     (cddr failure-reason)
                     evisc-tuple
                     (if (equal (cddr failure-reason) *nil*)
                         "  (See :DOC tail-biting if this surprises you.)"
                       "")))
               ((member-eq (cadr failure-reason) '(syntaxp
                                                   syntaxp-extended
                                                   bind-free
                                                   bind-free-extended))
                (let ((synp-fn (case (cadr failure-reason)
                                 (syntaxp-extended 'syntaxp)
                                 (bind-free-extended 'bind-free)
                                 (otherwise (cadr failure-reason)))))
                  (cond ((caddr failure-reason)
                         (msg "the evaluation of the ~x0 test in :HYP ~x1 ~
                               produced the error ``~@2''"
                              synp-fn
                              n
                              (cadddr failure-reason)))
                        (t (msg "the ~x0 test in :HYP ~x1 evaluated to NIL."
                                synp-fn
                                n)))))
               (t (er hard 'tilde-@-failure-reason-phrase1
                      "Unrecognized failure reason, ~x0."
                      failure-reason)))))))
        ((and (consp failure-reason)
              (eq (car failure-reason) 'normalizer-failed-to-evaluate))
         (msg "the normalizer, ~x0, simplified to a non-constant, ~x1."
              (cadr failure-reason)
              (caddr failure-reason)))
        ((and (consp failure-reason)
              (eq (car failure-reason) 'normalizer-returned-same-constant))
         (msg "the normalizer, ~x0, simplified to the same constant, ~x1."
              (cadr failure-reason)
              (caddr failure-reason)))
        ((and (consp failure-reason)
              (eq (car failure-reason) 'cached))
         (msg "~@0~|*NOTE*: This failure was cached earlier.  Use the hint ~
               :RW-CACHE-STATE ~x1 to disable failure caching."
              (tilde-@-failure-reason-phrase1
               (cdr failure-reason)
               level unify-subst evisc-tuple free-vars-display-limit state)
              nil))
        (t (er hard 'tilde-@-failure-reason-phrase1
               "Unrecognized failure reason, ~x0."
               failure-reason))))
)

(defun tilde-@-failure-reason-phrase (failure-reason level unify-subst
                                                     evisc-tuple
                                                     free-vars-display-limit
                                                     state)

; In relieve-hyps1 we store a 'free-vars failure reason in which we formerly
; reversed a "failure-reason-lst", which is really an alist mapping extended
; unify-substs to failure reasons.  Now, we save consing by delaying such
; reversal until the relatively rare times that we are ready to display the
; failure reason.

  (tilde-@-failure-reason-phrase1 (fix-free-failure-reason failure-reason)
                                  level unify-subst evisc-tuple
                                  free-vars-display-limit state))

(defun brr-result (state)
  (let ((result (get-brr-local 'brr-result state)))
    (cond ((eq (record-type (get-brr-local 'lemma state)) 'linear-lemma)
           (show-poly-lst result))
          (t result))))

(defconst *brkpt1-aliases*

; Keep this in sync (as appropriate) with *brkpt2-aliases*.

; Note: proceed-from-brkpt1 used below is not yet defined but it doesn't matter
; since this is just a quoted constant.  Proceed-from-brkpt1 has to check that
; the indicated runes are monitorable, which we can't define until we've
; introduced certain certain history management utilities.

  (flet ((not-yet-evaled-fn ()
                            `(lambda nil
                               (prog2$
                                (cw "~F0 has not yet been :EVALed.~%"
                                    (get-rule-field (get-brr-local 'lemma state)
                                                    :rune))
                                (value :invisible))))
         (lhs-fn (plusp)
                 `(lambda nil
                    (let ((val (get-rule-field (get-brr-local 'lemma state)
                                               :lhs)))
                      (cond
                       ((eq val :get-rule-field-none) ; linear lemma
                        (er soft :LHS
                            ":LHS is only legal for a :REWRITE rule."))
                       (t
                        (prog2$
                         (cw "~X01~|" val ,(if plusp
                                               nil
                                               '(brr-evisc-tuple state)))
                         (value :invisible)))))))
         (max-term-fn (plusp)
                      `(lambda nil
                         (let ((val (get-rule-field (get-brr-local 'lemma state)
                                                    :max-term)))
                           (cond
                            ((eq val :get-rule-field-none) ; rewrite rule
                             (er soft :MAX-TERM
                                 ":MAX-TERM is only legal for a :LINEAR rule."))
                            (t
                             (prog2$
                              (cw "~X01~|" val ,(if plusp
                                                    nil
                                                    '(brr-evisc-tuple state)))
                              (value :invisible)))))))
         (ancestors-fn (plusp)
                       `(lambda nil
                          (prog2$
                           (cw "~@0" (show-ancestors-stack-msg
                                      state
                                      ,(if plusp
                                           nil
                                         '(brr-evisc-tuple state))))
                           (value :invisible))))
         (btm-fn (plusp)
                 `(lambda nil
                    (prog2$
                     (let* ((whs (f-get-global 'wormhole-status state))
                            (gstack (access brr-status whs :brr-gstack)))
                       (cw-gframe (length gstack) nil (car gstack)
                                  ,(if plusp
                                       nil
                                     '(brr-evisc-tuple state))))
                     (value :invisible))))
         (frame-fn (plusp)
                   `(lambda (n)
                      (let* ((whs (f-get-global 'wormhole-status state))
                             (rgstack
                              (reverse (access brr-status whs :brr-gstack))))
                        (cond
                         ((and (integerp n)
                               (>= n 1)
                               (<= n (length rgstack)))
                          (prog2$
                           (cw-gframe n
                                      (if (= n 1)
                                          nil
                                        (access gframe (nth (- n 2) rgstack)
                                                :sys-fn))
                                      (nth (- n 1) rgstack)
                                      ,(if plusp
                                           nil
                                         '(brr-evisc-tuple state)))
                           (value :invisible)))
                         (t (er soft :frame
                                ":FRAME must be given an integer argument ~
                                 between 1 and ~x0."
                                (length rgstack)))))))
         (initial-ttree-fn (plusp)
                           `(lambda nil
                              (let ((lemma (get-brr-local 'lemma state)))
                                (cond
                                 ((eq (record-type lemma) 'linear-lemma)
                                  (er soft :INITIAL-TTREE
                                      ":INITIAL-TTREE is not legal for a ~
                                       :LINEAR rule."))
                                 (t (prog2$
                                     (cw "~X01~|"
                                         (get-brr-local 'initial-ttree state)
                                         ,(if plusp
                                              nil
                                            '(brr-evisc-tuple state)))
                                     (value :invisible)))))))
         (path-fn (plusp)
                  `(lambda nil
                     (prog2$ (cw-gstack :evisc-tuple
                                        ,(if plusp
                                             nil
                                           '(brr-evisc-tuple state)))
                             (value :invisible))))
         (pot-list-fn (plusp)
                      `(lambda nil
                         (let ((pot-list (get-brr-local 'pot-list state)))
                           (prog2$ (if pot-list
                                       (prog2$
                                        (cw "~%Display of linear pot-list:~|")
                                        (print-pot-lst
                                         pot-list
                                         ,(if plusp
                                              nil
                                            '(brr-evisc-tuple state))))
                                     (cw "~%The linear pot-list is empty.~|"))
                                   (value :invisible)))))
         (target-fn (plusp)
                    `(lambda nil
                       (prog2$ (cw "~X01~|"
                                   (get-brr-local 'target state)
                                   ,(if plusp
                                        nil
                                      '(brr-evisc-tuple state)))
                               (value :invisible))))
         (top-fn (plusp)
                 `(lambda nil
                    (prog2$
                     (cw-gframe 1
                                nil
                                (car (reverse
                                      (access brr-status
                                              (f-get-global 'wormhole-status
                                                            state)
                                              :brr-gstack)))
                                ,(if plusp
                                     nil
                                   '(brr-evisc-tuple state)))
                     (value :invisible))))
         (type-alist-fn (plusp)
                        `(lambda nil
                           (prog2$
                            (cw "~%Decoded type-alist:~%")
                            (prog2$
                             (print-type-alist-segments
                              (type-alist-segments
                               (get-brr-local 'type-alist state)
                               nil)
                              (w state)
                              ,(if plusp
                                   nil
                                 '(brr-evisc-tuple state)))
                             (prog2$
                              (cw "~%==========~%Use ~x0 to see actual ~
                                   type-alist.~%"
                                  '(get-brr-local 'type-alist state))
                              (value :invisible))))))
         (geneqv-fn (plusp)
                    `(lambda nil
                       (prog2$
                        (cw "~%Geneqv:~%~Y01"
                            (show-geneqv (get-brr-local 'geneqv state)
                                         'non-prims)
                            ,(if plusp
                                 nil
                                 '(brr-evisc-tuple state)))
                        (prog2$
                         (cw "~%==========~%Use ~x0 to see actual geneqv ~
                               data structure.~%"
                             '(get-brr-local 'geneqv state))
                         (value :invisible)))))
         (unify-subst-fn (plusp)
                         `(lambda nil
                            (prog2$
                             (cw "~*0"
                                 (tilde-*-alist-phrase
                                  (get-brr-local 'unify-subst state)
                                  ,(if plusp
                                       nil
                                     '(brr-evisc-tuple state))
                                  5))
                             (value :invisible)))))
    `(
; If you add commands, change the documentation for brr-commands.
      (:ancestors
       0 ,(ancestors-fn nil))
      (:ancestors+
       0 ,(ancestors-fn t))
      (:btm
       0 ,(btm-fn nil))
      (:btm+
       0 ,(btm-fn t))
      (:eval
       0 (lambda nil
           (proceed-from-brkpt1 'break t :eval state)))
      (:eval!
       0 (lambda nil
           (proceed-from-brkpt1 'break :none :eval! state)))
      (:eval$
       1 (lambda (runes)
           (proceed-from-brkpt1 'break runes :eval$ state)))
      (:explain-near-miss
       0 (lambda nil
           (explain-near-miss1
            (get-brr-local 'target state)
            30 ; an object containing >= 30 conses is ``large''
            (evisc-tuple 10 20 nil nil)
            state)))
      (:explain-near-miss+
       0 (lambda nil
           (explain-near-miss1
            (get-brr-local 'target state)
            nil ; everything is ``large''
            nil ; no evisceration
            state)))
      (:failure-reason
       0 ,(not-yet-evaled-fn))
      (:failure-reason+
       0 ,(not-yet-evaled-fn))
      (:final-ttree
       0 ,(not-yet-evaled-fn))
      (:final-ttree+
       0 ,(not-yet-evaled-fn))
      (:frame
       1 ,(frame-fn nil))
      (:frame+
       1 ,(frame-fn t))
      (:go
       0 (lambda nil
           (proceed-from-brkpt1 'print t :go state)))
      (:go!
       0 (lambda nil
           (proceed-from-brkpt1 'print :none :go! state)))
      (:go$
       1 (lambda (runes)
           (proceed-from-brkpt1 'print runes :go$ state)))
      (:help
       0 (lambda nil
           (doc 'brr-commands)))
      (:hyp
       1 (lambda (n)
           (cond
            ((and (integerp n)
                  (>= n 1)
                  (<= n (length (get-rule-field (get-brr-local 'lemma state)
                                                :hyps))))
             (prog2$ (cw "~X01~|"
                         (nth (1- n)
                              (get-rule-field (get-brr-local 'lemma state)
                                              :hyps))
                         nil)
                     (value :invisible)))
            (t (er soft :HYP
                   ":HYP must be given an integer argument between 1 and ~x0."
                   (length (get-rule-field (get-brr-local 'lemma state)
                                           :hyps)))))))
      (:hyps
       0 (lambda nil
           (prog2$
            (cw "~x0~|"
                (get-rule-field (get-brr-local 'lemma state)
                                :hyps))
            (value :invisible))))
      (:initial-ttree
       0 ,(initial-ttree-fn nil))
      (:initial-ttree+
       0 ,(initial-ttree-fn t))
      (:lhs
       0 ,(lhs-fn nil))
      (:lhs+
       0 ,(lhs-fn t))
      (:max-term
       0 ,(max-term-fn nil))
      (:max-term+
       0 ,(max-term-fn t))
      (:ok
       0 (lambda nil
           (proceed-from-brkpt1 'silent t :ok state)))
      (:ok!
       0 (lambda nil
           (proceed-from-brkpt1 'silent :none :ok! state)))
      (:ok$
       1 (lambda (runes)
           (proceed-from-brkpt1 'silent runes :ok$ state)))
      (:path
       0 ,(path-fn nil))
      (:path+
       0 ,(path-fn t))
      (:poly-list
       0 ,(not-yet-evaled-fn))
      (:poly-list+
       0 ,(not-yet-evaled-fn))
      (:pot-list
       0 ,(pot-list-fn nil))
      (:pot-list+
       0 ,(pot-list-fn t))
      (:q
       0 (lambda nil
           (prog2$ (cw "Proceed with some flavor of :ok, :go, or :eval, or ~
                        use :a! to abort.~%")
                   (value :invisible))))
      (:rewritten-rhs
       0 ,(not-yet-evaled-fn))
      (:rewritten-rhs+
       0 ,(not-yet-evaled-fn))
      (:rhs
       0 (lambda nil
           (let ((val (get-rule-field (get-brr-local 'lemma state)
                                      :rhs)))
             (cond
              ((eq val :get-rule-field-none) ; linear lemma
               (er soft :RHS
                   ":RHS is only legal for a :REWRITE rule."))
              (t
               (prog2$
                (cw "~x0~|" val)
                (value :invisible)))))))
      (:standard-help 0 help)
      (:target
       0 ,(target-fn nil))
      (:target+
       0 ,(target-fn t))
      (:top
       0 ,(top-fn nil))
      (:top+
       0 ,(top-fn t))
      (:type-alist
       0 ,(type-alist-fn nil))
      (:type-alist+
       0 ,(type-alist-fn t))
      (:geneqv
       0 ,(geneqv-fn nil))
      (:geneqv+
       0 ,(geneqv-fn t))
      (:unify-subst
       0 ,(unify-subst-fn nil))
      (:unify-subst+
       0 ,(unify-subst-fn t))
      (:wonp
       0 ,(not-yet-evaled-fn)))))

(defconst *brkpt2-aliases*

; Keep this in sync (as appropriate) with *brkpt1-aliases*.

; Note: exit-brr used below is not yet defined but it doesn't matter since
; this is just a quoted constant.

  (flet ((already-evaled-fn ()
                            '(lambda nil
                               (prog2$ (cw "You already have run some flavor ~
                                            of :eval.~%")
                                       (value :invisible))))
         (lhs-fn (plusp)
                 `(lambda nil
                    (let ((val (get-rule-field (get-brr-local 'lemma state)
                                               :lhs)))
                      (cond
                       ((eq val :get-rule-field-none) ; linear lemma
                        (er soft :LHS
                            ":LHS is only legal for a :REWRITE rule."))
                       (t
                        (prog2$
                         (cw "~X01~|" val ,(if plusp
                                               nil
                                               '(brr-evisc-tuple state)))
                         (value :invisible)))))))
         (max-term-fn (plusp)
                      `(lambda nil
                         (let ((val (get-rule-field (get-brr-local 'lemma state)
                                                    :max-term)))
                           (cond
                            ((eq val :get-rule-field-none) ; rewrite rule
                             (er soft :MAX-TERM
                                 ":MAX-TERM is only legal for a :LINEAR rule."))
                            (t
                             (prog2$
                              (cw "~X01~|" val ,(if plusp
                                                    nil
                                                    '(brr-evisc-tuple state)))
                              (value :invisible)))))))
         (ancestors-fn (plusp)
                       `(lambda nil
                          (prog2$
                           (cw "~@0" (show-ancestors-stack-msg
                                      state
                                      ,(if plusp
                                           nil
                                         '(brr-evisc-tuple state))))
                           (value :invisible))))
         (btm-fn (plusp)
                 `(lambda nil
                    (prog2$
                     (let* ((whs (f-get-global 'wormhole-status state))
                            (gstack (access brr-status whs :brr-gstack)))
                       (cw-gframe (length gstack) nil (car gstack)
                                  ,(if plusp
                                       nil
                                     '(brr-evisc-tuple state))))
                     (value :invisible))))
         (failure-reason-fn (plusp)
                            `(lambda nil
                               (prog2$
                                (if (get-brr-local 'wonp state)
                                    (cw "? ~F0 succeeded.~%"
                                        (get-rule-field (get-brr-local 'lemma
                                                                       state)
                                                        :rune))
                                  (cw "~@0~|"
                                      (tilde-@-failure-reason-phrase
                                       (get-brr-local 'failure-reason state)
                                       1
                                       (get-brr-local 'unify-subst state)
                                       ,(if plusp
                                            nil
                                          '(brr-evisc-tuple state))
                                       (free-vars-display-limit state)
                                       state)))
                                (value :invisible))))
         (final-ttree-fn (plusp)
                         `(lambda nil
                            (let ((lemma (get-brr-local 'lemma state)))
                              (cond
                               ((eq (record-type lemma) 'linear-lemma)
                                (er soft :FINAL-TTREE
                                    ":FINAL-TTREE is not legal for a :LINEAR ~
                                     rule."))
                               (t (prog2$
                                   (cw "~X01~|"
                                       (get-brr-local 'final-ttree state)
                                       ,(if plusp
                                            nil
                                          '(brr-evisc-tuple state)))
                                   (value :invisible)))))))
         (frame-fn (plusp)
                   `(lambda (n)
                      (let* ((whs (f-get-global 'wormhole-status state))
                             (rgstack (reverse
                                       (access brr-status whs :brr-gstack))))
                        (cond
                         ((and (integerp n)
                               (>= n 1)
                               (<= n (length rgstack)))
                          (prog2$
                           (cw-gframe n
                                      (if (= n 1)
                                          nil
                                          (access gframe (nth (- n 2) rgstack)
                                                  :sys-fn))
                                      (nth (- n 1) rgstack)
                                      ,(if plusp
                                           nil
                                           '(brr-evisc-tuple state)))
                           (value :invisible)))
                         (t (er soft :frame
                                ":FRAME must be given an integer argument ~
                                 between 1 and ~x0."
                                (length rgstack)))))))
         (initial-ttree-fn (plusp)
                           `(lambda nil
                              (let ((lemma (get-brr-local 'lemma state)))
                                (cond
                                 ((eq (record-type lemma) 'linear-lemma)
                                  (er soft :INITIAL-TTREE
                                      ":INITIAL-TTREE is not legal for a ~
                                       :LINEAR rule."))
                                 (t (prog2$
                                     (cw "~X01~|"
                                         (get-brr-local 'initial-ttree state)
                                         ,(if plusp
                                              nil
                                            '(brr-evisc-tuple state)))
                                     (value :invisible)))))))
         (path-fn (plusp)
                  `(lambda nil
                     (prog2$ (cw-gstack :evisc-tuple
                                        ,(if plusp
                                             nil
                                           '(brr-evisc-tuple state)))
                             (value :invisible))))
         (poly-list-fn (plusp)
                       `(lambda nil
                          (let ((lemma (get-brr-local 'lemma state)))
                            (cond
                             ((eq (record-type lemma) 'linear-lemma)
                              (prog2$
                               (cond
                                ((get-brr-local 'wonp state)
                                 (cw "~X01~|"
                                     (brr-result state)
                                     ,(if plusp
                                          nil
                                        '(brr-evisc-tuple state))))
                                (t (cw "? ~F0 failed.~%"
                                       (get-rule-field lemma :rune))))
                               (value :invisible)))
                             (t
                              (er soft :POLY-LIST
                                  ":POLY-LIST is only legal for a :LINEAR ~
                                   rule."))))))
         (pot-list-fn (plusp)
                      `(lambda nil
                         (let ((pot-list (get-brr-local 'pot-list state)))
                           (prog2$ (if pot-list
                                       (prog2$
                                        (cw "~%Display of linear pot-list:~|")
                                        (print-pot-lst
                                         pot-list
                                         ,(if plusp
                                              nil
                                            '(brr-evisc-tuple state))))
                                     (cw "~%The linear pot-list is empty.~|"))
                                   (value :invisible)))))
         (rewritten-rhs-fn (plusp)
                           `(lambda nil
                              (let ((lemma (get-brr-local 'lemma state)))
                                (cond
                                 ((eq (record-type lemma) 'rewrite-rule)
                                  (prog2$
                                   (cond
                                    ((or (get-brr-local 'wonp state)
                                         (member-eq (get-brr-local
                                                     'failure-reason state)
                                                    '(too-many-ifs
                                                      rewrite-fncallp)))
                                     (cw "~X01~|"
                                         (get-brr-local 'brr-result state)
                                         ,(if plusp
                                              nil
                                            '(brr-evisc-tuple state))))
                                    (t (cw "? ~F0 failed.~%"
                                           (get-rule-field lemma :rune))))
                                   (value :invisible)))
                                 (t
                                  (er soft :REWRITTEN-RHS
                                      ":REWRITTEN-RHS is only legal for a ~
                                       :REWRITE rule."))))))
         (target-fn (plusp)
                    `(lambda nil
                       (prog2$ (cw "~X01~|"
                                   (get-brr-local 'target state)
                                   ,(if plusp
                                        nil
                                      '(brr-evisc-tuple state)))
                               (value :invisible))))
         (top-fn (plusp)
                 `(lambda nil
                    (prog2$
                     (cw-gframe 1
                                nil
                                (car (reverse
                                      (access brr-status
                                              (f-get-global 'wormhole-status
                                                            state)
                                              :brr-gstack)))
                                ,(if plusp
                                     nil
                                   '(brr-evisc-tuple state)))
                     (value :invisible))))
         (type-alist-fn (plusp)
                        `(lambda nil
                           (prog2$
                            (cw "~%Decoded type-alist:~%")
                            (prog2$
                             (print-type-alist-segments
                              (type-alist-segments
                               (get-brr-local 'type-alist state)
                               nil)
                              (w state)
                              ,(if plusp
                                   nil
                                 '(brr-evisc-tuple state)))
                             (prog2$
                              (cw "~%==========~%Use ~x0 to see actual ~
                                   type-alist.~%"
                                  '(get-brr-local 'type-alist state))
                              (value :invisible))))))
         (geneqv-fn (plusp)
                    `(lambda nil
                       (prog2$
                        (cw "~%Geneqv:~%~Y01"
                            (show-geneqv (get-brr-local 'geneqv state)
                                         'non-prims)
                            ,(if plusp
                                 nil
                                 '(brr-evisc-tuple state)))
                        (prog2$
                         (cw "~%==========~%Use ~x0 to see actual geneqv ~
                               data structure.~%"
                             '(get-brr-local 'geneqv state))
                         (value :invisible)))))
         (unify-subst-fn (plusp)
                         `(lambda nil
                            (prog2$
                             (cw "~*0"
                                 (tilde-*-alist-phrase
                                  (get-brr-local 'unify-subst state)
                                  ,(if plusp
                                       nil
                                     '(brr-evisc-tuple state))
                                  5))
                             (value :invisible)))))
    `(
; If you add commands, change the documentation for brr-commands.
      (:ancestors
       0 ,(ancestors-fn nil))
      (:ancestors+
       0 ,(ancestors-fn t))
      (:btm
       0 ,(btm-fn nil))
      (:btm+
       0 ,(btm-fn t))
      (:eval
       0 ,(already-evaled-fn))
      (:eval!
       0 ,(already-evaled-fn))
      (:eval$
       1 (lambda (runes)
           (prog2$ runes ; avoid issues of ignored variable
                   ,(already-evaled-fn))))
      (:explain-near-miss
       0 (lambda nil
           (explain-near-miss1
            (get-brr-local 'target state)
            30 ; an object containing >= 30 conses is ``large''
            (evisc-tuple 10 20 nil nil)
            state)))
      (:explain-near-miss+
       0 (lambda nil
           (explain-near-miss1
            (get-brr-local 'target state)
            nil ; everything is ``large''
            nil ; no evisceration
            state)))
      (:failure-reason
       0 ,(failure-reason-fn nil))
      (:failure-reason+
       0 ,(failure-reason-fn t))
      (:final-ttree
       0 ,(final-ttree-fn nil))
      (:final-ttree+
       0 ,(final-ttree-fn t))
      (:frame
       1 ,(frame-fn nil))
      (:frame+
       1 ,(frame-fn t))
      (:go
       0 (lambda nil

; Like :ok, :man.

           (exit-brr state)))
      (:go!
       0 (lambda nil
           (exit-brr state)))
      (:go$
       1 (lambda (runes)
           (prog2$ runes ; avoid issues of ignored variable
                   (exit-brr state))))
      (:help
       0 (lambda nil
           (doc 'brr-commands)))
      (:hyp
       1 (lambda (n)
           (cond
            ((and (integerp n)
                  (>= n 1)
                  (<= n (length (get-rule-field (get-brr-local 'lemma state)
                                                :hyps))))
             (prog2$ (cw "~X01~|"
                         (nth (1- n)
                              (get-rule-field (get-brr-local 'lemma state)
                                              :hyps))
                         nil)
                     (value :invisible)))
            (t (er soft :HYP
                   ":HYP must be given an integer argument between 1 and ~x0."
                   (length (get-rule-field (get-brr-local 'lemma state)
                                           :hyps)))))))
      (:hyps
       0 (lambda nil
           (prog2$
            (cw "~x0~|"
                (get-rule-field (get-brr-local 'lemma state)
                                :hyps))
            (value :invisible))))
      (:initial-ttree
       0 ,(initial-ttree-fn nil))
      (:initial-ttree+
       0 ,(initial-ttree-fn t))
      (:lhs
       0 ,(lhs-fn nil))
      (:lhs+
       0 ,(lhs-fn t))
      (:max-term
       0 ,(max-term-fn nil))
      (:max-term+
       0 ,(max-term-fn t))
      (:ok
       0 (lambda nil
           (exit-brr state)))
      (:ok!
       0 (lambda nil
           (exit-brr state)))
      (:ok$
       1 (lambda (runes)
           (prog2$ runes ; avoid issues of ignored variable
                   (exit-brr state))))
      (:path
       0 ,(path-fn nil))
      (:path+
       0 ,(path-fn t))
      (:poly-list
       0 ,(poly-list-fn nil))
      (:poly-list+
       0 ,(poly-list-fn t))
      (:pot-list
       0 ,(pot-list-fn nil))
      (:pot-list+
       0 ,(pot-list-fn t))
      (:q
       0 (lambda nil
           (prog2$ (cw "Proceed with some flavor of :ok, :go, or :eval, ~
                       or use :a! to abort.~%")
                   (value :invisible))))
      (:rewritten-rhs
       0 ,(rewritten-rhs-fn nil))
      (:rewritten-rhs+
       0 ,(rewritten-rhs-fn t))
      (:rhs
       0 (lambda nil
           (let ((val (get-rule-field (get-brr-local 'lemma state)
                                      :rhs)))
             (cond
              ((eq val :get-rule-field-none) ; linear lemma
               (er soft :RHS
                   ":RHS is only legal for a :REWRITE rule."))
              (t
               (prog2$
                (cw "~x0~|" val)
                (value :invisible)))))))
      (:standard-help 0 help)
      (:target
       0 ,(target-fn nil))
      (:target+
       0 ,(target-fn t))
      (:top
       0 ,(top-fn nil))
      (:top+
       0 ,(top-fn t))
      (:type-alist
       0 ,(type-alist-fn nil))
      (:type-alist+
       0 ,(type-alist-fn t))
      (:geneqv
       0 ,(geneqv-fn nil))
      (:geneqv+
       0 ,(geneqv-fn t))
      (:unify-subst
       0 ,(unify-subst-fn nil))
      (:unify-subst+
       0 ,(unify-subst-fn t))
      (:wonp
       0 (lambda nil
           (prog2$
            (if (get-brr-local 'wonp state)
                (cw "? ~F0 succeeded.~%"
                    (get-rule-field (get-brr-local 'lemma state) :rune))
              (cw "? ~F0 failed.~%"
                  (get-rule-field (get-brr-local 'lemma state) :rune)))
            (value :invisible)))))))

(defrec brr-data-1

; Warning: Keep this in sync with the discussion in the ``Low-level details
; (optional)'' section of :DOC with-brr-data.

; This record stores information at calls of brkpt1.

  (((lemma . target) . (unify-subst type-alist . geneqv))
   .
   ((pot-list . ancestors) . (rcnst initial-ttree . gstack)))
  nil)

(defrec brr-data-2

; Warning: Keep this in sync with the discussion in the ``Low-level details
; (optional)'' section of :DOC with-brr-data.

; This record stores information at calls of brkpt2.

  ((failure-reason unify-subst . brr-result)
   .
   (rcnst final-ttree . gstack))
  nil)

(defrec brr-data

; Warning: Keep this in sync with the discussion in the ``Low-level details
; (optional)'' section of :DOC with-brr-data.

; This is a recursive record: pre and post are brr-data-1 and brr-data-2
; records, respectively, and completed is a list of brr-data records, all as
; follows.

; For a given call C1 of brkpt1, pre is a brr-data-1 record from that call,
; post is a brr-data-2 record from the matching (and subsequent) call C2 of
; brkpt2, and completed is a list of brr-data records similarly constructed
; from matching brkpt1 and brkpt2 calls at the top level between calls C1 and
; C2.

  (pre post . completed)
  nil)

(mutual-recursion

(defun brr-data-p (completed-p x)

; The :post of x is a record when completed-p is t and is nil otherwise.  Such
; records are called "complete" and "incomplete", respectively.

  (declare (xargs :guard t
                  :measure (acl2-count x)))
  (and (weak-brr-data-p x)
       (weak-brr-data-1-p (access brr-data x :pre))
       (if completed-p
           (weak-brr-data-2-p (access brr-data x :post))
         (null (access brr-data x :post)))
       (brr-data-listp t (access brr-data x :completed))))

(defun brr-data-listp (completed-p lst)
  (declare (xargs :guard t
                  :measure (acl2-count lst)))
  (cond ((atom lst) (null lst))
        ((brr-data-p completed-p (car lst))
         (brr-data-listp completed-p (cdr lst)))
        (t nil)))
)

(defproxy brkpt1-brr-data-entry (* * * state)

; The formals are those that are reasonable to query in both brkpt1 and its
; balancing brkpt2, so that the calls truly balance.  Perhaps unify-subst and
; type-alist could be added, but since they can change from brkpt1 to brkpt2,
; we omit those.

  => *)

(defproxy brkpt2-brr-data-entry (* * * state)

; See comments in brkpt1-brr-data-entry.

  => *)

(defstub update-brr-data-1 (lemma target unify-subst type-alist geneqv
                                  ancestors initial-ttree gstack rcnst pot-lst
                                  whs-data)

; This is called in brkpt1 to update the wormhole-data for the brr-data
; wormhole.

  t)

(defstub update-brr-data-2 (wonp failure-reason unify-subst gstack brr-result
                                 final-ttree rcnst ancestors whs-data)

; This is called in brkpt2 to update the wormhole-data for the brr-data
; wormhole.

  t)

(defun brkpt1-brr-data-entry-builtin (ancestors gstack rcnst state)

; The -builtin version of brr-data restricts collection to top-level rewriter
; calls (i.e., without ancestors).

  (declare (xargs :stobjs state)
           (ignore gstack rcnst state))
  (null ancestors))

(defun brkpt2-brr-data-entry-builtin (ancestors gstack rcnst state)

; The -builtin version of brr-data restricts collection to top-level rewriter
; calls (i.e., without ancestors).

  (declare (xargs :stobjs state)
           (ignore gstack rcnst state))
  (null ancestors))

(defun update-brr-data-1-builtin (lemma target unify-subst type-alist geneqv
                                        ancestors initial-ttree gstack rcnst
                                        pot-lst whs-data)

; This function is the default attachment for update-brr-data-1, which brkpt1
; may use to construct brr-data records.  See the description of those records
; in (defrec brr-data ...) for relevant background.

; The arguments other than whs-data are the arguments to brkpt1.  Whs-data is
; the wormhole-data of the current wormhole status for the wormhole named
; brr-data.  It is either nil or of the form (pending . completed), as follows.
; Pending is a list of brr-data records as recognized by (brr-data-listp nil
; pending); we push a new one with each brkpt1 call when tracking with gstackp
; = :brr-data.  Completed is a list of complete brr-data records; i.e.,
; (brr-data-listp t completed) holds.  Pending represents the top-level calls
; of brkpt1 that have not yet been matched with corresponding brkpt2 calls, and
; completed represents the result of "completing" previous such records using
; matching brkpt2 calls: those calls fill in records previously in pending with
; :post fields that are brr-data-2 records, by calling
; update-brr-data-2-builtin.

  (declare (xargs :guard t))
  (let ((ctx 'update-brr-data-1-builtin))
    (cond
     ((listp whs-data)
      (let* ((pending (car whs-data))
             (completed (cdr whs-data)))
        (cons (cons (make brr-data
                          :pre (make brr-data-1
                                     :lemma lemma
                                     :target target
                                     :unify-subst unify-subst
                                     :type-alist type-alist
                                     :geneqv geneqv
                                     :ancestors ancestors
                                     :initial-ttree initial-ttree
                                     :gstack gstack
                                     :rcnst rcnst
                                     :pot-list pot-lst)
                          :post nil
                          :completed nil)
                    pending)
              completed)))
     (t (er hard? ctx
            "Implementation error: Found whs-data not a listp:~|~y0"
            whs-data)))))

(defun update-brr-data-2-builtin (wonp failure-reason unify-subst gstack
                                       brr-result final-ttree rcnst ancestors
                                       whs-data)

; See update-brr-data-1-builtin for a description of that function and this
; function.

  (declare (xargs :guard t)
           (ignore ancestors))
  (let ((ctx 'update-brr-data-2-builtin))
    (cond
     ((listp whs-data)
      (let* ((pending (car whs-data))
             (completed (cdr whs-data)))
        (cond
         ((not (consp pending))
          (er hard? ctx
              "Implementation error: Found bad whs-data ((car pending) not a ~
               cons):~|~y0"
              whs-data))
         ((null wonp) ; pop pending
          (cons (cdr pending)
                completed))
         ((not (weak-brr-data-p (car pending)))
          (er hard? ctx
              "Implementation error: Found bad whs-data ((car pending) not a ~
               brr-data record)):~|~y0"
              whs-data))
         (t
          (let ((x (make brr-data-2
                         :failure-reason failure-reason
                         :unify-subst unify-subst
                         :gstack gstack
                         :brr-result brr-result
                         :final-ttree final-ttree
                         :rcnst rcnst)))
            (cond
             ((consp (cdr pending))
              (cond
               ((not (weak-brr-data-p (cadr pending)))
                (er hard? ctx
                    "Implementation error: Found whs-data (bad (cadr ~
                     pending)):~|~y0"
                    whs-data))
               (t

; Pop pending, folding (car pending) into the :completed field of (cadr
; pending), filling in the :post field of (car pending).  There is no change to
; completed.

                (cons (cons (change brr-data (cadr pending)
                                    :completed
                                    (cons (change brr-data (car pending)
                                                  :post x)
                                          (access brr-data (cadr pending)
                                                  :completed)))
                            (cddr pending))
                      completed))))
             (t

; Pop pending, leaving an empty stack.  So, we set the :post field of (car
; pending) to x and then push the resulting record onto completed.

              (cons nil
                    (cons (change brr-data (car pending)
                                  :post x)
                          completed)))))))))
     (t (er hard? ctx
            "Implementation error: Found whs-data not a listp:~|~y0"
            whs-data)))))

(defmacro set-brr-data-attachments (&optional (suffix 'builtin))
  (declare (xargs :guard (or (symbolp suffix)
                             (stringp suffix))))
  (let* ((suffix (cond ((symbolp suffix)
                        (symbol-name suffix))
                       (t suffix)))
         (suffix (concatenate 'string "-" suffix))
         (update-brr-data-1-suffix (add-suffix 'update-brr-data-1 suffix))
         (update-brr-data-2-suffix (add-suffix 'update-brr-data-2 suffix))
         (brkpt1-bde-suffix (add-suffix 'brkpt1-brr-data-entry suffix))
         (brkpt2-bde-suffix (add-suffix 'brkpt2-brr-data-entry suffix)))
    `(with-output :off :all
       (progn (defattach (update-brr-data-1 ,update-brr-data-1-suffix)
                :system-ok t)
              (defattach (update-brr-data-2 ,update-brr-data-2-suffix)
                :system-ok t)
              (defattach (brkpt1-brr-data-entry ,brkpt1-bde-suffix)
                :system-ok t)
              (defattach (brkpt2-brr-data-entry ,brkpt2-bde-suffix)
                :system-ok t)))))

(defun set-wormhole-data-fast (whs data)

; This function is like set-wormhole-data, except that it avoids a potentially
; expensive equality test with the trade-off that here, we always cons.

  (declare (xargs :guard t))
  (if (consp whs)
      (cons (car whs) data)
    (cons :enter data)))

(defun brr-data-mirror (lst acc)

; Lst is a list of brr-data records.  We accumulate the reverse of lst into
; acc, similarly reversing all :completed fields within lst; see brr-data-lst.
; The goal is for a left-to-right depth-first tree traversal to respect
; suitably the order present in the proof attempt.

  (declare (xargs :guard (and (brr-data-listp t lst)
                              (true-listp acc))))
  (cond ((endp lst)
         acc)
        (t (let* ((x1 (car lst))
                  (c (access brr-data x1 :completed))
                  (x2 (if (null c)
                          x1
                        (change brr-data x1
                                :completed (brr-data-mirror c nil)))))
             (brr-data-mirror (cdr lst)
                              (cons x2 acc))))))

(defun brr-data-lst (state)

; The top-level rewrites have been accumulated into the wormhole by pushing
; onto a stack.  We reverse that stack and the :completed entries within it to
; respect the original order of rewrites, as a convenience to the user.

  (declare (xargs :stobjs state))
  (er-let* ((status (get-persistent-whs 'brr-data state)))
    (value (let ((data (wormhole-data status)))
             (cond ((consp data)

; Data is nil or of the form (brr-data-list . brr-data-list).  We expect the
; car to be nil unless the proof was interrupted.

                    (ec-call (brr-data-mirror (cdr data) nil)))

; If data is not a cons then we haven't collected any data or we have run
; (clear-brr-data-lst).

                   (t nil))))))

(defun clear-brr-data-lst ()
  (declare (xargs :guard t))
  (wormhole-eval
   'brr-data
   '(lambda (whs)
      (set-wormhole-data-fast whs nil))
   nil))

(defmacro with-brr-data (form &key
                              (global-var 'brr-data-lst)
                              (brr-data-returned 'nil))

; Form, which needs to return a value-triple, is evaluated to obtain a result
; (mv erp val state), which is the error triple returned by the with-brr-data
; call unless brr-data-returned is true, in which case (mv erp lst state) is
; returned, where lst is the resulting list of brr-data records.  See :DOC
; with-brr-data.

  (let* ((form1 `(state-global-let* ((gstackp :brr-data))
                                    ,form))
         (form2 (if global-var
                    `(mv-let (erp val state)
                       ,form1
                       (er-progn (set-brr-data-lst ,global-var)
                                 (mv erp val state)))
                  form1))
         (form3 (if brr-data-returned
                    `(mv-let (erp val state)
                       ,form2
                       (declare (ignore val))
                       ,(if global-var
                            `(mv erp (@ ,global-var) state)
                          `(er-let* ((x (brr-data-lst state)))
                             (mv erp (reverse x) state))))
                  form2))
         (form4 `(cond
                  #+acl2-par
                  ((f-get-global 'waterfall-parallelism state)
                   (er soft 'with-brr-data
                       "~x0 is not supported in ACL2(p) with waterfall ~
                        parallelism on.  See :DOC ~
                        unsupported-waterfall-parallelism-features."
                       'with-brr-data))
                  (t ,form3))))
    `(prog2$ (clear-brr-data-lst)
             ,form4)))

(defun addr^p (addr)
  (declare (xargs :guard t))
  (cond ((atom addr) (eq addr nil))
        ((eq (car addr) '^) nil)
        ((posp (car addr))
         (if (and (consp (cdr addr))
                  (eq (cadr addr) '^))
             (eq (cddr addr) nil)
             (addr^p (cdr addr))))
        (t nil)))

(defun safe-nth (n x)
; (thm (equal (safe-nth n x) (nth n x)))
  (declare (xargs :guard t))
  (if (natp n)
      (if (consp x)
          (if (= n 0)
              (car x)
              (safe-nth (- n 1) (cdr x)))
          nil)
      (if (consp x)
          (car x)
          nil)))

(defun safe-nthcdr (n x)
; (thm (equal (safe-nthcdr n x) (nthcdr n x)))
  (declare (xargs :guard t))
  (if (natp n)
      (if (consp x)
          (if (= n 0)
              x
              (safe-nthcdr (- n 1) (cdr x)))
          (if (= n 0)
              x
              nil))
      x))

(defun terminal-marker (x)
  (declare (xargs :guard t))
  (if (consp x)
      (terminal-marker (cdr x))
      x))

; These theorems are not necessary but are informative.  The two ``safe-''
; functions above are just guard-free versions of more familiar functions.

; (defthm safe-nth-is-nth
;   (equal (safe-nth n x) (nth n x)))

; (defthm safe-nthcdr-is-nthcdr
;   (equal (safe-nthcdr n x) (nthcdr n x)))

(defun get-addr^ (addr x)
  (declare (xargs :guard (addr^p addr)
                  :measure (acl2-count addr)))
  (cond
   ((endp addr) x)
   (t (let* ((n (- (car addr) 1)) ; 0 based indexing below
             (k (len x))
             (up-flg (and (cdr addr) (eq (cadr addr) '^)))
             (addr1 (if up-flg nil (cdr addr))))
        (cond
         ((< n k)
          (get-addr^ addr1
                     (if up-flg
                         (safe-nthcdr n x)
                         (safe-nth n x))))
         ((= n k)
          (get-addr^ addr1
                     (if up-flg
                         (list '|.| (terminal-marker x))
                         '|.|)))
         ((= n (+ 1 k))
          (get-addr^ addr1
                     (if up-flg
                         (list (terminal-marker x))
                         (terminal-marker x))))
         (t nil))))))

(defun update-nthcdr (n val x)
  (declare (xargs :guard (and (natp n)
                              (<= n (len x)))))
  (cond
   ((zp n) val)
   (t (cons (car x)
            (update-nthcdr (- n 1) val (cdr x))))))

(defun put-addr^ (addr val x) ; SPARE COPY.  CHANGE IT AT WILL!
  (cond
   ((endp addr) val)
   ((and (consp (cdr addr))
         (eq (cadr addr) '^))
    (cond
     ((= (car addr) 1) ; ignore this index and the ^, just act like addr = nil!
      val)
     (t
      (let* ((n (- (car addr) 1))
             (k (len x)))
        (cond
         ((< n k)
          (update-nthcdr n val x))
         ((or (= n k) (= n (+ 1 k)))

; If the val we're putting is (|.| z) then we just put z, which uses Lisp's
; cons dot instead of the fake |.|.

          (update-nthcdr k
                         (if (and (consp val)
                                  (eq (car val) '|.|)
                                  (consp (cdr val))
                                  (null (cddr val)))
                             (cadr val)
                             val)
                         x))
         (t x))))))
   (t (let* ((n (- (car addr) 1)) ; 0-based indexing
             (k (len x)))
        (cond
         ((< n k)
          (update-nth n (put-addr^ (cdr addr) val (nth n x)) x))
         ((and (or (= n k)
                   (= n (+ k 1)))
               (null (cdr addr)))

; If the val we're putting is (|.| z) then we just put z, which uses Lisp's
; cons dot instead of the fake |.|.

          (update-nthcdr k
                         (if (and (consp val)
                                  (eq (car val) '|.|)
                                  (consp (cdr val))
                                  (null (cddr val)))
                             (cadr val)
                             val)
                         x))
         (t x))))))

; Now we work on compare-objects.

(mutual-recursion

(defun compare-objects1 (x y raddr ans)
  (declare (xargs :mode :program))
  (cond
   ((equal x y) ans)
   ((or (atom x)
        (atom y))
    (cons (list (reverse raddr) x y) ans))
   (t (compare-objects1-lst x y 1 raddr ans))))

(defun compare-objects1-lst (x y n raddr ans)
  (cond
   ((equal x y) ans)
   ((consp x)
    (cond ((consp y)
           (let ((ans1 (compare-objects1 (car x) (car y) (cons n raddr) ans)))
             (compare-objects1-lst (cdr x) (cdr y) (+ 1 n) raddr ans1)))
          (t (cons (list (reverse (cons '^ (cons n raddr))) x (list '|.| y)) ans))))
   ((consp y)
    (cons (list (reverse (cons '^ (cons n raddr))) (list '|.| x) y) ans))
   (t (cons (list (reverse (cons (+ 1 n) raddr)) x y) ans)))))

(defun make-compare-objects-placeholder (x)

; (make-compare-objects-placeholder 23) ==> :|<s23>|
; (make-compare-objects-placeholder 'PAT) ==> :|<pat>|

; Compare-objects (and explain-near-miss1) use placeholders to replace certain
; subterms.  When we prettyprint these placeholders we do so with a
; evisceration alist that prints :|<s23>| as <s23>.  So we could have used
; :<S23> as the placeholder because the user will never see the actual object,
; just what we prettyprint... UNLESS he or she pokes around, e.g., by tracing
; compare-objects, etc.  Nevertheless, we lowercase our placeholders for two
; reasons.  First, if the user does see them, they'll be easier to identify as
; special tokens.  Second, our code for compare-objects and explain-near-miss1
; could print confusing results if the objects or terms scanned contain these
; keywords.  We believe that lowercasing them (forcing the use of |...|) makes
; it ``more unlikely'' that our placeholders will clash with pre-existing
; keywords in the user's input.  Of course, nothing stops the user from typing
; or generating a term containing :|<s23>|!

; Note: If you change the appearance of placeholders in prettyprinted output,
; e.g., by changing the actual placeholder conventions below, be sure to change
; the fmt string in explain-near-miss1 which textually refers to placeholders
; by their prettyprinted appearance.

  (declare (xargs :guard (or (integerp x)
                             (and (symbolp x)
                                  (standard-char-listp (coerce (symbol-name x) 'list))))))

  (if (integerp x)
      (packn (list ':|<s| x '>))
      (intern-in-package-of-symbol
       (string-append
        "<"
        (string-append (string-downcase (symbol-name x))
                       ">"))
       :keyword)))

; The original code for compare-objects contained seven loop$s.  But loop$s are
; not allowed in ACL2 system code.  So below are six functions that compute the
; same thing as those seven loop$s.  (Compare-objects-loop$5 has a flag that
; allows it to serve for two slightly different loop$s.)  Each of these helper
; functions is commented with the original loop.  Note that the comment also
; shows the initial values of each of the formals, e.g., when called in
; compare-objects, the call of compare-objects-loop$1 is
; (compare-objects-loop$1 triplets (length triplets) nil).

(defun compare-objects-loop$1 (lst i ans)

;   (loop$ with lst = triplets
;          with i = (length triplets)
;          with ans = nil
;          do
;          (cond
;           ((endp lst) (return ans))
;           (t (let ((name (make-compare-objects-placeholder i)))
;                (progn
;                  (setq ans (cons (cons name (car lst)) ans))
;                  (setq i (- i 1))
;                  (setq lst (cdr lst)))))))
  (declare (xargs :mode :program))
  (cond
   ((endp lst) ans)
   (t (let ((name (make-compare-objects-placeholder i)))
        (compare-objects-loop$1 (cdr lst)
                                (- i 1)
                                (cons (cons name (car lst)) ans))))))

(defun compare-objects-loop$2 (lst obj)

;   (loop$ with lst = named-triplets
;          with obj = x
;          do
;          (cond ((endp lst) (return obj))
;                (t (let* ((named-triplet (car lst))
;                          (name (car named-triplet))
;                          (addr (cadr named-triplet)))
;                     (progn
;                       (setq obj (put-addr^ addr name obj))
;                       (setq lst (cdr lst)))))))
  (declare (xargs :mode :program))
  (cond
   ((endp lst) obj)
   (t (let* ((named-triplet (car lst))
             (name (car named-triplet))
             (addr (cadr named-triplet)))
        (compare-objects-loop$2 (cdr lst)
                                (put-addr^ addr name obj))))))

(defun compare-objects-loop$3 (lst)

;   (loop$ for temp in named-triplets
;          always
;          (let ((addri (cadr temp))
;                (xi (caddr temp))
;                (yi (cadddr temp)))
;            (and (if (and (consp xi)
;                          (eq (car xi) '|.|))
;                     (and (consp (cdr xi))
;                          (null (cddr xi)))
;                     t)
;                 (if (and (consp yi)
;                          (eq (car yi) '|.|))
;                     (and (consp (cdr yi))
;                          (null (cddr yi)))
;                     t)
;                 (if (or (and (consp xi)
;                              (eq (car xi) '|.|))
;                         (and (consp yi)
;                              (eq (car yi) '|.|)))
;                     (and (consp addri)
;                          (eq (car (last addri)) '^))

  (declare (xargs :mode :program))
  (cond
   ((endp lst) t)
   (t (let ((addri (cadr (car lst)))
            (xi (caddr (car lst)))
            (yi (cadddr (car lst))))
        (and (if (and (consp xi)
                      (eq (car xi) '|.|))
                 (and (consp (cdr xi))
                      (null (cddr xi)))
                 t)
             (if (and (consp yi)
                      (eq (car yi) '|.|))
                 (and (consp (cdr yi))
                      (null (cddr yi)))
                 t)
             (if (or (and (consp xi)
                          (eq (car xi) '|.|))
                     (and (consp yi)
                          (eq (car yi) '|.|)))
                 (and (consp addri)
                      (eq (car (last addri)) '^))
                 t)
             (compare-objects-loop$3 (cdr lst)))))))

(defun compare-objects-loop$4 (lst)

;   (loop$ for temp in named-triplets
;          collect
;          (list (car temp)
;                (cadr temp)
;                (if (and (consp (caddr temp))
;                         (eq (car (caddr temp)) '|.|))
;                    (cadr (caddr temp))
;                    (caddr temp))
;                (if (and (consp (cadddr temp))
;                         (eq (car (cadddr temp)) '|.|))
;                    (cadr (cadddr temp))
;                    (cadddr temp))))

  (declare (xargs :mode :program))
  (cond
   ((endp lst) nil)
   (t (cons (list (car (car lst))
                  (cadr (car lst))
                  (if (and (consp (caddr (car lst)))
                           (eq (car (caddr (car lst))) '|.|))
                      (cadr (caddr (car lst)))
                      (caddr (car lst)))
                  (if (and (consp (cadddr (car lst)))
                           (eq (car (cadddr (car lst))) '|.|))
                      (cadr (cadddr (car lst)))
                      (cadddr (car lst))))
            (compare-objects-loop$4 (cdr lst))))))

(defun compare-objects-loop$5 (flg lst obj)

; By the way, flg t means put the xi, flg nil means put the yi.

;   (loop$ with lst = named-triplets-without-bogus-dots
;          with obj = common-obj
;          do
;          (cond ((endp lst) (return obj))
;                (t (let* ((named-triplet (car lst))
;                          (addri (cadr named-triplet))
;                          (xi (caddr named-triplet)))
;                     (progn
;                       (setq obj (put-addr^ addri xi obj))
;                       (setq lst (cdr lst)))))))

; The binding of xi above was changed to yi in the other version of
; this loop$ and is subsumed by the flg below.

  (declare (xargs :mode :program))
  (cond ((endp lst) obj)
        (t (let* ((named-triplet (car lst))
                  (addri (cadr named-triplet))
                  (xi-or-yi (if flg
                                (caddr named-triplet)
                                (cadddr named-triplet))))
             (compare-objects-loop$5 flg
                                     (cdr lst)
                                     (put-addr^ addri xi-or-yi obj))))))


(defun compare-objects-loop$6 (lst)

;   (loop$ for temp in named-triplets-without-bogus-dots
;          collect (list (car temp)
;                        (caddr temp)
;                        (cadddr temp)))

  (declare (xargs :mode :program))
  (cond
   ((endp lst) nil)
   (t (cons (list (car (car lst))
                  (caddr (car lst))
                  (cadddr (car lst)))
            (compare-objects-loop$6 (cdr lst))))))

(defun compare-objects (x y)

  (declare (xargs :mode :program))

; This function returns ((:OBJ obj) (:LEGEND ((name1 x1 y1) ... (namek xk
; yk)))) such that if each namei is replaced in obj by the xi (or yi) the
; result is x (or y).  By ``replaced'' we mean put-addr^ is used to do each
; replacement, where the address used is that of the occurrence of namei in
; obj.  However, we do not report the addresses.  If this spec is not
; satisfied, we cause a hard error.

  (let* ((triplets (compare-objects1 x y nil nil))
         (named-triplets
          (compare-objects-loop$1 triplets (length triplets) nil))
         (common-obj
          (compare-objects-loop$2 named-triplets x)))
    (cond
     ((compare-objects-loop$3 named-triplets)

; We expect the above test to always be true!  We believe that each
; replacement, xi and yi, that begins with a bogus |.| is a doublet of the form
; (|.| z) and that if either xi or yi begins with a bogus |.| the associated
; addri ends with ^.  This gives us permission to simplify the replacements by
; transforming (|.| z) to simply z, thus hiding the bogus |.| from the user.
; We will cause an error if this test fails!

      (let* ((named-triplets-without-bogus-dots
              (compare-objects-loop$4 named-triplets))
             (x-prime
              (compare-objects-loop$5 t ; collect the xi
                                      named-triplets-without-bogus-dots
                                      common-obj))
             (y-prime
              (compare-objects-loop$5 nil ; collect the yi
                                      named-triplets-without-bogus-dots
                                      common-obj)))
        (cond ((and (equal x-prime x)
                    (equal y-prime y))

; Good! Stripping out the bogus dots preserved the intended semantics: x and y
; can be obtained from the common-obj by hitting each addri with the (stripped)
; xi and yi, respectively.

               (let ((named-doublets
                      (compare-objects-loop$6 named-triplets-without-bogus-dots)))

; We strip out the addresses.

                 `((:OBJ ,common-obj)
                   (:LEGEND ,named-doublets))))
              (t
               (er hard 'compare-objects
                   "Compare-objects does not satisfy its intended spec that ~
                    the original x and y can be obtained from the common ~
                    object by hitting, with put-addr^, the addr of each name ~
                    <si> with the simplified replacements, xi and yi, stripped ~
                    of any bogus dots.  Please send this error message ~
                    (complete with the display below) to the ~
                    implementors.~%~Y01~%Thanks."
                       (list (list :x x)
                             (list :y y)
                             (list :named-triplets named-triplets)
                             (list :named-triplets-without-bogus-dots
                                   named-triplets-without-bogus-dots)
                             (list :x-prime x-prime)
                             (list :y-prime y-prime))
                       nil)))))
     (t (er hard 'compare-objects
            "We thought compare-objects1 never reported a replacement ~
             containing a bogus dot unless the replacement was of the form ~
             (|.| z) and the associated address ended in ^.  Please send this ~
             error message (complete with the display below) to the ~
             implementors.~%~Y01~%~Y21.~%Thanks."
                x nil y)))))

(defun get-actual-brr-evisc-tuple (state)

; The brr-evisc-tuple, which is technically found in the global var
; brr-evisc-tuple, can actually be the keyword :default, which means it is the
; same as the term evisc-tuple.  That can be :default too, in which case we use
; the equivalent of (evisc-tuple 5 7 nil nil).  This function returns either
; nil, which is a standard-evisc-tuplep, or an actual 4-tuple.

  (let ((tuple (f-get-global 'brr-evisc-tuple state)))
    (cond
     ((eq tuple :default)

; If the brr-evisc-tuple is the default, it defaults to the term-evisc-tuple.g
      (let ((tuple (f-get-global 'term-evisc-tuple state)))
        (cond
         ((eq tuple :default)
          (evisc-tuple 5 7 nil nil))
         (t tuple))))
    (t tuple))))

(defun keyword-to-lc-string-alist (keywords)

; We believe that all placeholder keywords listed in the argument provided by
; explain-near-miss1 (for which this function was invented) are already
; lowercase, e.g., :|<s23>| not :<S23>, but we downcase anyway just so this
; function could be used elsewhere.

  (cond
   ((endp keywords) nil)
   ((keywordp (car keywords))
    (cons (cons (car keywords)
                (string-downcase (symbol-name (car keywords))))
          (keyword-to-lc-string-alist (cdr keywords))))
   (t (keyword-to-lc-string-alist (cdr keywords)))))

(defun explain-near-miss2 (pat-cmd pat-term target-term
                                   large-cons-count evisc-tuple state)

; See explain-near-miss1.

  (declare (xargs :mode :program))
  (mv-let (ans1 alist1 addr alist subtarget)
    (one-way-unify-fr pat-term target-term)
    (cond
     ((or (null pat-term)
          (not (or (eq pat-cmd :lhs)
                   (eq pat-cmd :max-term))))
      (er soft 'explain-near-miss
          "Explain-near-miss is meant to be invoked when (brr@ :lemma) is a ~
           lemma of rule-class :rewrite, :linear, or :rewrite-quoted-constant ~
           and the current value of (brr@ :lemma) is none of these."))
     ((not (or (null large-cons-count)
               (natp large-cons-count)))
      (er soft 'explain-near-miss
          "The large-cons-count argument must be nil or a natural, but you ~
           supplied ~x0."
          large-cons-count))
     ((not
       (or (eq evisc-tuple t)                    ; means :brr evisc-tuple
           (standard-evisc-tuplep evisc-tuple))) ; nil (means none) or 4-tuple
      (er soft 'explain-near-miss
          "The evisc-tuple argument must be nil (meaning no evisceration), ~
           t (meaning use the brr evisc-tuple), or a standard evisceration ~
           4-tuple.  You supplied ~x0."
          evisc-tuple))
     (t
      (let ((evisc-tuple
             (cond
              ((eq evisc-tuple nil) nil)
              ((eq evisc-tuple t) (get-actual-brr-evisc-tuple state))
              (t evisc-tuple))))
        (cond
         (ans1
          (mv-let (ans2 alist2)
            (one-way-unify pat-term target-term)
            (cond (ans2
                   (let ((state
                          (fmt-abbrev
                           "Explain-near-miss is meant to be invoked only ~
                            after the rule's triggering pattern, ~X01, fails ~
                            to match the target term, ~X21.  But these two ~
                            terms do match, under the substitution ~X31 (here ~
                            printed as a list of doublets, (var term), rather ~
                            than a list of pairs (var . term)).  The ~
                            triggering-pattern and target term may be ~
                            obtained from within a near miss break with the ~
                            commands ~x4 and :TARGET."
                           `((#\0 . ,pat-term)
                             (#\1 . ,evisc-tuple)
                             (#\2 . ,target-term)
                             (#\3 . ,(pairlis$ (strip-cars alist2)
                                               (pairlis-x2 (strip-cdrs alist2) nil)))
                             (#\4 . ,pat-cmd))
                           0
                           *standard-co*
                           state
                           "~%~%")))
                     (value :invisible)))
                  (t (prog2$
                      (er hard 'explain-near-miss
                          "There is a bug in ONE-WAY-UNIFY-FR.  It reports ~
                           that the pattern ~X01 matches the term ~X21 under ~
                           substitution ~X31, even though ONE-WAY-UNIFY ~
                           reports that the pattern and term do not match!  ~
                           Please provide the implementors with this ~
                           information."
                          pat-term
                          nil
                          target-term
                          alist1)
                      (value :invisible))))))
         (t (let* ((subpat (fetch-addr addr pat-term))
                   (instantiated-subpat (sublis-var alist subpat))
                   (marked-pat (put-addr^ addr
                                          (make-compare-objects-placeholder 'pat)
                                          pat-term))
                   (doublet-alist (pairlis$ (strip-cars alist)
                                            (pairlis-x2 (strip-cdrs alist) nil)))
                   (two-quotesp (and (quotep instantiated-subpat)
                                     (quotep subtarget)))
                   (compare-objectsp
                    (or two-quotesp
                        (and (nvariablep instantiated-subpat)
                             (not (fquotep instantiated-subpat))
                             (flambdap (ffn-symb instantiated-subpat))
                             (nvariablep subtarget)
                             (not (fquotep subtarget))
                             (flambdap (ffn-symb subtarget))
                             (not (equal (ffn-symb instantiated-subpat)
                                         (ffn-symb subtarget))))))
; Note that if compare-objectsp is known to be true and two-quotesp is nil,
; then instantiated-subpat and subtarget are applications of unequal lambda expressions.
; We will compare the evgs/lambda objects, if they are ``large''.  So we let
; obj1 and obj2 be the objects to compare and decide whether they're large.

                   (obj1 (if compare-objectsp
                             (if two-quotesp
                                 instantiated-subpat
                                 (ffn-symb instantiated-subpat))
                             nil))
                   (obj2 (if compare-objectsp
                             (if two-quotesp
                                 subtarget
                                 (ffn-symb subtarget))
                             nil))
                   (largep (if compare-objectsp
                               (or (null large-cons-count)
                                   (>= (cons-count-bounded-ac obj1 0
                                                              large-cons-count)
                                       large-cons-count)
                                   (>= (cons-count-bounded-ac obj2 0
                                                              large-cons-count)
                                       large-cons-count))
                               nil))
                   (obj-and-legend (compare-objects obj1 obj2)))
              (let ((state
                     (fmt-abbrev
                      "~%The ACL2 match algorithm attempted to match ~xe with ~
                       :TARGET by finding a substitution, s, such that ~xe/s ~
                       = :TARGET.  That attempt failed when trying to match ~
                       the subterm of ~xe marked <pat> in ~xe' below.~%~%~
                       ~xe:~_f ~Y01~
                       ~xe':~_f~Y21~
                       :TARGET:   ~Y31~%~
                       Below we show the substitution, s, computed prior to ~
                       the failure; the subterm of ~xe we're calling <pat>; ~
                       the instantiated subterm, <pat>/s; and the ~
                       corresponding subterm, <tar>, of :TARGET.~%~%~
                       s:       ~Y61~
                       <pat>:   ~Y51~
                       <pat>/s: ~Y81~
                       <tar>:   ~Y71~%~
                       For the rewriter to get past this failure the match ~
                       algorithm must be able to extend substitution s to s' ~
                       so that <pat>/s' is equal to <tar> and our match ~
                       algorithm could not find such an extension.~%~%In case ~
                       you want to manually explore <pat> and <tar> they may ~
                       be obtained by executing the following forms in the ~
                       break caused by this near miss~%~%<pat>: ~Yc1<tar>: ~
                       ~Yd1~%(Note: The substitution, s, is displayed above ~
                       as a list of ``doublets'' rather than pairs.  I.e., ~
                       ((var1 term1) ...) instead of ((var1 . term1) ...).  ~
                       If you wish to instantiate <pat> using sublis-var you ~
                       must convert the doublets to pairs.  Finally, be ~
                       advised that instantiating a term can produce a quoted ~
                       object, e.g., (sublis-var '((x . '13)) '(cons x x)) is ~
                       '(13 . 13), not (cons '13 '13).)~%~
                       ~#9~[~/~%Since <pat>/s and <tar> are ~#a~[quoted ~
                       objects, those objects~/applications of lambda ~
                       expressions, those lambda expressions~] must be ~
                       identical for the match algorithm to succeed.  ~
                       Because they are ``large'' it might be difficult to ~
                       see where they differ.  So we show you below.~%~%Let ~
                       x be ~#a~[<pat>/s~/the lambda expression being ~
                       applied in <pat>/s, i.e., (fn-symb <pat/s>)~] and let ~
                       y be ~#a~[<tar>~/(fn-symb <tar>)~].  Below is the ~
                       output of (compare-objects x y).  The object labeled ~
                       :OBJ shows the basic structure of x and y with ~
                       certain substructures replaced by tokens, <si>, ~
                       i=1,2,....  These <si> mark where x and y differ. The ~
                       :LEGEND is a list of elements, each of the form (<si> ~
                       xi yi) meaning ``at <si>, x contains xi but y ~
                       contains yi.''~%~%~Yb1~]~%See :DOC ~
                       explain-near-miss~#9~[~/ and :DOC compare-objects~] ~
                       for details."

                      `((#\0 . ,pat-term)

; We transfer the user's specified print-level and print-length into the
; evisc-tuple we'll use. We considered adding the user's specified alist to the
; end of our alist, and we considered using the user's specified hiding-cars.
; But we dropped those two ideas because we are nervous about those settings
; hiding the special tokens we've inserted.

                        (#\1 . ,(evisc-tuple (cadr evisc-tuple)
                                             (caddr evisc-tuple)
                                             (keyword-to-lc-string-alist
                                              (cons ':|<pat>|
                                                    (strip-cars
                                                     (cadr
                                                      (assoc-eq :legend obj-and-legend)))))
                                             nil))
                        (#\2 . ,marked-pat)
                        (#\3 . ,target-term)
; We don't use #\4 in the fmt string anymore, but we do use addr
;                       (#\4 . ,addr)
                        (#\5 . ,subpat)
                        (#\6 . ,doublet-alist)
                        (#\7 . ,subtarget)
                        (#\8 . ,instantiated-subpat)

; If the mismatch occurred on two ``large'' quotes or two ``large'' unequal
; lambda expressions, we'll print the comparison of the two.

                        (#\9 . ,(if (and compare-objectsp largep) 1 0))
                        (#\a . ,(if two-quotesp 0 1)) ; only relevant if compare-objectsp
                        (#\b . ,obj-and-legend)
                        (#\c . ,`(fetch-addr ',addr (brr@ ,pat-cmd)))
                        (#\d . ,`(fetch-addr ',addr (brr@ :target)))
                        (#\e . ,pat-cmd)
                        (#\f . ,(if (eq pat-cmd :max-term) 0 5)))
                      0
                      *standard-co*
                      state
                      "~%~%")))
                (value :invisible))))))))))

(defun explain-near-miss1 (target-term large-cons-count evisc-tuple state)

; We should be in a near miss break.  Brr-cmd-name and pattern should be bound
; in as brr-locals.  Large-cons-count is the minimum number of conses for a
; quote term to be considered ``large'' and evisc-tuple should be nil (meaning
; no evisceration), :default (which means brr evisc-tuple), or an evisc-tuple.
; The explanation of the near miss is done by explain-near-miss2, but we must
; first compute for it pattern term of the lemma and the brr command, :lhs or
; :max-term, which delivers the pattern to the user.

  (declare (xargs :mode :program))
  (let* ((pat-cmd (get-brr-local 'brr-cmd-name-for-pattern state))
         (pat-term (get-brr-local 'pattern state)))

; Pat-cmd is the brr command that will return the pattern of the rule.  There
; are three rule-classes of concern: :rewrite, :linear, and
; :rewrite-quoted-constant.  When stored, the last is a subclass of the first
; and, in the case of Form [2] rewrite-quoted-constant rules like (equiv
; (normalizer x) x) -- which fires only on quoted constants x and runs
; normalizer on x to get the result -- get-rule-field swaps the meaning of :lhs
; and :rhs.  So above when we bind pat-cmd we bind it either to :max-term or
; :lhs.  If it is bound to nil, explain-near-miss2 will signal an error because
; it means explain-near-miss was invoked when we were not in a near miss break

    (explain-near-miss2 pat-cmd pat-term target-term large-cons-count
                        evisc-tuple state)))

(defun refinement-failure-brkpt1 (lemma target type-alist geneqv ancestors
                                        initial-ttree gstack rcnst
                                        simplify-clause-pot-lst state)

; This function is called when lemma failed the refinement test.  That can only
; happen if lemma is a rewrite-rule! Here we cause a break similar to the one
; caused by brkpt1 IF the lemma is monitored.  See brkpt1.

; #+ACL2-PAR note: see brkpt1.

  (cond
   #+acl2-par ; test is always false anyhow when #-acl2-par
   ((f-get-global 'waterfall-parallelism state)
    nil)
   ((not (f-get-global 'gstackp state))
    nil)
   (t
    (mv-let (rune brr-cmd-name pattern restrictions)
      (get-brr-one-way-unify-info lemma rcnst)
      (brr-wormhole
; We enter the wormhole if the rule is monitored and the :RF keyword in the
; break criteria is bound to non-nil. But the :condition (yet to be checked)
; may make us exit silently.
       '(lambda (whs)
          (set-wormhole-entry-code
           whs
           (let ((temp (assoc-equal (get-rule-field lemma :rune)
                                    (access brr-status whs :brr-monitored-runes))))
             (if (and temp (cdr (assoc-eq :RF (cdr temp))))
                 :ENTER
                 :SKIP))))
       `((brr-gstack . ,gstack)
         (brr-local-alist . ((rune . ,rune)
                             (brr-cmd-name-for-pattern . ,brr-cmd-name)
                             (pattern . ,pattern)
                             (restrictions . ,restrictions)
                             (lemma . ,lemma)
                             (target . ,target)
                             (type-alist . ,type-alist)
                             (geneqv . ,geneqv)
                             (pot-list . ,simplify-clause-pot-lst)
                             (ancestors . ,ancestors)
                             (rcnst . ,rcnst)
                             (initial-ttree . ,initial-ttree))))
       '(pprogn
         (push-brr-status state)
         (let ((pair (assoc-equal (get-rule-field
                                   (get-brr-local 'lemma state)
                                   :rune)
                                  (access brr-status
                                          (f-get-global 'wormhole-status
                                                        state)
                                          :brr-monitored-runes))))
; We know pair is non-nil because of the entrance test on wormhole above
           (mv-let (erp okp state)
             (eval-break-condition (car pair)
                                   (cdr (assoc-eq :condition (cdr pair)))
                                   'wormhole state)
             (cond
              (erp

; If evaling the break condition caused an error, we abort.  The error message
; has already been printed by eval-break-condition.  To continue silently will
; most likely just cause the error to be printed repeatedly as the lemma is
; tried repeatedly.  To enter the interactive loop might leave an offline proof
; just hanging.

               (pprogn
                (stuff-standard-oi '(:a!) state)
                (value t)))
              (okp
               (pprogn
                (cond ((true-listp okp)
                       (stuff-standard-oi okp state))
                      (t state))
                (prog2$ (cw "~%(~F0 Breaking ~F1 on ~X23:~|~%The ~
                                equivalence relation, ~x4, of this rule is ~
                                not a refinement of the current geneqv, ~x5.  ~
                                Use :path or :path+ to see how the geneqv ~
                                evolved.  See :DOC refinement-failure for ~
                                advice about how to deal with this kind of ~
                                problem.~%~%"
                            (brr-depth state)
                            (get-rule-field (get-brr-local 'lemma state)
                                            :rune)
                            (get-brr-local 'target state)
                            (brr-evisc-tuple state)
                            (access rewrite-rule
                                    (get-brr-local 'lemma state)
                                    :equiv)
                            (show-geneqv (get-brr-local 'geneqv state)
                                         'non-prim))
                        (value t))))
              (t (pprogn
                  (pop-brr-status state)
                  (value nil)))))))
       *brkpt1-aliases*)))))

(defun near-miss-brkpt1 (lemma target type-alist geneqv ancestors initial-ttree
                               gstack rcnst simplify-clause-pot-lst state)

; This function is called when lemma failed to match target!  It causes a break
; similar to the one caused by brkpt1 IF the lemma's monitor specified a
; near-miss break criteria that is satisfied by the target.  See brkpt1.

; #+ACL2-PAR note: see brkpt1.

  (cond
   #+acl2-par ; test is always false anyhow when #-acl2-par
   ((f-get-global 'waterfall-parallelism state)
    nil)
   ((not (f-get-global 'gstackp state))
    nil)
   (t
    (mv-let (rune brr-cmd-name pattern restrictions)
      (get-brr-one-way-unify-info lemma rcnst)
      (brr-wormhole
       '(lambda (whs)
          (set-wormhole-entry-code
           whs

; Most failed matches inevitably are on unmonitored lemmas (since the vast
; majority of lemmas will be unmonitored).  So we optimize the case that there
; is no monitor on lemma.  Pair is either nil -- for an unmonitored rune -- or
; a pair of the form (rune . criteria-alist), where criteria-alist may or may
; not contain near-miss criteria.

           (let ((pair
                  (assoc-equal
                   (get-rule-field lemma :rune)
                   (access brr-status whs :brr-monitored-runes))))
             (cond
              ((null pair)
               :SKIP)
              ((brr-near-missp nil ; no msg required
                               lemma target rcnst (cdr pair))

; We :ENTER if this is a near miss.  But we don't need a msg here, just a
; simple Boolean: is this a near miss?
               :ENTER)
              (t :SKIP)))))
       `((brr-gstack . ,gstack)
         (brr-local-alist . ((rune . ,rune)
                             (brr-cmd-name-for-pattern . ,brr-cmd-name)
                             (pattern . ,pattern)
                             (restrictions . ,restrictions)
                             (lemma . ,lemma)
                             (target . ,target)
                             (type-alist . ,type-alist)
                             (geneqv . ,geneqv)
                             (pot-list . ,simplify-clause-pot-lst)
                             (ancestors . ,ancestors)
                             (rcnst . ,rcnst)
                             (initial-ttree . ,initial-ttree))))
       '(pprogn
         (push-brr-status state)
         (let ((pair (assoc-equal (get-rule-field (get-brr-local 'lemma
                                                                 state)
                                                  :rune)
                                  (access brr-status
                                          (f-get-global 'wormhole-status
                                                        state)
                                          :brr-monitored-runes))))
; We know pair is non-nil because of the entrance test on wormhole above
           (mv-let (erp okp state)
             (eval-break-condition (car pair)
                                   (cdr (assoc-eq :condition (cdr pair)))
                                   'wormhole state)
             (cond
              (erp

; If evaling the break condition caused an error, we abort.  The error message
; has already been printed by eval-break-condition.  To continue silently will
; most likely just cause the error to be printed repeatedly as the lemma is
; tried repeatedly.  To enter the interactive loop might leave an offline proof
; just hanging.

               (pprogn
                (stuff-standard-oi '(:a!) state)
                (value t)))
              (okp
               (pprogn
                (cond ((true-listp okp)
                       (stuff-standard-oi okp state))
                      (t state))
                (prog2$ (cw "~%(~F0 Breaking ~F1 on ~X23:~|~%The pattern in ~
                             this rule failed to match the target~#4~[~/ ~
                             under the restrictions ~x5~].  ~@6"
                            (brr-depth state)
                            (get-rule-field (get-brr-local 'lemma state)
                                            :rune)
                            (get-brr-local 'target state)
                            (brr-evisc-tuple state)
                            (if (get-brr-local 'restrictions state) 1 0)
                            (get-brr-local 'restrictions state)
                            (brr-near-missp
                             t ; msg required
                             (get-brr-local 'lemma state)
                             (get-brr-local 'target state)
                             (get-brr-local 'restrictions state)
                             (cdr (assoc-equal (get-brr-local 'rune state)
                                               (access brr-status
                                                       (f-get-global 'wormhole-status
                                                                     state)
                                                       :brr-monitored-runes)))))
                        (value t))))
              (t (pprogn
                  (pop-brr-status state)
                  (value nil)))))))
       *brkpt1-aliases*)))))

(defun brkpt1 (lemma target unify-subst type-alist geneqv ancestors
                     initial-ttree gstack rcnst simplify-clause-pot-lst state)

; #+ACL2-PAR note: since we lock the use of wormholes, brr might be usable
; within the parallelized waterfall.  However, since locks can serialize
; computation, we leave brr disabled for now.  Kaufmann has the following
; reaction to using brr and waterfall parallelism at the same time:

;;; "My immediate reaction is that if someone wants to use brr, they should
;;; turn off parallelism.  I'd probably even make it illegal to have both
;;; waterfall-parallelism enabled and :brr t at the same time."

; Parallelism blemish: cause an error when a user tries to enable parallelism
; and brr is enabled.  Also cause an error when enabling brr and
; waterfall-parallelism is enabled.  We do not label this a "wart", because we
; have documented this lack of feature in
; unsupported-waterfall-parallelism-features.

  (cond
   #+acl2-par ; test is always false anyhow when #-acl2-par
   ((f-get-global 'waterfall-parallelism state)
    nil)
   (t
    (let ((gstackp (f-get-global 'gstackp state)))
      (cond
       ((not gstackp)
        nil)
       (t
        (prog2$
         (and (eq gstackp :brr-data)
              (brkpt1-brr-data-entry ancestors gstack rcnst state)
              (wormhole-eval 'brr-data
                             '(lambda (whs)
                                (set-wormhole-data-fast
                                 whs
                                 (update-brr-data-1
                                  lemma target unify-subst type-alist geneqv
                                  ancestors initial-ttree gstack rcnst
                                  simplify-clause-pot-lst
                                  (wormhole-data whs))))
                             (list :no-wormhole-lock
                                   lemma target unify-subst type-alist geneqv
                                   simplify-clause-pot-lst ancestors rcnst
                                   initial-ttree gstack)))
         (brr-wormhole
          '(lambda (whs)
             (set-wormhole-entry-code
              whs
              (if (assoc-equal (get-rule-field lemma :rune)
                               (access brr-status whs :brr-monitored-runes))
                  :ENTER
                :SKIP)))
          `((brr-gstack . ,gstack)
            (brr-local-alist . ((lemma . ,lemma)
                                (target . ,target)
                                (unify-subst . ,unify-subst)
                                (type-alist . ,type-alist)
                                (geneqv . ,geneqv)
                                (pot-list . ,simplify-clause-pot-lst)
                                (ancestors . ,ancestors)
                                (rcnst . ,rcnst)
                                (initial-ttree . ,initial-ttree))))
          '(pprogn
            (push-brr-status state)
            (let ((pair (assoc-equal (get-rule-field (get-brr-local 'lemma
                                                                    state)
                                                     :rune)
                                     (access brr-status
                                             (f-get-global 'wormhole-status
                                                           state)
                                             :brr-monitored-runes))))
; We know pair is non-nil because of the entrance test on wormhole above
              (mv-let (erp okp state)
                (eval-break-condition (car pair)
                                      (cdr (assoc-eq :condition (cdr pair)))
                                      'wormhole state)
                (cond
                 (erp

; If evaling the break condition caused an error, we abort.  The error message
; has already been printed by eval-break-condition.  To continue silently will
; most likely just cause the error to be printed repeatedly as the lemma is
; tried repeatedly.  To enter the interactive loop might leave an offline proof
; just hanging.

                  (pprogn
                   (stuff-standard-oi '(:a!) state)
                   (value t)))
                 (okp
                  (pprogn
                   (cond ((true-listp okp)
                          (stuff-standard-oi okp state))
                         (t state))
                   (prog2$ (cw "~%(~F0 Breaking ~F1 on ~X23:~|"
                               (brr-depth state)
                               (get-rule-field (get-brr-local 'lemma state)
                                               :rune)
                               (get-brr-local 'target state)
                               (brr-evisc-tuple state))
                           (value t))))
                 (t (pprogn
                     (pop-brr-status state)
                     (value nil)))))))
          *brkpt1-aliases*))))))))

(defun brkpt2 (wonp failure-reason unify-subst gstack brr-result final-ttree
                    rcnst ancestors state)

; #+ACL2-PAR note: see brkpt1.

  (cond
   #+acl2-par ; test is always false anyhow when #-acl2-par
   ((f-get-global 'waterfall-parallelism state)
    nil)
   (t
    (let ((gstackp (f-get-global 'gstackp state)))
      (cond
       ((not gstackp)
        nil)
       (t
        (prog2$
         (brr-wormhole
          '(lambda (whs)
             (set-wormhole-entry-code
              whs
              (if (equal gstack (access brr-status whs :brr-gstack))
                  :ENTER
                :SKIP)))
          `((brr-gstack . ,gstack)
            (brr-local-alist . ((wonp . ,wonp)
                                (failure-reason . ,failure-reason)
                                (unify-subst . ,unify-subst) ; maybe changed
                                (brr-result . ,brr-result)
                                (rcnst . ,rcnst)
                                (final-ttree . ,final-ttree))))
          '(cond
            ((eq (get-brr-local 'action state) 'silent)

; We ought, perhaps, start by using put-brr-locals to augment the
; :brr-local-alist inherited from brkpt1 with the additional locals (above)
; passed to brkpt2.  But the action 'silent requires no use of those new
; locals so we avoid the unnecessary work.

             (prog2$ (cw "~F0)~%" (brr-depth state))
                     (pprogn
                      (pop-brr-status state)
                      (value nil))))
            ((eq (get-brr-local 'action state) 'print)

; In order to print the results we need to augment the :brr-local-alist with
; the new inputs.

             (pprogn
              (put-brr-locals (cdr (assoc-eq 'brr-local-alist
                                             (f-get-global 'wormhole-input
                                                           state)))
                              state)
              (prog2$ (if (get-brr-local 'wonp state)
                          (cw "~%~F0 ~F1 produced ~X23.~|~F0)~%"
                              (brr-depth state)
                              (get-rule-field (get-brr-local 'lemma state)
                                              :rune)
                              (brr-result state)
                              (brr-evisc-tuple state))
                        (cw "~%~F0x ~F1 failed because ~@2~|~F0)~%"
                            (brr-depth state)
                            (get-rule-field (get-brr-local 'lemma state) :rune)
                            (tilde-@-failure-reason-phrase
                             (get-brr-local 'failure-reason state)
                             1
                             (get-brr-local 'unify-subst state)
                             (brr-evisc-tuple state)
                             (free-vars-display-limit state)
                             state)))
                      (pprogn
                       (pop-brr-status state)
                       (value nil)))))
            (t (pprogn

; To interact with the user we need to augment the :brr-local-alist with the
; new inputs.

                (put-brr-locals (cdr (assoc-eq 'brr-local-alist
                                               (f-get-global 'wormhole-input
                                                             state)))
                                state)
                (er-progn
                 (set-standard-oi
                  (get-brr-local 'saved-standard-oi state)
                  state)
                 (cond ((consp (f-get-global 'standard-oi state))
                        (set-ld-pre-eval-print t state))
                       (t (value nil))) ; This (value nil) is not an exit!
                 (prog2$
                  (if (get-brr-local 'wonp state)
                      (cw "~%~F0! ~F1 produced ~X23.~|~%"
                          (brr-depth state)
                          (get-rule-field (get-brr-local 'lemma state) :rune)
                          (brr-result state)
                          (brr-evisc-tuple state))
                    (cw "~%~F0x ~F1 failed because ~@2~|~%"
                        (brr-depth state)
                        (get-rule-field (get-brr-local 'lemma state) :rune)
                        (tilde-@-failure-reason-phrase
                         (get-brr-local 'failure-reason state)
                         1
                         (get-brr-local 'unify-subst state)
                         (brr-evisc-tuple state)
                         (free-vars-display-limit state)
                         state)))

; We enter the interactive loop.  All exits are handled by the keyword aliases
; and ought to pop-brr-status.

                  (value t))))))
          *brkpt2-aliases*)
         (and (not (eq failure-reason 'near-miss))
              (not (eq failure-reason 'refinement-failure))
              (eq gstackp :brr-data)
              (brkpt2-brr-data-entry ancestors gstack rcnst state)
              (wormhole-eval 'brr-data
                             '(lambda (whs)
                                (set-wormhole-data-fast
                                 whs
                                 (update-brr-data-2
                                  wonp failure-reason unify-subst gstack
                                  brr-result final-ttree rcnst ancestors
                                  (wormhole-data whs))))
                             (list :no-wormhole-lock
                                   wonp failure-reason unify-subst gstack
                                   brr-result final-ttree rcnst))))))))))

(defun show-brr-data-1 (x)
  (declare (xargs :guard (weak-brr-data-1-p x)))
  (list :target (access brr-data-1 x :target)
        :unify-subst (alist-to-doublets
                      (access brr-data-1 x :unify-subst))
        :type-alist (alist-to-doublets
                     (decode-type-alist (access brr-data-1 x :type-alist)))
        :lemma (let ((lemma (access brr-data-1 x :lemma)))
                 (and (consp lemma)
                      (access-x-rule-rune (car lemma) lemma)))
        :gstack (access brr-data-1 x :gstack)))

(defun show-brr-data-2 (x)
  (declare (xargs :guard (weak-brr-data-2-p x)))
  (list* :brr-result (access brr-data-2 x :brr-result)
         (let ((failure-reason (access brr-data-2 x :failure-reason)))
           (and failure-reason
                (list :failure-reason failure-reason)))))

(mutual-recursion

(defun show-brr-data (x)
  (declare (xargs :guard (brr-data-p t x)))
  (and (mbt (brr-data-p t x))
       (append (show-brr-data-1 (access brr-data x :pre))
               (show-brr-data-2 (access brr-data x :post))
               (list :completed
                     (show-brr-data-lst (access brr-data x :completed))))))

(defun show-brr-data-lst (x)
  (declare (xargs :guard (brr-data-listp t x)))
  (cond ((endp x) nil)
        (t (cons (show-brr-data (car x))
                 (show-brr-data-lst (cdr x))))))
)

(mutual-recursion

(defun brr-data-2-for-term-1 (subterm-p term brr-data)
  (or (brr-data-2-for-term subterm-p
                           term
                           (access brr-data brr-data :completed))
      (let* ((post (access brr-data brr-data :post))
             (brr-result (access brr-data-2 post :brr-result)))
        (and (if subterm-p
                 (dumb-occur term brr-result)
               (equal term brr-result))
             post))))

(defun brr-data-2-for-term (subterm-p term brr-data-lst)
  (cond ((endp brr-data-lst) nil)
        (t (or (brr-data-2-for-term-1 subterm-p term (car brr-data-lst))
               (brr-data-2-for-term subterm-p term (cdr brr-data-lst))))))
)

(mutual-recursion

(defun matching-subterm (pat term alist target)

; If pat/alist2 is a subterm s of term for some extension of alist2 of alist
; such that s does not occur in target, then return that subterm.  Otherwise
; return nil.

  (mv-let (flg alist2)
    (one-way-unify1 pat term alist)
    (declare (ignore alist2))
    (cond ((and flg
                (not (dumb-occur term target)))
           term)
          ((or (variablep term)
               (fquotep term))
           nil)
          (t (matching-subterm-lst pat (fargs term) alist target)))))

(defun matching-subterm-lst (pat lst alist target)
  (cond ((endp lst) nil)
        (t (or (matching-subterm pat (car lst) alist target)
               (matching-subterm-lst pat (cdr lst) alist target)))))
)

(mutual-recursion

(defun cw-gstack-for-term-fn1-1 (subterm-p term brr-data alist)

; This returns either (mv nil nil nil nil) or (mv term2 x d-2 rest), where d-2
; is a brr-data-2 record, term2 is the brr-result for the bottom of the :gstack
; of d-2, rest is a list of brr-data records, and x is either nil or a natural
; number less than the length of the gstack of d-2.

  (let* ((pre (access brr-data brr-data :pre))
         (target (access brr-data-1 pre :target))
         (post (access brr-data brr-data :post))
         (brr-result (access brr-data-2 post :brr-result))
         (subterm
          (cond ((eq alist :none)
                 (and (not (dumb-occur term target))
                      (if subterm-p
                          (dumb-occur term brr-result)
                        (equal term brr-result))
                      term))
                (subterm-p
                 (matching-subterm term brr-result alist target))
                (t (mv-let (flg alist2)
                     (one-way-unify1 term brr-result alist)
                     (declare (ignore alist2))
                     (and flg
                          (not (dumb-occur brr-result target))
                          brr-result))))))
    (cond
     (subterm
      (let ((d-2 (brr-data-2-for-term
                  subterm-p
                  subterm
                  (access brr-data brr-data :completed))))
        (cond ((null d-2)
               (mv nil post nil))
              (t ; the :gstack of post is an initial segment of that of d-2
               (mv post d-2 nil)))))
     (t (cw-gstack-for-term-fn1 subterm-p
                                term
                                (access brr-data brr-data :completed)
                                alist)))))

(defun cw-gstack-for-term-fn1 (subterm-p term brr-data-lst alist)
  (cond ((endp brr-data-lst) (mv nil nil nil))
        (t (mv-let (earlier-d-2 d-2 rest)
             (cw-gstack-for-term-fn1-1 subterm-p term (car brr-data-lst)
                                       alist)
             (cond (d-2 (mv earlier-d-2
                            d-2
                            (append rest (cdr brr-data-lst))))
                   (t (cw-gstack-for-term-fn1 subterm-p
                                              term
                                              (cdr brr-data-lst)
                                              alist)))))))
)

(defun symbol-name-lst (lst)
  (declare (xargs :guard (symbol-listp lst)))
  (cond ((endp lst) nil)
        (t (cons (symbol-name (car lst))
                 (symbol-name-lst (cdr lst))))))

(defun acl2-query-simulate-interaction (msg alist controlledp ans state)
  (cond ((and (atom ans)
              (or controlledp
                  (and (not (f-get-global 'window-interfacep state))

; If a special window is devoted to queries, then there is no way to
; pretend to answer, so we don't.  We just go on.  Imagine that we
; answered and the window disappeared so quickly you couldn't see the
; answer.

                       (not (eq (standard-co state) *standard-co*)))))
         (pprogn
          (fms msg alist (standard-co state) state (ld-evisc-tuple state))
          (princ$ ans (standard-co state) state)
          (newline (standard-co state) state)
          state))
        (t state)))

(defun acl2-query1 (id qt alist state)

; This is the function actually responsible for printing the query
; and getting the answer, for the current level in the query tree qt.
; See acl2-query for the context.

  (let ((dv (cdr-assoc-query-id id (ld-query-control-alist state)))
        (msg "ACL2 Query (~x0):  ~@1  (~*2):  ")
        (alist1 (list (cons #\0 id)
                      (cons #\1 (cons (car qt) alist))
                      (cons #\2
                            (list "" "~s*" "~s* or " "~s*, "
                                  (symbol-name-lst (evens (cdr qt))))))))
    (cond
     ((null dv)
      (pprogn
       (io? query nil state
            (alist1 msg)
            (fms msg alist1 *standard-co* state (ld-evisc-tuple state)))
       (er-let*
        ((ans (read-object *standard-oi* state)))
        (let ((temp (and (symbolp ans)
                         (assoc-keyword
                          (intern (symbol-name ans) "KEYWORD")
                          (cdr qt)))))
          (cond (temp
                 (pprogn
                  (acl2-query-simulate-interaction msg alist1 nil ans state)
                  (value (cadr temp))))
                (t (acl2-query1 id qt alist state)))))))
     ((eq dv t)
      (pprogn
       (acl2-query-simulate-interaction msg alist1 t (cadr qt) state)
       (value (caddr qt))))
     (t (let ((temp (assoc-keyword (if (consp dv) (car dv) dv) (cdr qt))))
          (cond
           ((null temp)
            (er soft 'acl2-query
                "The default response, ~x0, supplied in ~
                 ld-query-control-alist for the ~x1 query, is not one ~
                 of the expected responses.  The ~x1 query ~
                 is~%~%~@2~%~%Note the expected responses above.  See ~
                 :DOC ld-query-control-alist."
                (if (consp dv) (car dv) dv)
                id
                (cons msg alist1)))
           (t
            (pprogn
             (acl2-query-simulate-interaction msg alist1 t dv state)
             (value (cadr temp))))))))))

(defun acl2-query (id qt alist state)

; A query-tree qt is either an atom or a cons of the form
;   (str :k1 qt1 ... :kn qtn)
; where str is a string suitable for printing with ~@, each :ki is a
; keyword, and each qti is a query tree.  If qt is an atom, it is
; returned.  Otherwise, str is printed and the user is prompted for
; one of the keys.  When ki is typed, we recur on the corresponding
; qti.  Note that the user need not type a keyword, just a symbol
; whose symbol-name is that of one of the keywords.

; Thus, '("Do you want to redefine ~x0?" :y t :n nil) will print
; the question and require a simple y or n answer, returning t or nil
; as appropriate.

; Warning: We don't always actually read an answer!  We sometimes
; default.  Our behavior depends on the LD specials standard-co,
; standard-oi, and ld-query-control-alist, as follows.

; Let x be (cdr (assoc-eq id (ld-query-control-alist state))).  X must
; be either nil, a keyword, or a singleton list containing a keyword.
; If it is a keyword, then it must be one of the keys in (cdr qt) or
; else we cause an error.  If x is a keyword or a one-element list
; containing a keyword, we act as though we read that keyword as the
; answer to our query.  If x is nil, we read *standard-oi* for an
; answer.

; Now what about printing?  Where does the query actually appear?  If
; we get the answer from the control alist, then we print both the
; query and the answer to standard-co, making it simulate an
; interaction -- except, if the control alist gave us a singleton
; list, then we do not do any printing.  If we get the answer from
; *standard-oi* then we print the query to *standard-co*.  In
; addition, if we get the answer from *standard-oi* but *standard-co*
; is not standard-co, we simulate the interaction on standard-co.

  (cond ((atom qt) (value qt))
        ((not (and (or (stringp (car qt))
                       (and (consp (car qt))
                            (stringp (caar qt))))
                   (consp (cdr qt))
                   (keyword-value-listp (cdr qt))))
         (er soft 'acl2-query
             "The object ~x0 is not a query tree!  See the comment in ~
              acl2-query."
             qt))
        (t
         (er-let* ((qt1 (acl2-query1 id qt alist state)))
                  (acl2-query id qt1 alist state)))))

(defun brr-data-query (id state)
  (acl2-query
   id
   '("Attempt to present another result?"
     :y t :n nil
     :? ("reply with y to continue, or with n to quit"
         :y t :n nil))
   nil
   state))

(defun cw-gstack-for-term-fn (id subterm-p multiple tterm brr-data-lst alist
                                 state)

; Multiple is nil if only one result is to be considered.  Otherwise multiple
; is t at the top level and :more on recursive calls.

  (cond
   ((null brr-data-lst) (value (eq multiple :more)))
   (t (mv-let (earlier-d2 d-2 rest)
        (cw-gstack-for-term-fn1 subterm-p tterm brr-data-lst alist)
        (cond
         (d-2
          (progn$ (cw-gstack1 1
                              nil
                              (reverse (access brr-data-2 d-2 :gstack))
                              nil)
                  (let ((brr-result (access brr-data-2 d-2 :brr-result))
                        (earlier-brr-result (and earlier-d2
                                                 (access brr-data-2 earlier-d2
                                                         :brr-result))))
                    (cw "The resulting (translated) term is~|  ~
                         ~y0.~|~#1~[~/Note: The first lemma application above ~
                         that provides a suitable result is at frame ~x2, and ~
                         ~#3~[it's the same result as above.~/that result ~
                         is~|  ~y4.~]~]~|"
                        brr-result
                        (if earlier-d2 1 0)
                        (and earlier-d2
                             (length (access brr-data-2 earlier-d2 :gstack)))
                        (if (equal brr-result earlier-brr-result) 0 1)
                        earlier-brr-result))
                  (cond
                   ((not multiple) (value :quit))
                   (t
                    (er-let* ((action (if multiple
                                          (brr-data-query id state)
                                        (value nil))))
                      (cond
                       ((eq action t)
                        (cw-gstack-for-term-fn id subterm-p :more tterm rest
                                               alist state))
                       (t (value :quit))))))))
         (t (assert$ (null rest)
                     (value (eq multiple :more)))))))))

(defun cw-gstack-for-term*-fn (id subterm-p multiple uterm+ brr-data-lst state)
  (mv-let (vars uterm freep)
    (case-match uterm+
      ((':free vars uterm)
       (mv vars uterm t))
      (& (mv nil uterm+ nil)))
    (er-let* ((tterm (cond
                      ((and (consp uterm)
                            (eq (car uterm) :free))
                       (er soft id
                           "An input of the form (:FREE ..) must be of the ~
                            form (:FREE vars x).  The input ~x0 is thus ~
                            illegal.  See :DOC cw-gstack-for-term."
                           uterm))
                      (t (translate uterm t nil nil id (w state) state))))
              (alist (cond
                      ((not (arglistp vars))
                       (er soft id
                           "The first argument of :FREE must be a list of ~
                            distinct variables, but ~f0 is not.  See :DOC ~
                            cw-gstack-for-term."
                           vars))
                      ((not freep) (value :none))
                      (t (let ((all-vars (all-vars tterm)))
                           (cond
                            ((subsetp-eq vars all-vars)
                             (let ((bound-vars (set-difference-eq all-vars
                                                                  vars)))
                               (value (pairlis$ bound-vars bound-vars))))
                            (t (er soft id
                                   "For a :FREE expression, each specified ~
                                    variable must occur in the specified ~
                                    term.  But ~&0 ~#0~[does~/do~] not occur ~
                                    in the term, ~x1.  See :DOC ~
                                    cw-gstack-for-term."
                                   (set-difference-eq vars all-vars)
                                   tterm)))))))
              (ans (cw-gstack-for-term-fn id subterm-p multiple tterm
                                          brr-data-lst alist state)))
      (prog2$ (cond ((eq ans t)
                     (cw "There are no more results.~|"))
                    ((eq ans nil)
                     (cw "There are no results.~|"))
                    (t ; (eq ans :quit)
                     nil))
              (value :invisible)))))

(defmacro cw-gstack-for-term* (uterm+ &key
                                      (global-var 'brr-data-lst))
  `(cw-gstack-for-term*-fn 'cw-gstack-for-term* nil t ',uterm+ (@ ,global-var)
                           state))

(defmacro cw-gstack-for-subterm* (uterm+ &key
                                         (global-var 'brr-data-lst))
  `(cw-gstack-for-term*-fn 'cw-gstack-for-subterm* t t ',uterm+ (@ ,global-var)
                           state))

(defmacro cw-gstack-for-term (uterm+ &key
                                     (global-var 'brr-data-lst))
  `(cw-gstack-for-term*-fn 'cw-gstack-for-term nil nil ',uterm+ (@ ,global-var)
                           state))

(defmacro cw-gstack-for-subterm (uterm+ &key
                                        (global-var 'brr-data-lst))
  `(cw-gstack-for-term*-fn 'cw-gstack-for-subterm t nil ',uterm+ (@ ,global-var)
                           state))

(defmacro set-brr-data-lst (global-var &optional (action ':observation))

; This sets the indicated global-var to the accumulated (and suitably reversed)
; list of accumulated brr-data records.

  (declare (xargs :guard (and (member-eq action '(:observation :error :silent))
                              global-var
                              (symbolp global-var))))
  `(er-let* ((x (brr-data-lst state))
             (y
              (cond
               ((null x)
                (case ,action
                  (:observation
                   (pprogn (observation nil
                                        "There is no brr-data available.")
                           (value nil)))
                  (:error
                   (er soft nil
                       "There is no brr-data available."))
                  (otherwise (value nil))))
               (t (value x)))))
     (pprogn (f-put-global ',global-var y state)
             (case ,action
               (:observation (observation nil
                                          "~x0 = ~x1"
                                          '(length (@ ,global-var))
                                          (len y)))
               (otherwise state))
             (value :invisible))))

; We now develop some of the code for an implementation of an idea put
; forward by Diederik Verkest, namely, that patterns should be allowed
; in :expand hints.

(defrec expand-hint
  ((equiv
    .
    alist) ; :none, a unify-subst or (:constants . unify-subst)
           ; where unify-subst is a partial substitution that must be
           ; extended by the match of pattern against the term being
           ; considered for expansion.  :None means an exact match
           ; is required. :Constants means the successful match must
           ; bind variables to themselves or to quoted evgs.
   .
   (pattern
    .
    ((rune ; nil for a lambda application
      .
      hyp) ; nil if there are no hypotheses of rule, else their conjunction
     .
     (lhs  ; left-hand side of rule, for matching against actual term
      .
      rhs)
     )))
  t)

(defun binds-to-constants-p (unify-subst)
  (cond ((endp unify-subst) t)
        (t (let ((pair (car unify-subst)))
             (and (or (eq (car pair) (cdr pair))
                      (quotep (cdr pair)))
                  (binds-to-constants-p (cdr unify-subst)))))))

(defun expand-permission-result1 (term expand-lst geneqv wrld)

; This is a generalized version of member-equal that asks whether expand-lst
; gives term permission to be expanded, as described in :DOC hints.  Here, term
; is a function application.  We return (mv new-term hyp unify-subst rune k),
; where if new-term is not nil, and assuming hyp if hyp is non-nil, then
; new-term is provably equal to the application of unify-subst to term and, if
; non-nil, rune justifies this equality.  If new-term is not nil then k is the
; length of the tail of expand-lst whose car justifies the expansion of
; new-term, but only if we want to remove that member of expand-lst for
; heuristic purposes; otherwise k is nil.  See expand-permission-result.

  (if expand-lst
      (let ((x (car expand-lst)))
        (cond ((eq x :lambdas)
               (cond ((flambda-applicationp term)
                      (mv (lambda-body (ffn-symb term))
                          nil
                          (pairlis$ (lambda-formals (ffn-symb term))
                                    (fargs term))
                          nil
                          nil))
                     (t (expand-permission-result1 term (cdr expand-lst) geneqv
                                                   wrld))))
              ((not (geneqv-refinementp (access expand-hint x :equiv)
                                        geneqv
                                        wrld))
               (expand-permission-result1 term (cdr expand-lst) geneqv wrld))
              (t (let* ((alist (access expand-hint x :alist))
                        (alist-none-p (eq alist :none))
                        (alist-constants-p (and (not alist-none-p)
                                                (eq (car alist) :constants)))
                        (alist (if alist-constants-p
                                   (cdr alist)
                                 alist)))
                   (mv-let
                    (flg unify-subst0)
                    (cond
                     (alist-none-p
                      (mv (equal (access expand-hint x :pattern) term) nil))
                     (t (one-way-unify1 (access expand-hint x :pattern)
                                        term
                                        alist)))
                    (let ((flg (and flg
                                    (if alist-constants-p

; We require that unify-subst0 bind each variable to itself or to a constant.
; See the long comment in filter-disabled-expand-terms for further discussion.

                                        (binds-to-constants-p unify-subst0)
                                      t))))
                      (cond
                       (flg
                        (mv-let
                         (flg unify-subst)
                         (one-way-unify (access expand-hint x :lhs) term)
                         (cond (flg
                                (mv (access expand-hint x :rhs)
                                    (access expand-hint x :hyp)
                                    unify-subst
                                    (access expand-hint x :rune)
                                    (and (or alist-none-p

; For the example in a comment in expand-permission-result, looping occurs if
; we do not remove the expand hint in the alist-constants-p case.  See the long
; comment in filter-disabled-expand-terms for further discussion.

                                             alist-constants-p)
                                         (length expand-lst))))
                               (t (expand-permission-result1
                                   term (cdr expand-lst) geneqv wrld)))))
                       (t (expand-permission-result1 term (cdr expand-lst)
                                                     geneqv wrld)))))))))
    (mv nil nil nil nil nil)))

(defun remove1-by-position (target-index lst acc)
  (declare (xargs :guard (and (true-listp lst)
                              (true-listp acc)
                              (natp target-index)
                              (< target-index (len lst)))))
  (cond
   ((zp target-index)
    (revappend acc (cdr lst)))
   (t (remove1-by-position (1- target-index) (cdr lst) (cons (car lst) acc)))))

(defun expand-permission-result (term rcnst geneqv wrld)

; This is a generalized version of member-equal that asks whether rcnst gives
; term permission to be expanded, as described in :DOC hints.  Here, term is a
; function application.  We return (mv new-term hyp unify-subst rune
; new-rcnst), where if new-term is not nil:

; - term is provably equal to the application of unify-subst to new-term, where
;   if hyp is non-nil then this is under the assumption of the application of
;   unify-subst to hyp,

; - if rune is non-nil, rune justifies the above claim; and

; - new-rcnst is either rcnst or an update of it that removes the reason for
;   expansion of term from the :expand-lst (see long comment below).

  (let ((expand-lst (access rewrite-constant rcnst :expand-lst)))
    (mv-let
     (new-term hyp unify-subst rune posn-from-end)
     (expand-permission-result1 term expand-lst geneqv wrld)
     (cond
      (posn-from-end

; In this case new-term is non-nil; so term will be expanded, and we want to
; remove the reason for this expansion in order to avoid looping.  The thm
; below did indeed cause a rewriting loop through Version_4.3.  (It is OK for
; it to fail, but not with looping.)

;   (defun first-nondecrease (lst)
;     (cond ((endp lst) nil)
;       ((endp (cdr lst)) (list (car lst)))
;       ((> (car lst) (cadr lst)) (list (car lst)))
;       (t (cons (car lst) (first-nondecrease (cdr lst))))))
;
;   (defun removeN (lst n)
;     (cond ((endp lst) nil)
;       ((zp n) lst)
;       (t (removeN (cdr lst) (1- n)))))
;
;   (defthm len-removen  ; Needed to admit next fn.  If you disable this
;     (implies (natp n)  ; lemma, the overflow no longer occurs.
;              (equal (len (removen lst n))
;                     (if (>= n (len lst))
;                         0
;                         (- (len lst) n)))))
;
;   (defun longest-nondecrease (lst)
;     (declare (xargs :measure (len lst)))
;     (if (or (endp lst) (not (true-listp lst))) nil
;         (let* ((first (first-nondecrease lst))
;            (n (len first)))
;       (let ((remain (longest-nondecrease (removeN lst n))))
;         (if (>= n (len remain)) first remain)))))
;
;   ; This is an arithmetic lemma that may seem benign.
;   (defthm equality-difference-hack
;     (implies (and (acl2-numberp x)
;                   (acl2-numberp y))
;              (equal (equal (+ x (- y)) x)
;                     (equal y 0))))
;
;   ; Loops:
;   (thm (implies (true-listp lst)
;                 (equal (equal (len (longest-nondecrease lst)) (len lst))
;                        (equal (longest-nondecrease lst) lst))))

       (assert$
        new-term
        (mv new-term hyp unify-subst rune
            (let ((expand-lst (access rewrite-constant rcnst :expand-lst)))
              (change rewrite-constant rcnst
                      :expand-lst
                      (remove1-by-position (- (length expand-lst)
                                              posn-from-end)
                                           expand-lst
                                           nil))))))
      (t (mv new-term hyp unify-subst rune rcnst))))))

(defun expand-permission-p (term rcnst geneqv wrld)

; Returns nil if we do not have permission from :expand hints to expand, else
; returns rcnst possibly updated by removing term from the :expand-lst field
; (see comments about that in expand-permission-result).  It may be more
; appropriate to use expand-permission-result instead.

  (mv-let (new-term hyp unify-subst rune new-rcnst)
          (expand-permission-result term rcnst geneqv wrld)
          (declare (ignore hyp unify-subst rune))
          (and new-term new-rcnst)))

(defun ev-fncall! (fn args state aok)

; This function is logically equivalent to ev-fncall.  However, it is
; much faster because it can only be used for certain fn and args: fn
; is a Common Lisp compliant function, not trafficking in stobjs,
; defined as a function in raw Lisp.  The args satisfy the guard of fn.

; Note that return-last is not defined as a function in raw Lisp, so fn should
; not be return-last.  That is also important so that we do not take the
; stobjs-out of return-last, which causes an error.

  (declare (xargs :guard
                  (let ((wrld (w state)))
                    (and (symbolp fn)
                         (not (eq fn 'return-last))
                         (function-symbolp fn wrld)
                         (all-nils (stobjs-in fn wrld))
                         (equal (stobjs-out fn wrld) '(nil))
                         (eq (symbol-class fn wrld)
                             :common-lisp-compliant)
                         (mv-let
                           (erp val latches)
                           (ev (guard fn nil wrld)
                               (pairlis$ (formals fn wrld)
                                         args)
                               state
                               nil
                               t
                               aok)
                           (assert$
                            (null latches)
                            (and (null erp)
                                 val)))))))
  #+(and (not acl2-loop-only) lucid)
  (declare (ignore state))
  #-acl2-loop-only
  (return-from ev-fncall!
               (mv nil (apply fn args) nil))
  (ev-fncall fn args
             nil ; irrelevant arg-exprs (as latches is nil)
             state
             nil ; latches

; Since ev-fncall-meta calls ev-fncall!, the comment about sys-call under
; ev-fncall-meta explains why the following argument of nil is important.

             nil aok))

(defun ev-fncall-meta (fn args state)
  (declare (xargs :guard
                  (and (symbolp fn)
                       (function-symbolp fn (w state)))))

; Fn is a metafunction and args is its list of arguments.  Extended
; metafunctions have three arguments, term, mfc, and state.  Thanks to the
; power of coerce-state-to-object, we actually find the live state in args.
; The args of a vanilla metafunction is just the list containing the term.  Our
; first interest below is to bind the Lisp special *metafunction-context* to
; the context if we are calling an extended metafunction.  This will allow the
; metafunction's subroutines to authenticate their arguments.  We assume that
; the context was correctly constructed by our caller, e.g., rewrite.  Our
; second concern is to avoid guard checking if possible.

  (let (#-acl2-loop-only
        (*metafunction-context* (if (cdr args) (cadr args) nil))
        )
    (cond ((eq (symbol-class fn (w state))
               :common-lisp-compliant)

; Since the guard of the meta function fn is implied by pseudo-termp of its
; arg, and since fn is only applied to terms by our meta facility, and finally
; because we check that fn does not traffic in stobjs (see
; chk-acceptable-meta-rule), we know that it is safe to call the raw Lisp
; version of fn.

; See chk-evaluator-use-in-rule for a discussion of how we restrict the use of
; evaluators in rules of class :meta or :clause-processor, so that we can use
; aok = t in the calls of ev-fncall! and ev-fncall just below.

           (ev-fncall! fn args state t))
          (t (ev-fncall fn args
                        nil ; irrelevant arg-exprs (as latches is nil)
                        state
                        nil ; latches

; The next argument, hard-error-returns-nilp, is nil.  Think hard before
; changing it!  For example, it guarantees that if a metafunction invokes
; sys-call, then the call (er hard ...) under sys-call will cause an error that
; the user can see (and react to).

                        nil t)))))

(defun ev-synp (synp-term unify-subst mfc state)

; Synp-term is the quotation of the term to be evaluated.  Unify-subst is the
; unifying substitution presently in force, and mfc is the meta-level context
; (formerly referred to as "metafunction-context").  This function has been
; modeled (weakly) on ev-fncall-meta.

; This call to synp is the result of the macro-expansion of a syntaxp or
; bind-free hypothesis.  Or at least it might as well be; we check in
; bad-synp-hyp-msg (called in chk-acceptable-rewrite-rule2) that synp-term has
; a form that we know how to handle.

  (let* (#-acl2-loop-only
         (*metafunction-context* mfc)
         (unify-subst1 (if mfc
                           (cons (cons 'mfc mfc)
                                 unify-subst)
                         unify-subst))
         (unify-subst2 (if mfc
                           (cons (cons 'state (coerce-state-to-object state))
                                 unify-subst1)
                         unify-subst)))

; It is tempting to bind the state global safe-mode to t here, using
; state-global-let*.  However, we cannot do that without returning state, which
; we want to avoid since the caller, relieve-hyp, does not return state.  Since
; synp is only used heuristically, it really isn't necessary to use safe mode,
; although it would have been nice for avoiding hard errors (e.g., from car of
; a non-nil atom).

    (ev (get-evg synp-term 'ev-synp) unify-subst2 state nil t t)))

(defun bad-synp-alist1 (alist unify-subst vars-to-be-bound wrld)

; We return nil if the alist is legal, else a string or message suitable for
; printing with ~@.

  (declare (xargs :guard (alistp alist)))
  (if (null alist)
      nil
    (or (let ((key (caar alist))
              (value (cdar alist)))
          (cond ((not (legal-variablep key))
                 (msg "the key ~x0 is not a legal variable" key))
                ((assoc-eq key unify-subst)
                 (msg "the key ~x0 is already bound in the unifying ~
                       substitution, ~x1"
                      key
                      unify-subst))
                ((not (termp value wrld))
                 (msg "the value ~x0 bound to key ~x1 is not a legal term ~
                       (translated into ACL2 internal form) in the current ~
                       ACL2 world"
                      value key))
                ((and (not (eq vars-to-be-bound t))
                      (not (member-eq key vars-to-be-bound)))
                 (msg "the key ~x0 is not a member of the specified list of ~
                       variables to be bound, ~x1"
                      key vars-to-be-bound))
                (t nil)))
        (bad-synp-alist1 (cdr alist) unify-subst vars-to-be-bound wrld))))

(defun bad-synp-alist1-lst (alist-lst unify-subst vars-to-be-bound wrld)
  (cond
   ((endp alist-lst) nil)
   (t (or (bad-synp-alist1 (car alist-lst) unify-subst vars-to-be-bound wrld)
          (bad-synp-alist1-lst (cdr alist-lst) unify-subst vars-to-be-bound
                               wrld)))))

(defun bind-free-info (x unify-subst vars-to-be-bound wrld)

; X is a value returned by a bind-free synp hypothesis, known not to be t or
; nil; unify-subst is an alist containing the unifying substitution gathered so
; far; and vars-to-be-bound is either t or a quoted list of variables.  We
; check that alist is indeed an alist, that it does not bind any variables
; already bound in unify-subst, and that it only binds variables to ACL2 terms.
; If vars-to-be-bound is anything other than t, we also require that alist only
; binds vars present in vars-to-be-bound.

; We return nil if x is a legal alist, t if x is a legal list of alists, and
; otherwise a string or message suitable for printing with ~@.

  (cond
   ((and (true-listp x)
         (alistp (car x)))
    (or (bad-synp-alist1-lst x
                             unify-subst
                             (get-evg vars-to-be-bound 'bad-synp-alist)
                             wrld)
        t))
   ((alistp x)
    (bad-synp-alist1 x
                     unify-subst
                     (get-evg vars-to-be-bound 'bad-synp-alist)
                     wrld))
   (t "it is not an alist")))

(defun evgs-or-t (lst alist)

; Consider the result, lst', of substituting alist into the list of
; terms, lst.  Is every term in lst' a quoted constant?  (For example,
; lst might be (x '23) and alist might be '((x . '7) (y . a)), in
; which case, the answer is "yes, they're all quoted constants.")  If
; so, we return the true-list containing the evgs of the elements of
; lst'; else we return t.

  (cond ((endp lst) nil)
        ((variablep (car lst))
         (let ((temp (assoc-eq (car lst) alist)))
           (if (and temp (quotep (cdr temp)))
               (let ((rest (evgs-or-t (cdr lst) alist)))
                 (cond ((eq rest t) t)
                       (t (cons (cadr (cdr temp)) rest))))
             t)))
        ((fquotep (car lst))
         (let ((rest (evgs-or-t (cdr lst) alist)))
           (cond ((eq rest t) t)
                 (t (cons (cadr (car lst)) rest)))))
        (t t)))

; Essay on Correctness of Meta Reasoning

; Below, we sketch a proof of a theorem asserting the correctness of ACL2's
; meta reasoning, starting with meta rules and then handling clause processor
; rules.  We state correctness for extended metafunctions, but correctness for
; ordinary metafunctions follows trivially by adding mfc and state as ignored
; arguments.  We assume a call of hyp-fn in the meta rule, but of course this
; too is fully general; just define hyp-fn to return 't if it is not already
; present.  We also assume that the metatheorem includes hypotheses of
; (pseudo-termp term) and (alistp a), but of course the metatheorem then
; applies if it omits these hypotheses -- just weaken it by adding them back
; in!  And of course, the mention of meta-extract-hyps is harmless if there are
; no meta-extract hypotheses; in that case, meta-extract-hyps is the empty
; conjunction.

; At the end of this Essay are two appendices, both pertaining to transparent
; functions.  The first explains how our correctness argument can be made to
; accommodate transparent functions.  The second discusses how the
; implementation accommodates transparent functions.

; For the discussion below of attachments, it might be helpful to look at the
; Essay on Defattach and perhaps also the Essay on Merging Attachment Records.

; Let *mfc* be a metafunction context, and let {*mfc*} denote the formula
; asserting the validity of *mfc*, as based on its type-alist.  For example, if
; *mfc* has only one entry in its type-alist, and that entry binds (foo x) to
; (ts-complement *ts-integer*), then {*mfc*} is (not (integerp (foo x))).  For
; notational convenience, we write "ev" below for an evaluator function symbol
; (which thus is definitely not the predefined ACL2 ev function!).

; Recall the ancestor relation: the transitive-reflexive closure of the
; relation "g is an immediate ancestor of f" generated by pairs <f,g> where g
; occurs in the axiom that introduces f.  Note that attachments are not
; considered for this relation.

; Theorem.  Suppose that the following is a theorem, where the only axioms for
; ev are evaluator axioms; where term, a, mfc, and state are variables with
; those exact names (clearly this theorem then generalizes to more arbitrary
; variables); and where META-EXTRACT-HYPS is explained below.

;   (implies (and (pseudo-termp term)
;                 (alistp a)
;                 META-EXTRACT-HYPS ; see below
;                 (ev (hyp-fn term mfc state) a))
;            (equal (ev term a)
;                   (ev (meta-fn term mfc state) a)))

; Suppose in addition that LHS, HYP, and RHS are terms, and that in an
; environment where term is bound to 'LHS, mfc is bound to *mfc* (the current
; metafunction context), and state is bound to the live ACL2 state, the
; following conditions hold, where evaluation may use attachments.

;   (hyp-fn term mfc state) evaluates to 'HYP;
;   (meta-fn term mfc state) evaluates to 'RHS; and
;   META-EXTRACT-HYPS is a conjunction of meta-extract hypotheses,
;     as recognized by remove-meta-extract-contextual-hyps and
;     remove-meta-extract-global-hyps

; Let EXTRA-FNS be a set of 0, 1, or 2 symbols consisting of
; meta-extract-contextual-fact, meta-extract-global-fact+, or both, according
; to which have top-level calls among META-EXTRACT-HYPS.

; Finally, assume the following: ev is not ancestral in any defaxiom or in
; EXTRA-FNS; no ancestor of ev or EXTRA-FNS with an attachment is ancestral in
; meta-fn or hyp-fn; and no ancestor of any defaxiom has an attachment.  (See
; chk-evaluator-use-in-rule for enforcement.  See the example towards the end
; of :DOC evaluator-restrictions for necessity of ruling out functions that are
; "both ancestral in the evaluator and also ancestral in the meta or
; clause-processor functions."  Also see the Concluding Remark below about
; allowing an attachment to ev even if it is ancestral in meta-fn or hyp-fn.)

; Then the following is a theorem of (mfc-world *mfc*), or equivalently (since
; the worlds have the same logical theory), (w *the-live-state*):

;   (implies (and {*mfc*}
;                 HYP)
;            (equal LHS RHS)).

; The proof of the theorem above uses the following lemma.

; Evaluator Elimination Lemma.  Assume that u is a term, ev is an evaluator for
; the function symbols in u, and a0 is a term of the form (list (cons 'v1 t1)
; ... (cons 'vn tn)) where (v1 ... vn) includes all variables occurring free in
; u and each ti is a term.  Let s be the substitution mapping vi to ti (1 <= i
; <= n).  Then the following is a theorem:

;   (ev 'u a0) = u/s

; Proof:  An easy induction on the structure of term u.  Q.E.D.

; As a warmup, we first prove the theorem in the special case that
; META-EXTRACT-HYPS is the empty conjunction and there are no attachments
; involved.  Let (v1 .. vn) be the variables occurring free in lhs, rhs, or
; hyp.  Let A0 be the term

;   (list (cons 'v1 v1) ... (cons 'vn vn)).

; We instantiate the assumed theorem

;   (implies (and (pseudo-termp term)
;                 (alistp a)
;                 (ev (hyp-fn term mfc state) a))
;            (equal (ev term a) (ev (meta-fn term mfc state) a)))

; replacing term by 'LHS, a by A0, mfc by *mfc*, and state by the live state,
; to obtain the following.

;   (implies (and (pseudo-termp 'LHS)
;                 (alistp A0)
;                 (ev (hyp-fn 'LHS *mfc* *the-live-state*) A0))
;            (equal (ev 'LHS A0)
;                   (ev (meta-fn 'LHS *mfc* *the-live-state*) A0)))

; which is provably equal, by computation, to the following (assuming no
; attachments are used in the computation; we consider attachments later):

;   (implies (ev 'HYP A0)
;            (equal (ev 'LHS A0) (ev 'RHS A0)))

; By functional instantiation, we may replace ev in the hypotheses of this
; theorem by an "extended" evaluator for a set of function symbols including
; all those that occur in hyp, lhs, or rhs.  (A long comment in
; defaxiom-supporters justifies this use of functional instantiation.)  Then by
; the Evaluator Elimination Lemma the formula above simplifies to

;   (implies HYP
;            (equal LHS RHS))

; as desired.

; We next consider the general case, where there may be meta-extract hypotheses
; and attachments may be used.  To start, note that the following is a theorem,
; as it results from the assumed theorem by strengthening hypotheses.  (Here we
; write obj1, obj2, st, and aa for variables not occurring elsewhere in the
; formula.)

;   (implies
;    (and (pseudo-termp term)
;         (alistp a)
;         (forall (obj1)
;                 (ev (meta-extract-contextual-fact obj1 mfc state) a))
;         (forall (obj2 st2 aa)
;                 (ev (meta-extract-global-fact+ obj2 st2 state) aa))
;         (ev (hyp-fn term mfc state) a))
;    (equal (ev term a) (ev (meta-fn term mfc state) a)))

; We instantiate as before, to obtain:

; (1)  (implies
;       (and (pseudo-termp 'LHS)
;            (alistp A0)
;            (forall (obj1)
;             (ev (meta-extract-contextual-fact obj1 *mfc* *the-live-state*)
;                 A0))
;            (forall (obj2 st2 aa)
;             (ev (meta-extract-global-fact+ obj2 st2 *the-live-state*) aa))
;            (ev (hyp-fn 'LHS *mfc* *the-live-state*) A0))
;       (equal (ev 'LHS A0)
;              (ev (meta-fn 'LHS *mfc* *the-live-state*) A0)))

; As before, this reduces by computation to the following formula.

; (2)  (implies
;       (and (forall (obj1)
;             (ev (meta-extract-contextual-fact obj1 *mfc* *the-live-state*)
;                 A0))
;            (forall (obj2 st2 aa)
;             (ev (meta-extract-global-fact+ obj2 st2 *the-live-state*) aa))
;            (ev 'hyp A0))
;       (equal (ev 'LHS A0) (ev 'RHS A0)))

; However, attachments may have been used in evaluating these calls of hyp-fn
; and meta-fn.  So at this point, we know only that (2) is a theorem of the
; evaluation theory.  Our intuition, however, is that the attachments can
; somehow be renamed in an extension of the world so that they don't interfere
; with ev or EXTRA-FNS, which can allow us to conclude by a conservativity
; argument that (2) is a theorem of the current world.  We use that intuition
; to prove the following claim.  We thank Sol Swords for a key observation
; leading to the specific notion of "green" just below, which enabled us to
; complete this proof.

; Claim: (2) is a theorem of the current world.

; Proof of Claim.  We replicate the current world by renaming each function
; symbol for which some ancestor has an attachment.  For convenience, we view
; each function symbol f in the original world, W0, as "red"; and if f is
; renamed to a function symbol f', then f' is "green", the "green version of"
; f.

; Let W1 be the world isomorphic to W0 that results from applying this renaming
; to the existing world, W0.  For a function symbol f in W0, we refer to its
; "W1 version" as the corresponding green function symbol in W1 if such exists
; (that is, if f has an ancestor in W0 with an attachment), else as f itself.
; The notion of "green" in W1 is clearly "closed upward": if g' is green and
; its corresponding red function in W0 is an ancestor of function f in W0, then
; f is renamed to a green version in W1.  Note that every defaxiom event
; consists entirely of red functions since, by hypothesis, no ancestor of any
; defaxiom has an attachment.

; Let W0- be the result of removing defattach events from W0.  Now imagine
; including books for both worlds W0- and W1 to obtain a world W.  Thus, W
; incorporates both W0 without defattach events and W1 with defattach events,
; where every function with an attachment is green.  These worlds are
; compatible because if the axiom in W1 introducing a function symbol f has any
; call of a green function symbol, then f is green by the "closed upward"
; property mentioned above; thus every axiom in W1 introducing a red function
; symbol is redundant with (indeed, identical to) its axiom in W0.

; Let (1') be the result of replacing hyp-fn and meta-fn in W0 with their W1
; versions, hyp-fn' and meta-fn'.  We next show that (1') is a theorem of W.
; First note that since (1) is a theorem of W0 and hence of W0- (since W0- and
; W0 have the same theory, even though their evaluation theories may differ),
; then (1) is a theorem of the extension W of W0-.  We next show that (1') also
; holds in W, using functional instantiation.  Let fs be the functional
; substitution that contains, for every green ancestor f' of hyp-fn' or
; meta-fn', the pair <f,f'> where f is the red version of f'.  Note that ev is
; not in the domain of fs, since otherwise ev would have a green version and
; hence ev would have an ancestor f with an attachment that is also an ancestor
; of hyp-fn or meta-fn, a contradiction.  Thus (1') is the result of applying
; fs to (1), perhaps after replacing green pseudo-termp and/or alistp by the
; provably equal corresponding red function (since fully-defined functions are
; provably unique).  So for (1') to hold in W by functional instantiation of
; (1), we need only show that fs is a valid functional substitution for (1) in
; W.  Recall this comment in relevant-constraints, specifying which formulas
; need to remain theorems when fs is applied to them.

; The relevant theorems are the set of all terms, term, such that
;   (a) term mentions some function symbol in the domain of alist,
;   AND
;   (b) either
;      (i) term arises from a definition of or constraint on a function symbol
;          ancestral either in thm or in some defaxiom,
;       OR
;      (ii) term is the body of a defaxiom.

; In this case, the terms satisfying (b) are the axioms that introduce
; ancestors of defaxioms or of hyp-fn, meta-fn, ev, EXTRA-FNS, alistp, or
; pseudo-termp.  We need only consider those that also satisfy (a).  By
; hypothesis no defaxiom has any ancestor with an attachment, so since every
; function symbol in the domain of fs has an attachment, we may ignore
; defaxioms in (i)(b) and (ii).  We also ignore alistp and pseudo-termp since
; they and their ancestors are fully defined, hence with provably equal red and
; green functions.  Any axiom introducing an ancestor f of hyp-fn or meta-fn
; clearly is either left alone by fs or else is mapped to the axiom introducing
; the green version of f.  The validation of fs is concluded by showing that
; the axiom introducing an arbitrary ancestor f of ev or EXTRA-FNS mentions no
; symbol in the domain of fs.  Suppose to the contrary that g is such a symbol;
; then since g has a green version, there is an ancestor h of g such that h has
; an attachment.  But then h is a common ancestor of ev or EXTRA-FNS and also
; of either hyp-fn or meta-fn, contradicting the hypothesis that no such common
; ancestor has an attachment.

; By the Evaluation History Theorem in the Essay on Defattach, there is a world
; W' whose theory is the evaluation theory of W.  (That theorem assumes that
; only encapsulated functions get attachments, but that's immaterial since we
; can always logically replace a defun by an encapsulate that exports the
; corresponding definition rule.)  Clearly any call of hyp-fn or meta-fn that
; completes in W0 with attachments gives the same result as the corresponding
; call of its W1 version in W1 with attachments, hence in W with attachments.
; So each such call and result are provably equal in W with attachments, hence
; in W'.  Therefore, just as (2) followed from (1) in our earlier "warmup"
; argument, (2) follows from (1') in W'.  Let W2 be the world obtained by
; restricting W' to the set of ancestors of at least one of the (red) functions
; ev, EXTRA-FNS, alistp, and pseudo-termp, and all defaxioms.  As usual the
; theory of W' conservatively extends the theory of W2: both are worlds and W2
; contains all defaxioms.  So (2) is a theorem of W2.  But W2 is contained in
; W0, since W2 consists entirely of red functions by the "closed upward"
; property for green functions.  Therefore (2) is a theorem of W0.

; That completes the proof of the Claim.  Thus (2) is a theorem of the current
; world, and we justifiably ignore attachments for the remainder of this
; discussion.

; Now we functionally instantiate (2).  We do so as in the earlier "warmup"
; argument (which was made without considering attachments), this time after
; introducing an evaluator ev' that includes all currently known function
; symbols, thus obtaining a world w' extending the current logical world, w.

;   (implies
;    (and (forall (obj1)
;          (ev' (meta-extract-contextual-fact obj1 *mfc* *the-live-state*)
;               A0))
;         (forall (obj2 st2 aa)
;          (ev' (meta-extract-global-fact+ obj2 st2 *the-live-state*) aa))
;         (ev' 'HYP A0))
;    (equal (ev' 'LHS A0) (ev' 'RHS A0)))

; As before, the Evaluator Elimination Lemma yields that the following is a
; theorem of w'.

;   (implies
;    (and (forall (obj1)
;          (ev' (meta-extract-contextual-fact obj1 *mfc* *the-live-state*)
;               A0))
;         (forall (obj2 st2 aa)
;          (ev' (meta-extract-global-fact+ obj2 st2 *the-live-state*) aa))
;         HYP)
;    (equal LHS RHS))

; Thus, it remains only to modify the rest of the earlier "warmup" argument by
; dealing with the two universally quantified hypotheses.

; Our first step is to show that the second universally quantified hypothesis,
; where we may as well ignore the forall quantifier, is a theorem of w'.  Let
; term0 be the value returned by (meta-extract-global-fact+ obj2 st2
; *the-live-state*).  Since (ev' *t* aa) is provably equal to *t*, let us
; assume without loss of generality that term0 is not *t*, .  The first case we
; consider is that obj2 is not of the form (:FNCALL fn arglist).  Then we
; claim, without proof (but by appeal to plausibility!), that term0 is provably
; a member of the finite list ('THM1 'THM2 ...), where (THM1 THM2 ...)
; enumerates the theorems of w that can be returned by rewrite-rule-term,
; linear-lemma-term, and meta-extract-formula when called by
; meta-extract-global-fact+.  We thus need to show that for each member 'THM of
; this list, (ev' 'THM aa) is a theorem of w'.  By the (argument of the)
; Evaluator Elimination Lemma, (ev' 'THM aa) is provably equal to the instance
; of THM obtained by replacing each variable x by the term (cdr (assoc 'x aa)).
; Since THM is a theorem of w and hence w', so is this instance.  It remains to
; consider the other case, i.e., to show that for obj2 = (:FNCALL fn arglist),
; (ev' term0 aa) is a theorem of w'.  Since we are assuming that term0 is not
; *t*, we know that (w st2) = (w *the-live-state*), which is w, and we also
; know (by inspection of the definition of fncall-term) that term0 =
; (fncall-term fn arglist st2) for a logic-mode function symbol fn of w whose
; input arity is the length of arglist.  But (fncall-term fn arglist st2) is
; the term (equal (fn . arglist) 'val) where (magic-ev-fncall fn arglist st2
; ...) = (mv nil val).  We arrange that magic-ev-fncall has
; unknown-constraints, but we conceive of it as being axiomatized using
; clocked, logic mode definitions that follow the definitions supporting
; ev-fncall -- in particular, a clocked, logic-mode version of
; ev-fncall-rec-logical -- such that (mv t nil) is returned when the clock
; expires.  (All of those functions are conceptually in the ground-zero theory,
; but they need not be defined in the ACL2 system implementation.)  Then the
; top-level recursive function is called with a clock that is greater than all
; clocks that would ever be needed for termination under this story for actual
; calls made.  Thus, for every input term, the value returned by ev-fncall is
; provably equal to the value returned by magic-ev-fncall.

; Thus, we now know that the following is a theorem of w':

; (*)
;   (implies
;    (and (forall (obj1)
;          (ev' (meta-extract-contextual-fact obj1 *mfc* *the-live-state*)
;               A0))
;         HYP)
;    (equal LHS RHS))

; Recall that we are trying to show that the following is a theorem of w.

;   (implies
;    (and {*mfc*}
;         HYP)
;    (equal LHS RHS))

; Since the introduction of ev' makes w' a conservative extension of w, it
; suffices to show that the formula just above is a theorem of w'.  Since (*)
; has been shown to be a theorem of w', then it suffices to show that the
; following is a theorem of w'.

; (+)
;   (implies
;    {*mfc*}
;    (forall (obj1)
;     (ev' (meta-extract-contextual-fact obj1 *mfc* *the-live-state*) A0)))

; But we now argue that this is indeed a theorem.  Informally, we think of it
; as a way to formalize the spec for meta-extract-contextual-fact: that it only
; produces terms that evaluate to true.  To see why (+) is a theorem, we focus
; on the case that obj has the form (:rw term obj nil).  Then the above call of
; meta-extract-contextual-fact is equal to a term of the form (equal lhs0
; rhs0), where rhs0 is the result of applying mfc-rw-fn to lhs0, *mfc*, and a
; state whose world is w, the world of *mfc*.  The key is that in such a case,
; mfc-rw-fn rewrites a term to one that is equal to it with respect to the
; hypotheses of *mfc* including its world, w.  A little more precisely, we
; arrange that mfc-rw-fn -- and mfc-ts-fn, and so on -- all have
; unknown-constraints, but we conceive of those constraints as coming from
; clocked, logic mode versions of corresponding prover routines.  For example,
; we conceive of the definition of mfc-rw-fn as following the definition of
; rewrite, but with a clock and using analogous logic-mode supporting functions
; (just as discussed above for magic-ev-fncall), so that the original term is
; returned if the clock expires.  That clock has an initial value that is
; greater than all clocks that could be needed for termination in support of
; all calls ever actually made, in the sense of this story.  This approach
; guarantees that any value computed by rewrite can be legitimately used as a
; value returned by mfc-rw-fn; that is, the returned value is provably equal to
; the call of mfc-rw-fn on its inputs.  But by the (conceived) definition of
; mfc-rw-fn as a logic mode function, the proof obligations pertaining to
; mfc-rw-fn for (+) are provable.  By extending this argument to other mfc-
; functions, we see that (+) is a theorem.

; It remains to modify the arguments above in the case of clause-processors.
; The terms in META-EXTRACT-HYPS are then all calls of
; meta-extract-global-fact+, not meta-extract-contextual-fact.  The argument
; then proceeds in analogy to how it went before, thus for example replacing
; (ev' 'HYP A0) by (forall aa (ev' 'CLAUSES-RESULT aa)), where CLAUSES-RESULT
; is the formal conjunction of the (disjunctions of the) clauses returned by
; the clause-processor.  This hypothesis is a theorem (by the Evaluator
; Elimination Lemma), however, because by hypothesis, these clauses are all
; theorems.

; (Comment added by Matt January 2023.  It's no longer clear to me that we need
; to collect guards as described in the next paragraphs: the "in essence
; proved" remark below looks good enough at the moment!  But we have been
; collecting ancestors of guards for quite some time without obvious ill
; effect, so we take the safe approach of continuing to do so.  If this
; decision is revisited, also think about the effect that has on the use of
; canonical-ancestors in ext-ancestors-attachments1.)

; We remark briefly on the relation between guards and ancestors in our
; criterion for using attachments in meta-level reasoning.  Above, we argue
; that we can restrict to attachments to functions ancestral in metafunctions
; or clause-processors.  But how do we know that evaluation produces theorems
; in the resulting evaluation history?  If raw-Lisp functions installed by ACL2
; involve mbe, then we need to know that their guards hold.  Thus we need to
; know that the guard proof obligation holds when a function is calling its
; attachment.  This was in essence proved when the defattach event was
; admitted, but after applying the entire functional substitution of that
; event.  Thus, we include guards in our notion of ancestor so that this guard
; obligation clearly holds; see the calls of canonical-ancestors-lst in
; function chk-evaluator-use-in-rule.

; So, we enrich the notion of ancestor to include guards.  However, we can
; weaken our notion of ancestor to avoid the next-to-last argument of
; return-last, except when it is used to implement mbe (see function
; canonical-ffn-symbs).  This weakening was inspired by an example sent to us
; by Sol Swords, who derived it from his own experience, and is justified by
; imagining that all such calls of return-last are expanded away before storing
; events.  The parameter rlp passed to our functions is true when this special
; handling of return-last is to be performed.

; Concluding Remark.  Sol Swords observes that the restrictions in the Theorem
; above may be weakened to allow attachments ev* and ev*-lst to ev and ev-lst
; even if ev is ancestral in meta-fn or hyp-fn, provided ev* and ev*-lst are an
; evaluator pair and that neither they nor EXTRA-FNS have any ancestral
; attachments.  (He also notes that these attachments need not be direct: they
; can be by way of a chain of attachments.)  He sketches the following
; modification of the argument above.  As before we derive (2) in the
; evaluation theory, by reducing (1) using evaluation.  Let (2*) be the result
; of replacing ev by ev* in (2); then since ev and ev* are provably equal in
; the evaluation theory, (2*) also holds there.  Since (2*) has no functions
; with ancestral attachments, it holds in the current world by the usual
; conservativity argument, as before.  Finally, complete the argument (the part
; after the Claim) as before, replacing ev by ev*; here we use the fact that
; ev* is an evaluator.

; We turn now to the two appendices promised above, regarding foundations and
; implementation for transparent functions.  We thank Sol Swords for suggesting
; (and naming) the notion of transparent functions and sketching a correctness
; argument, and we thank Mertcan Temel for putting forward a problem with the
; restriction on common ancestors that was inhibiting progress on community
; book books/projects/rp-rewriter/cl-correct.isp.  That restriction pertains to
; common ancestors of meta functions and evaluators; transparent functions
; modify the notion of ancestor for meta functions in a way that can overcome
; that restriction.

; Appendix 1: Correctness of Meta Reasoning with Transparent Functions

; The following extension of the Essay on Correctness of Meta Reasoning is
; rooted in a communication from Sol Swords that included the basic correctness
; argument.  That communication, on 1/5/2023, introduced the notion of
; "transparent" function.  For relevant background see the Essay above and see
; :DOC evaluator-restrictions and :DOC transparent-functions.

; Let ev be our evaluator and let meta-fn our meta function; a similar
; argument, omitted here, works for clause-processors.  As in the Essay above,
; we know that

; (1) (equal (ev 'LHS A0)
;            (ev (meta-fn 'LHS) A0))

; is a theorem of the base theory of the current world (what is sometimes
; called the "current theory"; that is, the theory used by the prover, not the
; evaluation theory).

; (2) (equal (ev 'LHS A0)
;            (ev 'RHS A0))

; is a theorem in the evaluation theory, where (meta-fn 'LHS) computes to 'RHS.
; We want to show that (2) is a theorem of the base theory.

; Certain constrained functions are introduced as "transparent".  However, in
; this Appendix we will only consider a function to be transparent if it has an
; attachment in the current world (denoted W0 below).  The restrictions in
; Sub-Appendix 1.1 below guarantee that if any function introduced in the
; signature of a given encapsulate is transparent with an attachment, then they
; all are.

; A key notion is the "modified extended-ancestor" relation.  It is obtained
; from the ordinary ancestor relation by modifying the ordinary immediate
; ancestor relation for any transparent function f, so that f has only its
; attachment as an immediate modified extended-ancestor (thus ignoring the
; constraints on f).

; Remarks.  1. As noted in the Essay on Merging Attachment Records, the usual
; extended-ancestor relation collects both the attachment and the functions
; called in the constraint.  The terminology "modified" above suggests that for
; transparent functions, we are collecting only the attachment.  2. The two
; ancestor relations (modified extended-ancestor and ordinary ancestor) are
; based on "siblings"; see Sub-Appendix 1.1.

; We define the following worlds.  See Sub-Appendix 1.2 for why these world
; constructions are valid.

; W0:  the current world, which may have attachments
; W0-: like W0, but only retaining attachments to functions that both
;      are transparent and are modified extended-ancestors of meta-fn
; W1-: like W0- except that for each attachment pair <f,g> of W0-, that
;      attachment is removed, but also the constraint on f is eliminated
;      in favor of defining f = g
; W1:  same base theory as W1-, but this world includes all defattach
;      events that were eliminated when forming W0-

; Here is a key guarantee on W0, checked by ACL2 (function
; chk-evaluator-use-in-rule).

;   (G0) For W0, no function symbol satisfies the following three properties:
;         has an attachment, is a modified extended-ancestor of meta-fn, and is
;         an ordinary ancestor of ev.

; Next note the following property of W0 and W1, followed by a proof sketch.

;   (Anc) If f1 is an ordinary ancestor of f2 in W1, then f1 is a modified
;         extended-ancestor of f2 in W0.

; Note first that either f2 has the same ordinary immediate ancestors in W1 as
; in W0, or else f2 is transparent and has its attachment as its unique
; ordinary ancestor; either way, (Anc) holds if f1 is an ordinary immediate
; ancestor of f2 in W1.  Then (Anc) follows by an induction on the closure of
; the ordinary immediate ancestor relation.

; Our next observation is also critical; a proof sketch follows, essentially by
; induction on the distance of an ancestor from ev.

;   (E01) Every ordinary ancestor of ev in W1 is an ordinary ancestor of ev in
;         W0.

; Let's say that a "W1-ancestor path from ev" is a path starting with ev, such
; that every link satisfies the (ordinary) immediate ancestor relation of W1.
; We prove by induction on n that every W1-ancestor path from ev consists of
; ordinary ancestors of ev in W0.  The base case is obvious, since ev is an
; ordinary ancestor of itself in W0.  It remains to show that if f is an
; ordinary ancestor of ev in W0 and g is an ordinary immediate ancestor of f in
; W1, then g is an ordinary ancestor of f in W0.  It suffices that f has the
; same defining event in W1 as in W0.  But by definition of W1 (and W0- and
; W1-), the only way that can fail is if f is transparent (hence, has an
; attachment) and f is a modified extended-ancestor of meta-fn in W0; but that
; is a violation of (G0).

; The following is proved by an inductive argument similar to the one
; just above.  The only difference is that in the last step, f may be
; transparent; but this is fine by definition of the modified
; extended-ancestor relation of W0.

;   (M01) Every ordinary ancestor of meta-fn in W1 is a modified
;         extended-ancestor of meta-fn in W0.

; The next property is key, and follows immediately from (G0), (E01), (M01),
; and the fact that every attachment of W1 is an attachment of W0.

;   (G1)  For W1, no function symbol satisfies the following three properties:
;         has an attachment, is an ordinary ancestor of meta-fn, and is an
;         ordinary ancestor of ev.

; Recall that (2) is theorem of the evaluation theory of W0.  We are finally
; ready to argue that (2) is a theorem of the base theory of W0.

; - (2) is a theorem of the evaluation theory of W1 since that is the same as
;   the evaluation theory as W0.

; - Let H be the history contained in W1 obtained by closing under ordinary
;   ancestors of ev in W1.  Thus the base theory of W1 is a conservative
;   extension of the theory of H.

; - By (G1), together with applying to W1 the main result of the Essay on
;   Correctness of Meta Reasoning, (2) is a theorem of the base theory of W1.

; - Since W1 is conservative over H (as noted above), (2) is a theorem of H.

; - Since H is contained in W0, by (E01), then (2) is a theorem of the base
;   theory of W0.

; We now turn to the sub-appendices promised above.

; Sub-Appendix 1.1: Restrictions pertaining to transparent functions

; The implementation uses a notion of "sibling" to compute the various
; ancestor relations, such that two functions introduced in the same
; encapsulate's signatures are considered siblings.  The following
; property therefore holds for the ordinary ancestor relation as well as
; the modified extended-ancestor relation.

;   Suppose that g is an ordinary ancestor (respectively, a modified
;   extended-ancestor) of f.  Suppose also that f and f' are siblings
;   and also g and g' are siblings.  Then g' is an ordinary ancestor
;   (respectively, a modified extended-ancestor) of f'.

; This property leads us to make the following restriction, since the
; property just above for the modified extended-ancestor relation
; requires transparency to be the same for all siblings of a given
; function symbol.

;   Restriction 1. If any function introduced in an encapsulate's signature is
;   marked with :transparent t, then all of them are.

; The second restriction is as follows.  Its suitability is discussed in
; Sub-Appendix 1.3.

;   Restriction 2. When the domain of a defattach event includes a transparent
;   function, that domain must equal the set of function symbols introduced in
;   a single encapsulate.  (This is the "siblings" of each introduced function,
;   and includes all function symbols constrained by the encapsulate, not just
;   those introduced by the signature, though those are often the same.)

; Sub-Appendix 1.2:  Why the world constructions are valid

; Let's consider the three constructions, in order, starting in each case with
; the definition given earlier.

; W0-: like W0, but only retaining attachments to functions that both are
;      transparent and are modified extended-ancestors of meta-fn

; We can construct W0- from W0 by first removing all attachments (say, by
; attaching nil to all of them) and then re-running just the attachments to
; transparent functions that are modified extended-ancestors of meta-fn in W0.
; Let us those call those ancestral transparent functions, "meta-fn
; transparent".  That is, a meta-fn transparent function is a transparent
; function that is a modified extended-ancestor of meta-fn.  Thus, the
; defattach events in W0- are those of W0 that attach to meta-fn transparent
; functions.

; The re-attachments, after removing all attachments, are legal because they
; were legal when constructing W0.  In particular, the full extended-ancestor
; relation of W0- is contained in that of W0 and hence remains acyclic, and the
; proof obligations all hold in the base theory of W0 (because they held when
; admitting them, and world extensions never weaken the theory -- even when
; discarding local events, by conservativity).

; W1-: like W0- except that for each attachment pair <f,g> of W0-, that
;      attachment is removed, but also the constraint on f is eliminated in
;      favor of defining f = g

; This is justified by the Evaluation History Theorem.  Note that the base
; theory of W1- is the same as the evaluation theory of W0-.

; W1:  same base theory as W1-, but this world includes all defattach
;      events that were eliminated when forming W0-

; Thus, W1 is the world resulting from W1- by redoing all defattach events of
; W0 that aren't in W1- (i.e., those that attach to other than meta-fn
; transparent functions).  Why are these legal?  The extended-ancestor relation
; of W1- is contained in that of W0, hence is acyclic.  The proof obligations
; are unchanged from W0 to W1, since the guards are unchanged (see next
; paragraph) and the constraints on the to-be-unattached functions are the same
; in W0 as in W1.  These proof obligations are all theorems of the base theory
; of W0 (as argued above when considering W0-), so they are also all theorems
; of the base theory of W1, since as noted above that is just the evaluation
; theory of W0 (which of course extends the base theory of W0).

; (Remark.  It's implicit in the Evaluation History Theorem that guards are
; unchanged.  The idea is that we added f=g only after proving that the guard
; of f implies the guard of g, so we keep the guard of f unchanged and that's
; OK.)

; Sub-Appendix 1.3: On the suitability of Restriction 2

; Recall that Restriction 2 says that if the domain of a defattach event
; contains any transparent function symbol, then that domain must equal the set
; of all signature functions from a single encapsulate.  To see why this
; restriction is reasonable, consider the following example.

; (encapsulate ((f1 (x) t :transparent t))
;   (local (defun f1 (x) x)))
; (encapsulate ((f2 (x) t :transparent t))
;   (local (defun f2 (x) x)))
; (defattach (f1 consp) (f2 f1))

; The argument below requires us to extend with defattach events on transparent
; functions.  In the example above, if we collect f1 as an extended-ancestor of
; meta-fn, we will collect f2 -- which leads back to f1.  This loop cannot
; happen if the domain of the defattach consists of signatures from a single
; encapsulate, where there is a single canonical sibling.  Perhaps the argument
; can be extended without the restriction of a single encapsulate, but if so,
; that may ruin the benefit memoization provides for function
; canonical-ancestors-tr-rec, memoized in boot-strap-pass-2-b.lisp) because of
; a new parameter that keeps a list of the function symbols that we have
; visited.  Perhaps it would suffice to memoize only
; immediate-canonical-ancestors-tr (also done in boot-strap-pass-2-b.lisp).
; For now it seems that restricting to a single encapsulate is not a severe
; restriction; we can revisit this restriction if necessary.

; Appendix 2: How the Implementation Accommodates Transparent Functions

; This Appendix is divided into the following parts.

; Part 1: Terminology and introduction to relevant properties (explained
;         further below)
; Part 2: Invariants
; Part 3: Remarks
; Part 4: Actions
; Part 5: On the preservation of invariants

;;;;;;;;;;
; Part 1: Terminology and introduction to relevant properties (explained
;         further below)
;;;;;;;;;;

; We refer to "meta-fns" to denote a set (represented as a list) with the
; following members: for a :meta rule, the meta-function and, if there is one,
; the hypothesis meta-function; and for a :clause-processor rule, the
; clause-processor function.  We refer to "ev-fns" as a set (represented as a
; list) containing the evaluator and any meta-extract functions of the rule.

; A function is considered to be "transparent" or "non-transparent" according
; to whether or not (respectively) its canonical sibling has a 'constrainedp
; property that is a transparent-rec record, which is a record with a single
; field, :names.  Transparent functions are generally those marked with
; :transparent t in an encapsulate's signature, but any sibling of such a
; function is also transparent, in particular those that infect the
; encapsulate's constraint (see :DOC infected-constraints).  We arrange (when
; setting the 'siblings properties in encapsulate-pass-2) that the canonical
; sibling of a transparent function is always a signature function.  This
; avoids the conflict that would occur if the canonical function were an
; "infected" function of the encapsulate, defined with defun: such a function
; should have a 'constrainedp property of nil, hence cannot have a
; 'constrainedp property that is a transparent-rec record.

; For a rule r of class :meta or :clause-processor, the "common ancestors for
; r" refers to the set of all function symbols f such that f is both a modified
; extended-ancestor of the meta-fns of r and a canonical ancestor of the ev-fns
; of r.

; Note that although "r" suggests "rule", we typically use "r" below as the
; name of a defthm event that introduces a rule of class :meta or
; :clause-processor.  Of course, the common case is that only one such rule is
; introduced by r.

; Here is a summary of the relevant properties.  The next section,
; "Invariants", spells out the invariants maintained for these
; properties.

; - Constrainedp property of a canonical transparent function, fn:

;     The property's value is a transparent-rec record whose (unique) :names
;     field lists all the names of defthm events that introduce a :meta or
;     :clause-processor rule for which fn is a modified extended-ancestor of
;     its meta-fns.

;     Note that there is a check in encapsulate-pass-2 that a function symbol
;     cannot be transparent if it has unknown-constraints.  (There is a comment
;     about this in the case (and unknown-constraints-p transparent) in
;     encapsulate-pass-2.)  This avoids the potential conflict caused by the
;     need to set the 'constrainedp property to *unknown-constraints* in the
;     unknown-constraints-p case.

; - Attachment property of a function, fn, for which attachments are
;   disallowed:

;     This property has value of the form (:attachment-disallowed . &).  If fn
;     is not canonical then the value is (:attachment-disallowed . g) where g
;     is the canonical sibling of fn.  Then the 'attachment property of g is
;     (:attachment-disallowed . alist), where alist consists of a pair (r
;     . token) for every name r of a defthm event that adds a :meta or
;     :clause-processor rule for which g is common ancestor for r.  Token
;     represents a rule-class added for r: generally :meta or
;     :clause-processor, but in the very rare case of more than one such rule
;     added for r, token is t.

; - Evaluator-check-inputs property of an event name, r:

;     This property is nil except in the following case: r names a defthm event
;     that adds a :meta or :clause-processor rule that has at least one
;     transparent, modified extended-ancestor of its meta-fns.  Note that such
;     an event is necessarily a defthm event.  A non-nil value is of the form

;     (tr-meta-anc common-anc
;                  (rule-class-1 meta-fns-1 ev-anc-1 extra-anc-1 ev-fns-1)
;                  ...
;                  (rule-class-k meta-fns-k ev-anc-k extra-anc-k ev-fns-k))

;     where:

;     - tr-meta-anc lists the transparent modified extended-ancestors of the
;       meta-fns for r;

;     - common-anc lists the modified extended-ancestors of the meta-fns
;       that are also canonical ancestors of the ev-fns; and

;     - the remaining elements correspond to the :meta and :clause-processor
;       rules associated with r.  There is always at least one of these, but
;       usually there will be only one.  For each such rule:

;       - rule-class is the rule's class (:meta or :clause-processor);
;       - meta-fns is the rule's meta-fns;
;       - ev-anc is the canonical-ancestors of the rule's evaluator;
;       - extra-anc is the canonical-ancestors of the rule's meta-extract
;         functions if any, else nil; and
;       - ev-fns is a list without duplicates containing the canonical siblings
;         of the evaluator and any meta-extract functions of the rule.

;;;;;;;;;;
; Part 2: Invariants
;;;;;;;;;;

; For a given defthm name r, we may refer to the "tr-meta-anc of r" and the
; "common-anc of r" to be lists stored as noted above in the
; 'evaluator-check-inputs property of r, or nil when that property is nil.
; Note that all such function symbols are canonical.  Common-anc Invariant 1
; below connects the list, "common-anc of r", with the set (defined earlier),
; "common ancestors for r".

; Transparent Function Invariant:

;   The following are equivalent for every canonical function symbol, f.

;   (a) f is transparent.

;   (b) The 'constrainedp property of f is a transparent-rec record.

; Tr-meta-anc Invariant:

;   The following are equivalent for every function symbol f and every name r.

;   (a) f is a transparent, modified extended-ancestor of the meta-fns of a
;       rule stored for r.

;   (b) f is in the tr-meta-anc of r.

;   (c) f is canonical and its 'constrainedp property is a transparent-rec
;       record whose :names includes r.

; Common-anc Invariant 1:

;   The following are equivalent for every transparent function symbol f and
;   every name, r.

;   (a) f is a common ancestor for a rule of a defthm event named r.

;   (b) f is in the common-anc of r.

;   (c) r is mapped to the rule-class of its :meta or :clause-processor rule in
;       the alist of the 'attachment property of f, (:attachment-disallowed
;       . alist).  Except, if there is more than one such rule for r, then r is
;       mapped to t.

; Common-anc Invariant 2:

;   For every name r and every f in the common-anc of r, f does not have an
;   attachment.

; Attachment Invariants:

;   For any canonical function f and sibling g of f, the 'attachment property
;   of either is of the form (:attachment-disallowed . x) if and only if both
;   are of that form.  For f, x is a non-empty alist as described in part (c)
;   of Common-anc Invariant 1.  For g not equal to f, x is f.

;;;;;;;;;;
; Part 3: Remarks
;;;;;;;;;;

; A defaxiom cannot have a rule of class :meta or :clause-processor: the
; functional instantiation argument in the Essay on Correctness of Meta
; Reasoning depends on that.  That explains our attention to defthm for
; addition of such rules.

; As noted above, if there is no transparent, modified extended-ancestor of the
; meta-fns of a rule for a defthm named r, then the 'evaluator-check-inputs
; property of r is nil.  The reason nil is appropriate is that the role of the
; 'evaluator-check-inputs property is to help ensure the invariants hold, but
; the modified extended-ancestors of the meta-fns will never change if they do
; not include a transparent function, even when attachments are modified.

; The rule-class components of (c) in Common-anc Invariant 1 are used for error
; messages.

; Membership in common-anc does not exclude transparent functions.  This may be
; surprising when one considers that changing a transparent function's
; attachment may eliminate the presence of any attachment to a function symbol
; in common-anc, because the modified extended-ancestors of meta-fns can
; change.  However, if a function symbol f is in common-anc, then f will remain
; in common-anc even if its attachment is changed: the path from meta-fns to f
; will still be valid.  The only way the common-anc can change with attachment
; to a transparent function is if that function is on the path from a meta-fn
; to a common ancestor, before reaching a common ancestor.

; Consider the case that the 'constrainedp property for a transparent function
; fn is a transparent-rec record with names (r1 r2 ... rk), where each ri is
; the name of a theorem for which fn is a modified canonical-ancestor of its
; meta-fns.  Then although more than one :meta or :clause-processor rule may be
; associated with an ri, this is likely to be very rare, so we don't try to be
; particularly efficient for that case.  Rather, we coalesce into a single
; tr-meta-anc and a single common-anc for ri, rather than for each of its
; rules.

; One might be concerned about the case that a transparent function f and meta
; rule r are introduced in a sub-encapsulate, where r has f in its tr-meta-anc?
; But that works out, since ACL2 insists that if any signature function in an
; encapsulate is marked with :transparent t, then they all are.  Thus, the
; notion of "transparency" for f at the time r is introduced doesn't change as
; one pops out of the sub-encapsulate.

;;;;;;;;;;
; Part 4: Actions
;;;;;;;;;;

; Actions taken for events establish and preserve the invariants above as the
; three relevant properties are updated: 'constrainedp, 'attachment, and
; 'evaluator-check-inputs.  There are two event types whose actions affect
; these invariants: defthm and defattach.  Here we describe their effects on
; those three properties.

;;;
; Defthm actions
;;;

; Here is how defthm-fn1 puts properties as described in the first section
; above.  (That section is referenced freely and implicitly below.)  Function
; update-meta-props does this work.

; Let r be the name of the defthm.

; First, as the rule is checked, function chk-evaluator-use-in-rule creates a
; ttree entry with tag 'evaluator-check-for-rule and value as described above,
; of the form (tr-meta-anc common-anc rule-class meta-fns ev-anc extra-anc
; ev-fns).  Except, of course, if any member of common-anc has an attachment
; then there is an error.  (Also, as an optimization, there is no ttree entry
; added when both tr-meta-anc and common-anc are nil.)  The resulting ttree is
; passed to chk-acceptable-meta-rule or chk-acceptable-clause-processor-rule.
; Then defthm-fn1 uses these values to update properties as follows.

; Property 'evaluator-check-inputs of r is created from the list L of values
; from the ttree.  That property's value is (tr-meta-anc common-anc . L'),
; where: tr-meta-anc is the union of the tr-meta-anc values from L; common-anc
; is the union of the common-anc values from L; and L' is the result of
; removing these from each element of L.

; The 'constrainedp property of each symbol f in that tr-meta-anc list is
; updated to reflect r.  We know that the existing property's value is a
; transparent-rec record.  The action is to update that property by adding r to
; its :names.

; Finally, the 'attachment property of each symbol in that common-anc list is
; then put as value (:attachment-disallowed . alist), where there are two
; cases, based on the existing value, v, of that property.  In both cases, let
; c be the rule-class of the :meta or :clause-processor rule associated with r
; unless there are more than one, in which case c is t.  Then if v is nil,
; alist is ((r . c)); otherwise v is of the form (:attachment-disallowed
; . alist0), and lst is ((r . c) . lst0).

;;;
; Defattach actions
;;;

; For defattach, the property updates take place after installing the new
; world, just before calling install-event.  The actions may cause an error;
; hence, a revert-world-on-error wrapper is necessary around the relevant
; defattach-fn code (and it may be found in the definition of
; put-defattach-props).

; First, here is a summary.  When a defattach event applies to any function fn
; in the tr-meta-anc of a theorem named r, that may change the tr-meta-anc of r
; and thus also change the common-anc of r.  So these are recomputed, while
; checking that no member of the new common-anc has an attachment.  Then ACL2
; updates the 'evaluator-check-inputs property of r with the new tr-meta-anc
; and common-anc, the 'constrained properties according to the old and new
; tr-meta-anc, and the 'attachment properties according to the old and new
; common-anc.

; Here is a more detailed description of the defattach actions.  These are
; taken by function put-defattach-props.

; Consider a new event (defattach (f1 ...) ...) that attaches to at least one
; transparent function.  ACL2 then insists that it attach to precisely a single
; set of siblings.  Let fn be the canonical sibling among them; equivalently,
; because of the "single set" property just mentioned, fn is the canonical
; sibling of f1.

; Thus, the value of the 'constrainedp property of fn is a transparent-rec
; record, say with :names (r1 r2 ... rk).  After updating the world as though
; the defattach event has completed, then for each ri, grab its
; 'evaluator-check-inputs property and recompute tr-meta-anc and then
; common-anc using function chk-meta-fn-attachments, which causes an error if
; there is an attachment to any function in common-anc.  Then take the
; following actions for that ri.  (Note that the 'constrainedp property of a
; canonical transparent function symbol is a transparent-rec record, and also
; that every member of a tr-meta-anc list is a canonical transparent function
; symbol; so we can refer below to the :names of any symbol in a tr-meta-anc
; list.)

; - Replace the tr-meta-anc of the 'evaluator-check-inputs property of
;   ri with the newly-computed tr-meta-anc, and do the following for every
;   function symbol g that is in the difference between the old and new
;   tr-meta-anc.

;   - If g is old but not new, remove ri from the :names in the 'constrainedp
;     property of g.

;   - If g is new but not old, add ri to the :names in the 'constrainedp
;     property of g.

; - Replace the common-anc of the 'evaluator-check-inputs property of ri with
;   the newly-computed common-anc, and do the following for every function
;   symbol g that is in the difference between the old and new common-anc.

;   - If g is old but not new, remove ri as a key from the alist in the
;     (:attachment-disallowed . alist) value of the 'attachment property of g.
;     Except, if the alist becomes empty then set that 'attachment property to
;     nil.

;   - If g is new but not old, there are two cases depending on the value of
;     the 'attachment property of g (which we have already checked cannot
;     indicate an attachment).  Note that relevant rule-classes are in the cddr
;     of the 'constrainedp property of ri; denote that as Lst.

;     - If the value is (:attachment-disallowed . alist), then add a suitable
;       entry with key ri to alist.

;     - If the value is nil then set the 'attachment property to
;       (:attachment-disallowed . ((ri . rule-class))) for suitable rule-class
;       from Lst; thus, rule-class is t if Lst has more than one element.

;;;;;;;;;;
; Part 5: On the preservation of invariants
;;;;;;;;;;

; It is straightforward to check that the actions described above preserve the
; invariants (from the "Invariants" section above).  Here we merely make a few
; remarks that may be helpful.

; The Transparent Function Invariant holds for a function symbol f when it is
; introduced; see encapsulate-pass-2.  No subsequent action violates this
; invariant.

; The Tr-meta-anc Invariant, Common-anc Invariants 1 and 2, and the Attachment
; Invariants are established for f and r when r is introduced by defthm.  They
; are preserved by the actions taken for defattach.

; For preservation of Common-anc Invariant 2 by defattach, note that attachment
; to a function is disallowed when its 'attachment property is of the form
; (:attachment . &).

; End of Essay on Correctness of Meta Reasoning

(defun search-type-alist+ (term typ type-alist unify-subst ttree wrld)

; Keep this in sync with search-type-alist.  One difference between this
; function and search-type-alist is that the present function returns one
; additional argument: the remainder of type-alist to be searched.  Another is
; that we assume here that term has at least one variable not bound by
; unify-subst.

; No-change loser except for type-alist.

  (mv-let (term alt-term)
    (cond ((or (variablep term)
               (fquotep term)
               (not (equivalence-relationp (ffn-symb term) wrld)))
           (mv term nil))
          (t ; we know there are free vars in term
           (mv term
               (fcons-term* (ffn-symb term) (fargn term 2) (fargn term 1)))))
    (search-type-alist-rec term alt-term typ type-alist unify-subst ttree)))

(defun oncep (nume-runes match-free rune nume)

; We are given a oncep-override value (e.g., from the :oncep-override value of
; a rewrite constant), nume-runes; a rune, rune and its corresponding nume; and a
; value :once or :all from the match-free field of the rule corresponding to
; that rune.  We want to determine whether we should try only one binding when
; relieving a hypothesis in order to relieve subsequent hypotheses, and return
; non-nil in that case, else nil.

  (if (or (eq nume-runes :clear)
          (<= (car nume-runes) nume))
      (eq match-free :once)
    (member-equal rune (cdr nume-runes))))

(defmacro zero-depthp (depth)

; We use this macro instead of zpf for two reasons.  For one, we have not (as
; of this writing) made zpf a macro, and we want efficiency.  For another, we
; want to be able to experiment to see what sort of stack depth is used for
; a given event.  Use the first body below for that purpose, but use the second
; body for normal operation.

  #+acl2-rewrite-meter ; for stats on rewriter depth
  `(prog2$ #+acl2-loop-only
           ,depth
           #-acl2-loop-only
           (setq *rewrite-depth-max* (max ,depth *rewrite-depth-max*))
           nil)
  #-acl2-rewrite-meter ; normal stats (no stats)
  `(eql (the-fixnum ,depth) 0))

(defmacro rdepth-error (form &optional preprocess-p)
  (if preprocess-p
      (let ((ctx ''preprocess))
        `(prog2$ (er-hard
                  ,ctx "Call depth"
                  "The call depth limit of ~x0 has been exceeded in the ACL2 ~
                   preprocessor (a sort of rewriter).  There might be a loop ~
                   caused by some set of enabled simple rules.  To see why ~
                   the limit was exceeded, ~@1retry the proof with :hints~%  ~
                   :do-not '(preprocess)~%and then follow the directions in ~
                   the resulting error message.  See :DOC rewrite-stack-limit ~
                   for a possible solution when there is not a loop."
                  (rewrite-stack-limit wrld)
                  (if (f-get-global 'gstackp state)
                      ""
                    "execute~%  :brr t~%and next "))
                 ,form))
    (let ((ctx ''rewrite))
      `(prog2$ (er-hard
                ,ctx "Call depth"
                "The call depth limit of ~x0 has been exceeded in the ACL2 ~
                 rewriter.  To see why the limit was exceeded, ~@1execute the ~
                 form (cw-gstack) or, for less verbose output, instead try ~
                 (cw-gstack :frames 30).  You may then notice a loop caused ~
                 by some set of enabled rules, some of which you can then ~
                 disable; see :DOC disable.  For a possible solution when ~
                 there is not a loop, see :DOC rewrite-stack-limit."
                (rewrite-stack-limit wrld)
                (if (f-get-global 'gstackp state)
                    ""
                  "first execute~%  :brr t~%and then try the proof again, and ~
                   then "))
               ,form))))

(defun bad-synp-hyp-msg1 (hyp bound-vars all-vars-bound-p wrld)

; A hyp is a "good synp hyp" if either it does not mention SYNP as a function
; symbol or else it is a call of SYNP that we know how to handle in our
; processing of rewrite and linear rules.  We return nil as the first value in
; this case, or else an appropriate message explaining the problem.  See
; bad-synp-hyp-msg.

  (if (ffnnamep 'synp hyp)
      (cond ((not (eq (ffn-symb hyp) 'synp))

; Through Version_8.1, the message below seemed to suggest that we insist that
; synp only occur as the top function symbol of hyp.  However, we can actually
; allow it below that in a non-executable context, provided it also occurs as
; the top function symbol.  So we changed "can occur only" to "should occur
; only", since really, this weaker check is probably good enough.

             (mv (cons
                  "a call of syntaxp or bind-free should occur only ~
                   at the top level of a hypothesis, but in ~x0 it ~
                   appears elsewhere but not at the top level."
                  (list (cons #\0 (untranslate hyp t wrld))))
                 bound-vars all-vars-bound-p))
            ((not (all-quoteps (fargs hyp)))
             (mv (cons
                  "a call of ~x0 in a hypothesis should be made on quoted ~
                   arguments, but that is not true for the hypothesis, ~x1."
                  (list (cons #\0 'synp)
                        (cons #\1 (untranslate hyp nil wrld))))
                 bound-vars all-vars-bound-p))

; Note that we check for the well-formedness of a call to synp in
; translate, so the following bindings should be safe.

            (t
             (let* ((term-to-be-evaluated (unquote (fargn hyp 3)))
                    (vars (all-vars term-to-be-evaluated))
                    (saved-term (unquote (fargn hyp 2)))
                    (vars-to-be-bound (unquote (fargn hyp 1))))
               (cond ((not (termp term-to-be-evaluated wrld))
                      (mv (cons
                           "the term to be evaluated by the syntaxp or ~
                            bind-free hypothesis must be an ACL2 term, but ~
                            this is not the case in ~x0.  The term's internal ~
                            (translated) form is ~x1."
                           (list (cons #\0 (untranslate hyp nil wrld))
                                 (cons #\1 term-to-be-evaluated)))
                          bound-vars all-vars-bound-p))
                     ((or (variablep saved-term)
                          (fquotep saved-term)
                          (not (member-eq (ffn-symb saved-term)
                                          '(syntaxp bind-free))))
                      (mv (cons
                           "a synp hyp has been found which does not appear to ~
                            have come from a syntaxp or bind-free hypothesis: ~
                            ~x0. This is not, at present, allowed.  If we are ~
                            in error or you believe we have been otherwise too ~
                            restrictive, please contact the maintainers of ~
                            ACL2."
                           (list (cons #\0 (untranslate hyp nil wrld))))
                          bound-vars all-vars-bound-p))
                     ((and (not (equal vars-to-be-bound nil)) ; not syntaxp
                           (not (equal vars-to-be-bound t))
                           (or (collect-non-legal-variableps vars-to-be-bound)
                               all-vars-bound-p
                               (intersectp-eq vars-to-be-bound bound-vars)))
                      (mv (cons
                           "the vars to be bound by a bind-free hypothesis ~
                            must be either t or a list of variables which ~
                            are not already bound.  This is not the case in ~
                            ~x0.  The vars to be bound are ~x1 and the vars ~
                            already bound are ~x2."
                           (list (cons #\0 (untranslate hyp t wrld))
                                 (cons #\1 vars-to-be-bound)
                                 (cons #\2
                                       (if all-vars-bound-p
                                           '<all_variables>
                                           (reverse bound-vars)))))
                          bound-vars all-vars-bound-p))
                     ((and (not all-vars-bound-p)
                           (not (subsetp-eq (set-difference-eq vars
                                                               '(state mfc))
                                            bound-vars)))
                      (mv (cons
                           "any vars, other than ~x2 and ~x3, used in ~
                            the term to be evaluated by a ~
                            syntaxp or bind-free hypothesis must already be ~
                            bound.  This does not appear to be the case ~
                            in ~x0.  The vars already bound are ~x1."
                           (list (cons #\0 (untranslate hyp t wrld))
                                 (cons #\1 (reverse bound-vars))
                                 (cons #\2 'mfc)
                                 (cons #\3 'state)))
                          bound-vars all-vars-bound-p))
                     ((or (member-eq 'state vars)
                          (member-eq 'mfc vars))
                      (cond ((or (member-eq 'state bound-vars)
                                 (member-eq 'mfc bound-vars)
                                 all-vars-bound-p)

; The point here is that if state or mfc is already bound, then the user may be
; confused as to whether the present uses are intended to refer to the "real"
; state and mfc or whether they are intended to refer to the variables already
; bound.

                             (mv (cons
                                  "we do not allow the use of state or mfc ~
                                   in a syntaxp or bind-free hypothesis ~
                                   in a context where either state or ~
                                   mfc is already bound.  This restriction ~
                                   is violated in ~x0.  The vars already ~
                                   bound are ~x1."
                                  (list (cons #\0 (untranslate hyp nil wrld))
                                        (cons #\1 (if all-vars-bound-p
                                                      '<all_variables>
                                                    (reverse bound-vars)))))
                                 bound-vars all-vars-bound-p))
                            ((or (not (eq 'state (car vars)))
                                 (member-eq 'state (cdr vars))
                                 (not (eq 'mfc (cadr vars)))
                                 (member-eq 'mfc (cddr vars))
                                 (and (not all-vars-bound-p)
                                      (not (subsetp-eq (cddr vars) bound-vars))))
                             (mv (cons
                                  "if either state or mfc is a member of the ~
                                   vars of the term to be evaluated, we ~
                                   require that both mfc and state be present ~
                                   and that they be the last two args of the ~
                                   term, in that order.  We also require that ~
                                   the remaining vars be already bound.  This ~
                                   does not appear to be the case in ~x0.  The ~
                                   vars already bound are ~x1."
                                  (list (cons #\0 (untranslate hyp nil wrld))
                                        (cons #\1 (if all-vars-bound-p
                                                      '<all_variables>
                                                    (reverse bound-vars)))))
                                 bound-vars all-vars-bound-p))
                            (t
                             (mv nil
                                 (cond ((eq vars-to-be-bound nil)
                                        bound-vars)
                                       ((eq vars-to-be-bound t)
                                        bound-vars)
                                       (t
                                        (union-eq vars-to-be-bound
                                                  bound-vars)))
                                 (or all-vars-bound-p
                                     (equal vars-to-be-bound t))))))
                     (t
                      (mv nil
                          (cond ((equal vars-to-be-bound nil)
                                 bound-vars)
                                ((equal vars-to-be-bound t)
                                 bound-vars)
                                (t
                                 (union-eq vars-to-be-bound
                                           bound-vars)))
                          (or all-vars-bound-p
                              (equal vars-to-be-bound t))))))))

; We do not have a synp hyp.

    (mv nil
        (union-eq (all-vars hyp) bound-vars)
        all-vars-bound-p)))

(defun bad-synp-hyp-msg (hyps bound-vars all-vars-bound-p wrld)

; We check hyps for any bad synp hyps and return either nil, if there
; were none found, or an error message suitable for use with ~@.  This
; message will describe what is wrong with the first (and only) bad
; synp hyp found and will be used in chk-acceptable-rewrite-rule2
; (and related checkers for linear and quoted constant rules)
; and in rewrite-with-lemma.

; Hyps is a list of hypotheses we are to check, bound-vars is an
; accumulator of all the vars known to be bound (initially set to the
; vars in the lhs of the rewrite rule or the trigger term of a linear
; rule), and all-vars-bound-p is a boolean which indicates whether all
; vars are potentially bound (due to the presence of a 't var-list in
; an earlier synp hyp) and is initially nil.

; See bad-synp-hyp-msg1 for the checks we perform.  Crudely, we
; check that a synp hyp looks like it came from the expansion of a
; syntaxp or bind-free hyp and that it does not appear to rebind any
; vars that are already bound.

  (if (null hyps)
      nil
    (mv-let (bad-synp-hyp-msg bound-vars all-vars-bound-p)
      (bad-synp-hyp-msg1 (car hyps) bound-vars all-vars-bound-p wrld)
      (or bad-synp-hyp-msg
          (bad-synp-hyp-msg (cdr hyps) bound-vars all-vars-bound-p wrld)))))

(defmacro sl-let (vars form &rest rest)

; Keep in sync with sl-let@par.

  (let ((new-vars (cons 'step-limit vars)))
    `(mv-let ,new-vars
             ,form
             (declare (type #.*fixnum-type* step-limit))
             ,@rest)))

#+acl2-par
(defmacro sl-let@par (vars form &rest rest)

; Keep in sync with sl-let.

  (declare (xargs :guard ; sanity check inherited from mv-let@par
                  (member-eq 'state vars)))
  (let ((new-vars (cons 'step-limit vars)))
    `(mv-let@par ,new-vars
                 ,form
                 (declare (type #.*fixnum-type* step-limit))
                 ,@rest)))

(defmacro rewrite-entry-extending-failure (unify-subst failure-reason form
                                                       &rest args)
  `(mv-let (step-limitxx relieve-hyps-ansxx failure-reason-lstxx unify-substxx
                         ttreexx allpxx rw-cache-alist-newxx)
           (rewrite-entry ,form ,@args)
           (mv step-limitxx relieve-hyps-ansxx
               (and (null relieve-hyps-ansxx)
                    (cons (check-vars-not-free
                           (step-limitxx relieve-hyps-ansxx
                                         failure-reason-lstxx unify-substxx
                                         ttreexx allpxx rw-cache-alist-newxx)
                           (cons ,unify-subst ,failure-reason))
                          failure-reason-lstxx))
               unify-substxx ttreexx allpxx rw-cache-alist-newxx)))

(defun extend-unify-subst (alist unify-subst)

; We attempt to keep all terms in quote-normal form, which explains the use of
; quote-normal-form below.  There are also three calls of quote-normal-form in
; rewrite-with-lemma.

; The rest of this remark was written before the introduction of the function
; quote-normal-form, using (sublis-var nil ...) instead, which, unlike
; quote-normal-form, recurred inside calls of HIDE.

; We wondered if for large problems, the cost of exploring large terms might
; not be worth the benefit of maintaining quote-normal form, so we tried
; replacing the pairlis$ call below with, simply, alist.  However, we found
; relatively little benefit, as we now describe.

; Below are timings from 4 different configurations.  In all cases, we
; abstained from doing anything else on the laptop during the run.  So the
; differences you see are real, up to GC time.  All the runs were conducted
; sequentially in the same image.
;
; The first configuration, A, is as reported in the Stateman paper (by J Moore)
; at the 2015 ACL2 Workshop.  The relevant fact is that sublis-var1 is memoized
; when the substitution is nil and the term has a HIDE on it.  Three runs were
; done to see if the time would stabilize.  The time reported in the paper was
; 275 seconds.
;
; ; A runs:
; ; 388.94 seconds realtime, 382.18 seconds runtime
; ; 265.68 seconds realtime, 262.71 seconds runtime
; ; 274.68 seconds realtime, 272.27 seconds runtime
;
; The next configuration is the same as A except that here, sublis-var1 is not
; memoized.  So here you see the extra cost of the sublis-var nil calls.
;
; ; B runs:
; ; 485.81 seconds realtime, 482.91 seconds runtime
; ; 494.81 seconds realtime, 491.70 seconds runtime
;
; The next configuration is with the change described above, as follows: we
; replaced the pairlis$ call with the variable, alist, and replaced each
; (sublis-var nil X) call in rewrite-with-lemma by the corresponding X.  Note
; that sublis-var is not memoized here either.
;
; ; C runs:
; ; 281.10 seconds realtime, 278.37 seconds runtime
; ; 284.11 seconds realtime, 281.30 seconds runtime
;
; So eliminating the call has about the same effect on time as memoizing it.
;
; The final experiment leaves memoization on (for sublis-var1 with nil
; substitution and a term beginning with HIDE) but also includes the
; modifications described above, that is, to avoid the (sublis-var nil ...)
; call in this function and the three such calls in rewrite-with-lemma.

; D runs:
; 273.10 seconds realtime, 270.52 seconds runtime
; 299.00 seconds realtime, 277.31 seconds runtime

; This suggests that memoizing sublis-var as Stateman does and eliminating
; these sublis-var calls is marginally worse than just memoizing sublis-var (as
; in A).  That seems rather unlikely, so we are willing to conclude that the
; differences are just noise.  So we have decided to keep these four calls of
; sublis-var-lst or sublis-var, which will avoid the potential pain of
; modifying some books to accommodate their removal.  (Actually no regression
; books as of early November 2015 needed to be modified; but other user books
; might need to be.)

  (append (pairlis$ (strip-cars alist)
                    (quote-normal-form (strip-cdrs alist)))
          unify-subst))

(defun relieve-hyp-synp (rune hyp0 unify-subst rdepth type-alist wrld state
                              fnstack ancestors backchain-limit
                              simplify-clause-pot-lst rcnst gstack ttree bkptr)

; Hyp0 is a call of synp.  This special case of relieve-hyp returns some of the
; same values as does relieve-hyp, namely the following
; where wonp is t, nil, or :unify-subst-list:

; (mv wonp failure-reason unify-subst' ttree'')

  (let* ((synp-fn (car (get-evg (fargn hyp0 2) 'relieve-hyp)))
         (mfc (if (member-eq 'state (all-vars (get-evg (fargn hyp0 3)
                                                       'relieve-hyp)))
                  (make metafunction-context
                        :rdepth rdepth
                        :type-alist type-alist

; The user-supplied term for synp may use the mfc in arbitrary ways, so we
; don't have a clear :obj and we cannot do better than equality for :geneqv.

                        :obj '?
                        :geneqv nil
                        :wrld wrld
                        :fnstack fnstack
                        :ancestors ancestors
                        :backchain-limit backchain-limit
                        :simplify-clause-pot-lst simplify-clause-pot-lst
                        :rcnst rcnst
                        :gstack (if bkptr

; Bkptr is nil when we turn off tracking, e.g. for show-rewrites.

                                    (push-gframe 'synp
                                                 bkptr
                                                 (if (eq synp-fn 'syntaxp)
                                                     synp-fn
                                                   'bind-free))
                                  gstack)
                        :ttree ttree
                        :unify-subst unify-subst)
                nil)))
    (mv-let (erp val latches)
            (ev-synp (fargn hyp0 3) unify-subst mfc state)
            (declare (ignore latches))
            #-acl2-loop-only (setq *deep-gstack* gstack)
            (cond
             ((or erp (null val))
              (let ((sym (cond ((null mfc) synp-fn)
                               ((eq synp-fn 'syntaxp) 'syntaxp-extended)
                               ((eq synp-fn 'bind-free) 'bind-free-extended)
                               (t ; impossible?
                                synp-fn))))
                (mv nil
                    (list sym erp val)
                    unify-subst
                    ttree)))
             ((eq synp-fn 'syntaxp)
              (cond
               ((eq val t)
                (mv t nil unify-subst
                    (push-lemma
                     (fn-rune-nume 'synp nil nil wrld)

; It is tempting to record the following:

;                           (definition-runes
;                             (all-fnnames (get-evg (fargn hyp0 3) 'relieve-hyp))
;                             t wrld))

; However, some of the functions in question may be :program mode functions, in
; which case they will not have executable-counterpart runes.  It is fine not
; to track these, even if they are in logic mode, since these functions
; contribute only heuristically to the proof, not logically; and besides, it
; would be confusing to report runes that are disabled, which they may well be.

                     ttree)))
               (t
                (mv (er hard 'relieve-hyp
                        "The evaluation of the SYNTAXP test in :HYP ~x0 of ~
                         rule ~x1 produced something other than t or nil, ~
                         ~x2. This was unexpected and is illegal.  Please ~
                         contact the maintainers of ACL2 with a description ~
                         of the situation that led to this message."
                        (get-evg (fargn hyp0 1) 'relieve-hyp)
                        rune
                        val)
                    nil unify-subst ttree))))
             (t (let ((info (bind-free-info val unify-subst (fargn hyp0 1)
                                            wrld)))
                  (cond
                   ((eq info nil)
                    (mv t nil
                        (extend-unify-subst val unify-subst)
                        (push-lemma
                         (fn-rune-nume 'synp nil nil wrld) ; see comment above
                         ttree)))
                   ((eq info t)
                    (mv :unify-subst-list nil
                        val ; a list of alists with which to extend unify-subst
                        (push-lemma
                         (fn-rune-nume 'synp nil nil wrld) ; see comment above
                         ttree)))
                   (t
                    (mv (er hard 'relieve-hyp
                            "The evaluation of the BIND-FREE form in ~
                             hypothesis ~p0 of rule ~x1 produced the result ~
                             ~x2, which is illegal because ~@3."
                            (untranslate hyp0 t wrld)
                            rune val info)
                        nil unify-subst ttree)))))))))

(defmacro push-lemma+ (rune ttree rcnst ancestors rhs rewritten-rhs)

; Warning: Keep this in sync with push-splitter?; see the comment there for how
; these two macros differ.

  `(cond ((and (null ,ancestors)
               (access rewrite-constant ,rcnst :splitter-output)
               (ffnnamep-hide 'if ,rhs t)
               (ffnnamep-hide 'if ,rewritten-rhs t))
          (let ((rune ,rune)
                (ttree ,ttree))
            (add-to-tag-tree 'splitter-if-intro rune
                             (push-lemma rune ttree))))
         (t (push-lemma ,rune ,ttree))))

(defmacro push-splitter? (rune ttree rcnst ancestors rhs rewritten-rhs)

; Warning: Keep this in sync with push-lemma+, which differs in three ways:
; that macro does not require that rune is bound to a symbol, it does not allow
; the value of rune to be nil, and it also adds a 'lemma tag.

; We could easily remove the guard below, which simply avoids the need to bind
; rune and hence ttree.

  (declare (xargs :guard (symbolp rune)))
  `(cond ((and ,rune
               (null ,ancestors)
               (access rewrite-constant ,rcnst :splitter-output)
               (ffnnamep-hide 'if ,rhs t)
               (ffnnamep-hide 'if ,rewritten-rhs t))
          (add-to-tag-tree 'splitter-if-intro ,rune ,ttree))
         (t ,ttree)))

(defmacro prepend-step-limit (n form)
  (let ((vars (if (consp n)
                  n
                (make-var-lst 'x n))))
    `(mv-let ,vars
             ,form
             (mv step-limit ,@vars))))

; We are almost ready to define the rewrite mutual-recursion nest.  But first
; we provide support for the rw-cache; see the Essay on Rw-cache.

(defrec rw-cache-entry

; This structure is a record of a failed attempt at relieve-hyps.  The
; :step-limit is set to the step-limit upon entry to the failed relieve-hyps
; call.

; There are two cases, which we call the "normal-failure" case and the
; "free-failure" case.  In the free-failure case, a preceding hypothesis bound
; a free variable without being a binding hypothesis or being a call of
; bind-free that returns a single substitution; otherwise, we are in the
; normal-failure case.

; Consider first the normal-failure case.  Then the :unify-subst is the
; restriction of a failed attempt to rewrite the nth hypothesis, stored in
; :hyp-info, to true, where the :failure-reason has the form (n . &), and the
; indexing is one-based.

; In the free-failure case, failure-reason is a structure satisfying
; free-failure-p, i.e.  of the form (:RW-CACHE-ALIST . alist), where each key
; of alist is a unify-subst and each value is a failure reason (either
; normal-failure or recursively of this form).  We sometimes call alist an
; "rw-cache-alist".  The :hyp-info field contains the :hyps field of the
; rewrite-rule, and the :step-limit is as above.  The following example
; illustrates the form of the :failure-reason.  Suppose we have a rewrite rule
; whose left-hand side has variables x1 and x2, such that hypothesis 2 binds
; free variable y and hypothesis 6 binds free variable z.  Suppose that when
; binding x1 to a1 and x2 to a2 we find:

; - bind y to b1
;    - obtained failure-reason-1 at hypothesis 4
; - bind y to b2
;    - bind z to c1
;      - obtained failure-reason-2 at hypothesis 8
;    - bind z to c2
;      - obtained failure-reason-3 at hypothesis 8

; Then the :unify-subst is ((x1 . a1) (x2 . a2)), and the corresponding
; :failure-reason looks as follows.

; (:RW-CACHE-ALIST
;  (((y . b1) (x1 . a1) (x2 . a2)) ; unify-subst
;   . failure-reason-1)
;  (((y . b2) (x1 . a1) (x2 . a2)) ; unify-subst
;   . (:RW-CACHE-ALIST
;      (((z . c1) (y . b2) (x1 . a1) (x2 . a2)) ; unify-subst
;       . failure-reason-2)
;      (((z . c2) (y . b2) (x1 . a1) (x2 . a2)) ; unify-subst
;       . failure-reason-3))))

; Note that if for example we bind y to b3 at hypothesis 2 and fail by finding
; no binding of z at hypothesis 6, then we do not store a failure-reason; and
; this is reasonable, because maybe a later context will find a binding of z.
; Another way to look at this case is to notice that above, we are storing a
; failure reason for each binding of z; so if there are no bindings of z, then
; there is nothing to store!

; We use lexorder a lot, so we put the step-limit field first.

  ((step-limit . failure-reason)
   .
   (unify-subst . hyp-info))
  t)

(defmacro free-failure-p (r)
  `(eq (car ,r) :RW-CACHE-ALIST))

(defabbrev combine-free-failure-reasons (r1 r2)

; See the Essay on Rw-cache.

; R1 and r2 are failure reasons satisfying free-failure-p.  We return (mv flg
; r), where r is a merge of the given failure reasons and if flg is t, then r
; is equal (in fact eq) to r2.

  (mv-let (flg alist)
          (combine-free-failure-alists (cdr r1) (cdr r2))
          (cond (flg (mv t r2))
                (t (mv nil (cons :RW-CACHE-ALIST alist))))))

(defun combine-free-failure-alists (a1 a2)

; A1 and a2 are rw-cache-alists, as described in (defrec rw-cache-entry ...).

  (cond
   ((endp a1) (mv t a2))
   (t
    (let ((pair (assoc-equal (caar a1) a2)))
      (cond
       (pair ; then first update a2 with (car a1)
        (let ((failure-reason-1 (cdar a1))
              (failure-reason-2 (cdr pair)))
          (mv-let
           (flg a2)
           (cond
            ((not (free-failure-p failure-reason-2)) ; keep normal-failure reason
             (mv t a2))
            ((not (free-failure-p failure-reason-1))
             (mv nil (put-assoc-equal (caar a1) failure-reason-1 a2)))
            (t
             (mv-let
              (flg2 new-reason)
              (combine-free-failure-reasons failure-reason-1 failure-reason-2)
              (cond
               (flg2 (mv t a2))
               (t (mv nil (put-assoc-equal (caar a1) new-reason a2)))))))
           (cond
            (flg (combine-free-failure-alists (cdr a1) a2))
            (t ; a2 has been updated, so returned flag must be nil
             (mv-let
              (flg alist)
              (combine-free-failure-alists (cdr a1) a2)
              (declare (ignore flg))
              (mv nil alist)))))))
       (t ; (null pair); in this case, a2 has not yet been updated
        (mv-let
         (flg alist)
         (combine-free-failure-alists (cdr a1) a2)
         (declare (ignore flg))
         (mv nil (cons (car a1) alist)))))))))

(defun combine-sorted-rw-cache-lists1 (l1 l2)

; We are given two rw-cache-lists l1 and l2, where each element is an
; rw-cache-entry record (not t) and the lists are sorted by lexorder.  We
; return (mv flg lst), where lst is a sorted list that suitably combines l1 and
; l2, and if flg is true then lst is l2.  Note that t is not a member of the
; result.

  (cond ((endp l1) (mv t l2))
        ((endp l2) (mv nil l1))
        ((and (equal (access rw-cache-entry (car l1) :unify-subst)
                     (access rw-cache-entry (car l2) :unify-subst))
              (equal (access rw-cache-entry (car l1) :hyp-info)
                     (access rw-cache-entry (car l2) :hyp-info)))
         (mv-let
          (flg lst)
          (combine-sorted-rw-cache-lists1 (cdr l1) (cdr l2))
          (let ((r1 (access rw-cache-entry (car l1) :failure-reason))
                (r2 (access rw-cache-entry (car l2) :failure-reason)))
            (cond
             ((and (free-failure-p r1)
                   (free-failure-p r2))
              (mv-let
               (flg2 failure-reason)
               (combine-free-failure-reasons r1 r2)
               (cond
                ((and flg flg2)
                 (mv t l2))
                (t (mv nil (cons (change rw-cache-entry (car l2)
                                         :failure-reason
                                         failure-reason)
                                 lst))))))

; Otherwise we prefer r2 to r1, at least if flg is true (so that we return a
; true flg).  If r2 is a free-failure-p and r1 is not, then r1 would actually
; be preferable.  But we expect that case to be virtually impossible, both
; because the failure that produced r1 would presumably have produced r2 as
; well, and because the :hyp-info field of r1 would be a single hypothesis but
; for r2 it would be a list of hypotheses.

             (flg (mv flg l2))
             (t (mv nil (cons (car l2) lst)))))))
        ((lexorder (car l1) (car l2))
         (mv-let (flg lst)
                 (combine-sorted-rw-cache-lists1 (cdr l1) l2)
                 (declare (ignore flg))
                 (mv nil (cons (car l1) lst))))
        (t
         (mv-let (flg lst)
                 (combine-sorted-rw-cache-lists1 l1 (cdr l2))
                 (cond (flg (mv t l2))
                       (t (mv nil (cons (car l2) lst))))))))

(defun split-psorted-list1 (lst acc)
  (cond ((endp lst)
         (mv acc nil))
        ((eq (car lst) t)
         (assert$ (not (member-eq t (cdr lst)))
                  (mv acc (cdr lst))))
        (t (split-psorted-list1 (cdr lst) (cons (car lst) acc)))))

(defun split-psorted-list (lst)

; Lst is a list with at most one occurrence of t, the idea being that the tail
; after T is sorted.  We return the list of elements of lst preceding that
; occurrence of T if any, in any order, together with the list of elements
; after the T (possibly empty, if there is no such T), in their given order.

; We assume that (car lst) is not t.

  (cond ((member-eq t (cdr lst))
         (split-psorted-list1 (cdr lst) (list (car lst))))
        (t (mv lst nil))))

(defun merge-lexorder-fast (l1 l2)
  (declare (xargs :guard (and (true-listp l1)
                              (true-listp l2))
                  :measure (+ (len l1) (len l2))))
  (cond ((endp l1) (mv t l2))
        ((endp l2) (mv nil l1))
        ((lexorder (car l1) (car l2))
         (mv-let (flg x)
                 (merge-lexorder-fast (cdr l1) l2)
                 (declare (ignore flg))
                 (mv nil (cons (car l1) x))))
        (t ; (lexorder (car l2) (car l1))
         (mv-let (flg x)
                 (merge-lexorder-fast l1 (cdr l2))
                 (cond (flg (mv t l2))
                       (t (mv nil (cons (car l2) x))))))))

(defun merge-sort-lexorder-fast (l)

; We have considered calling merge-lexorder below instead of
; merge-lexorder-fast.  However, the realtime of a one-processor regression
; increased by nearly 1% when we tried that -- not a lot, but enough to keep
; using merge-lexorder-fast, especially since it might generate less garbage
; (which could be useful for ACL2(p)).  Note: The above experiment took place
; before adding the cddr case, and before removing the equal case from
; merge-lexorder-fast, which should be an impossible case for our application
; of sorting the "front" (unsorted) part of a psorted list.  But we did a
; second experiment with a later version, on an "insert-proof" example from
; Dave Greve.

; Using merge-lexorder-fast:
; ; 387.18 seconds realtime, 297.43 seconds runtime
; ; (19,564,695,712 bytes allocated).
; Total GC time: 44573873 T

; Using merge-lexorder:
; ; 388.84 seconds realtime, 298.74 seconds runtime
; ; (19,739,620,816 bytes allocated).
; Total GC time: 44831695 T

; So, we'll use merge-lexorder-fast.

  (declare (xargs :guard (true-listp l)
                  :measure (len l)))
  (cond ((endp (cdr l)) l)
        ((endp (cddr l)) ; avoid the cons built by calling take below
         (cond ((lexorder (car l) (cadr l)) l)
               (t (list (cadr l) (car l)))))
        (t (let* ((n (length l))
                  (a (ash n -1)))
             (mv-let (flg x)
                     (merge-lexorder-fast
                      (merge-sort-lexorder-fast (take a l))
                      (merge-sort-lexorder-fast (nthcdr a l)))
                     (declare (ignore flg))
                     x)))))

(defun sort-rw-cache-list (lst)

; See the Essay on Rw-cache.

; Lst is an rw-cache-list.  We return a corresponding sorted list of
; rw-cache-entry records, without t as a member.

  (cond ((eq (car lst) t) (cdr lst))
        ((null (cdr lst)) lst)
        (t (mv-let (front back)
                   (split-psorted-list lst)
                   (mv-let (flg ans)
                           (combine-sorted-rw-cache-lists1
                            (merge-sort-lexorder-fast front)
                            back)
                           (declare (ignore flg))
                           ans)))))

(defun combine-rw-cache-lists (lst1 lst2)

; See the Essay on Rw-cache.

; Lst1 and lst2 are rw-cache-lists.  We return a suitable combination of the
; two, together with a flag which, when true, implies that the result is equal
; (in fact, eq) to lst2.

  (cond ((null lst1) (mv t lst2))
        ((null lst2) (mv nil lst1))
        ((eq (car lst2) t)
         (mv-let (flg ans)
                 (combine-sorted-rw-cache-lists1 (sort-rw-cache-list lst1)
                                                 (cdr lst2))
                 (cond (flg (mv t lst2))
                       (t (mv nil (cons t ans))))))
        (t (mv nil (cons t
                         (mv-let (flg ans)
                                 (combine-sorted-rw-cache-lists1
                                  (sort-rw-cache-list lst1)
                                  (sort-rw-cache-list lst2))
                                 (declare (ignore flg))
                                 ans))))))

(defun merge-rw-caches (alist1 alist2)

; Each of alist1 and alist2 is a symbol-alist sorted by car according to
; symbol<.  The value of each key is a sorted-rw-cache-list.  We return a
; symbol-alist, sorted that same way, such that each key's value is the
; suitable combination of its values in the two alists.  We avoid some consing
; by returning an additional value: a flag which, if true, implies that the
; result is equal (in fact, eq) to alist2.

  (cond ((endp alist1) (mv t alist2))
        ((endp alist2) (mv nil alist1))
        ((eq (caar alist1) (caar alist2))
         (mv-let (flg rest)
                 (merge-rw-caches (cdr alist1) (cdr alist2))
                 (mv-let (flg2 objs)
                         (combine-rw-cache-lists
                          (cdar alist1)
                          (cdar alist2))
                         (cond ((and flg flg2) (mv t alist2))
                               (flg2 (mv nil (cons (car alist2) rest)))
                               (t (mv nil (acons (caar alist2) objs rest)))))))
        ((symbol< (caar alist1) (caar alist2))
         (mv-let (flg rest)
                 (merge-rw-caches (cdr alist1) alist2)
                 (declare (ignore flg))
                 (mv nil (cons (car alist1) rest))))
        (t ; (symbol< (caar alist2) (caar alist1))
         (mv-let (flg rest)
                 (merge-rw-caches alist1 (cdr alist2))
                 (cond (flg (mv t alist2))
                       (t   (mv nil (cons (car alist2) rest))))))))

(defmacro sorted-rw-cache-p (cache)

; WARNING: This macro assumes that the given rw-cache is non-empty.

  `(eq (car ,cache) t))

(defun cdr-sort-rw-cache (cache)

; We sort the given rw-cache.

  (assert$
   cache
   (cond ((sorted-rw-cache-p cache) (cdr cache))
         (t (mv-let (front back)
                    (split-psorted-list cache)
                    (mv-let (flg ans)
                            (merge-rw-caches (merge-sort-symbol-alistp front)
                                             back)
                            (declare (ignore flg))
                            ans))))))

(defun combine-rw-caches (c1 c2)

; See the Essay on Rw-cache.

; C1 and c2 are rw-caches, typically the respective values in two caches of
; either 'rw-cache-any-tag or 'rw-cache-nil-tag.  Thus, they are psorted
; symbol-alists.  We return a suitable combination of c1 and c2, together with
; a flag implying that the result is equal (in fact eq) to c2.

  (cond ((null c1) (mv t c2))
        ((null c2) (mv nil c1))
        (t (mv-let (flg x)
                   (merge-rw-caches (cdr-sort-rw-cache c1)
                                    (cdr-sort-rw-cache c2))
                   (cond ((and flg (sorted-rw-cache-p c2))
                          (mv t c2))
                         (t (mv nil (cons t x))))))))

(defun unify-subst-subsetp (a1 a2)

; Both a1 and a2 satisfy symbol-alistp.  We assume that if a1 is a subset of
; a2, then their keys occur in the same order.

  (cond ((endp a1) t)
        ((endp a2) nil)
        ((eq (caar a1) (caar a2))
         (and (equal (cdar a1) (cdar a2))
              (unify-subst-subsetp (cdr a1) (cdr a2))))
        (t (unify-subst-subsetp a1 (cdr a2)))))

(defun rw-cache-list-lookup (unify-subst hyps recs)
  (cond
   ((endp recs) nil)
   ((eq (car recs) t)
    (rw-cache-list-lookup unify-subst hyps (cdr recs)))
   ((let* ((rec (car recs))
           (failure-reason (access rw-cache-entry rec :failure-reason))
           (hyp-info (access rw-cache-entry rec :hyp-info)))
      (and
       (cond ((free-failure-p failure-reason)
              (and (equal hyps hyp-info)
                   (equal (access rw-cache-entry rec :unify-subst)
                          unify-subst)))
             (t (and (equal hyp-info

; We test the stored hypothesis against the corresponding current hypothesis
; because the same rune can correspond to several different rules.  Theorem
; mod-completion in community book arithmetic-2/floor-mod/floor-mod.lisp
; fails if we cache a failure for one rule stored under (:rewrite
; mod-completionxxx) and then decide not to fire the other rule because we come
; across the same unify-subst.

                            (nth (1- (car failure-reason)) hyps))
                     (unify-subst-subsetp (access rw-cache-entry rec
                                                  :unify-subst)
                                          unify-subst))))
           rec)))
   (t (rw-cache-list-lookup unify-subst hyps (cdr recs)))))

(defstub relieve-hyp-failure-entry-skip-p
  (rune unify-subst hyps ttree step-limit)
  t)

(defun relieve-hyp-failure-entry-skip-p-builtin (rune unify-subst hyps ttree
                                                      step-limit)
  (declare (ignore rune unify-subst hyps ttree step-limit)
           (xargs :mode :logic :guard t))
  nil)

(defattach (relieve-hyp-failure-entry-skip-p
            relieve-hyp-failure-entry-skip-p-builtin))

(defmacro rw-cache-active-p (rcnst)
  `(member-eq (access rewrite-constant ,rcnst :rw-cache-state)
              '(t :atom)))

(defun assoc-rw-cache (key alist)
  (cond ((endp alist) nil)
        ((eq (car alist) t)
         (assoc-eq key (cdr alist)))
        ((eql key (caar alist))
         (car alist))
        (t (assoc-rw-cache key (cdr alist)))))

(defun put-assoc-rw-cache1 (key val alist)

; Alist is a psorted-alist (see the Essay on Rw-cache) and key is a key of
; alist.  We return the result of replacing the value of key with val in alist.

  (cond ((atom alist) (list (cons key val)))
        ((eq (car alist) t)
         (cons (car alist)
               (put-assoc-eq key val (cdr alist))))
        ((eq key (caar alist)) (cons (cons key val) (cdr alist)))
        (t (cons (car alist) (put-assoc-rw-cache1 key val (cdr alist))))))

(defun put-assoc-rw-cache (key val alist)

; Alist is a psorted-alist (see the Essay on Rw-cache).  We return a
; psorted-alist that associates key with val.

  (cond ((assoc-rw-cache key alist)
         (put-assoc-rw-cache1 key val alist))
        (t (acons key val alist))))

(defun relieve-hyp-failure-entry (rune unify-subst hyps ttree step-limit)

; We return either nil or else an rw-cache-entry from the rw-cache of the
; ttree.

  (let* ((cache (tagged-objects 'rw-cache-any-tag ttree))
         (entry (and cache ; optimization
                     (rw-cache-list-lookup
                      unify-subst
                      hyps
                      (cdr (assoc-rw-cache (base-symbol rune) cache))))))

; We could do our check with relieve-hyp-failure-entry-skip-p before even
; looking up the entry, above.  Instead, we optimize for the common case that
; relieve-hyp-failure-entry-skip-p returns nil, hence only calling it when
; necessary.  This way, the user's attachment to
; relieve-hyp-failure-entry-skip-p could print (with cw or observation-cw, say)
; when an entry is found but skipped.

    (cond ((null entry) nil)
          ((relieve-hyp-failure-entry-skip-p rune unify-subst hyps ttree
                                             step-limit)
           nil)
          (t entry))))

(defun maybe-extend-tag-tree (tag vals ttree)

; Warning: We assume that tag is not a key of ttree.

  (cond ((null vals) ttree)
        (t (extend-tag-tree tag vals ttree))))

(defun accumulate-rw-cache1 (replace-p tag new-ttree old-ttree)

; This function is intended to return an extension of the rw-cache of old-ttree
; according to new-ttree, or else nil if the "extension" would not actually
; change old-ttree.  Below we describe more precisely what we mean by
; "extension", hence specifying the tag-tree returned in the non-nil case.

; If replace-p is true, then replace the caches tagged by the rw-cache tag in
; old-ttree with those tagged by tag in new-ttree, the expectation being that
; the value of tag in new-ttree extends its value in old-ttree.  If replace-p
; is false, then instead of replacing, combine the two caches.  In the case
; that replace-p is nil, performance may be best if the value of tag in
; new-ttree is more likely to be contained in its value in old-ttree, than the
; other way around (given our use below of combine-rw-caches).

  (let ((new-vals (tagged-objects tag new-ttree))
        (old-vals (tagged-objects tag old-ttree)))
    (cond
     ((and replace-p ; restrict optimization (else equality is unlikely)
           (equal new-vals old-vals))

; It's not clear to us whether this COND branch is helpful or harmful.  It can
; avoid modifying the tag-tree, but only to save at most a few conses, and at
; the cost of the above equality check.

      nil)
     (old-vals
      (cond
       (replace-p
        (assert$
         new-vals ; extends non-nil old-vals
         (extend-tag-tree tag
                          new-vals
                          (remove-tag-from-tag-tree! tag old-ttree))))
       (t (mv-let
           (flg objs)
           (combine-rw-caches new-vals old-vals)
           (assert$
            objs
            (cond (flg old-ttree)
                  (t (extend-tag-tree
                      tag
                      objs
                      (remove-tag-from-tag-tree! tag old-ttree)))))))))
     (new-vals (extend-tag-tree tag new-vals old-ttree))
     (t nil))))

(defun accumulate-rw-cache (replace-p new-ttree old-ttree)

; Keep this in sync with accumulate-rw-cache?, which is similar but may (and
; usually will) return nil if old-ttree is unchanged.

; New-ttree is an extension of old-ttree.  We incorporate the rw-cache from
; new-ttree into old-ttree, generally because new-ttree is to be discarded
; after a failure but we want to save its cached failures to relieve
; hypotheses.  If replace-p is true then we actually ignore the list of values
; of the relevant tags in old-ttree, assuming (and perhaps checking with an
; assert$) that this list forms a tail of the corresponding list of values in
; new-ttree.

  (let ((ttree1 (or (accumulate-rw-cache1 replace-p 'rw-cache-nil-tag
                                          new-ttree old-ttree)
                    old-ttree)))
    (or (accumulate-rw-cache1 replace-p 'rw-cache-any-tag new-ttree ttree1)
        ttree1)))

(defun accumulate-rw-cache? (replace-p new-ttree old-ttree)

; Keep this in sync with accumulate-rw-cache, which is similar; see comments
; there.  However, that function always returns a tag-tree, while the present
; function may (and usually will) return nil if old-ttree is unchanged.

  (let* ((ttree1-or-nil (accumulate-rw-cache1 replace-p 'rw-cache-nil-tag
                                              new-ttree old-ttree))
         (ttree1 (or ttree1-or-nil old-ttree))
         (ttree2-or-nil (accumulate-rw-cache1 replace-p 'rw-cache-any-tag
                                              new-ttree ttree1)))
    (or ttree2-or-nil
        ttree1-or-nil)))

(defun restrict-alist-to-all-vars1 (alist term)

; Return the result of restricting alist to those pairs whose key is a variable
; occurring free in term, together with a flag that, if nil, implies that the
; result is equal (in fact eq) to alist.

  (declare (xargs :guard (and (symbol-alistp alist)
                              (pseudo-termp term))))
  (cond ((endp alist) (mv nil nil))
        (t (mv-let (changedp rest)
                   (restrict-alist-to-all-vars1 (cdr alist) term)
                   (cond ((dumb-occur-var (caar alist) term)
                          (cond (changedp (mv t (cons (car alist) rest)))
                                (t (mv nil alist))))
                         (t (mv t rest)))))))

(mutual-recursion

(defun all-vars-boundp (term alist)
  (declare (xargs :guard (and (pseudo-termp term)
                              (symbol-alistp alist))))
  (cond ((variablep term)
         (assoc-eq term alist))
        ((fquotep term) t)
        (t (all-vars-lst-boundp (fargs term) alist))))

(defun all-vars-lst-boundp (lst alist)
  (declare (xargs :guard (and (pseudo-term-listp lst)
                              (symbol-alistp alist))))
  (cond ((endp lst) t)
        (t (and (all-vars-boundp (car lst) alist)
                (all-vars-lst-boundp (cdr lst) alist)))))

)

(defun restrict-alist-to-all-vars (alist term)

; We return a subset of alist, with the order of elements unchanged.  In our
; intended application of this function, alist is a unify-subst obtained by
; matching the lhs of a rewrite-rule, and term is a hypothesis of that rule
; that has generated a failure reason other than a free-failure.  The return
; value is then intended to capture enough of the unify-subst such that for any
; extension of it encountered subsequently, we can reasonably expect the same
; hypothesis to fail again.

  (cond ((all-vars-boundp term alist)
         (mv-let (changedp result)
                 (restrict-alist-to-all-vars1 alist term)
                 (declare (ignore changedp))
                 result))
        (t

; This case can happen when we have a binding hypothesis.  If we pass in the
; list of all hypotheses in our intended application (see above), we could
; compute which variables bound by alist are really relevant to term.

         alist)))

(defun push-rw-cache-entry (entry tag rune ttree)

; Add entry, an rw-cache-entry record that corresponds to rune, to the records
; associated with tag (which is 'rw-cache-any-tag or 'rw-cache-nil-tag) in
; ttree.

  (let* ((cache (tagged-objects tag ttree))
         (base (base-symbol rune))
         (recs (and cache ; optimization
                    (cdr (assoc-rw-cache base cache)))))
    (cond ((null cache)
           (extend-tag-tree tag
                            (list (cons base (list entry)))
                            ttree))
          (t (extend-tag-tree
              tag
              (put-assoc-rw-cache
               base
               (cons entry recs)
               cache)
              (remove-tag-from-tag-tree tag ttree))))))

(defstub rw-cache-debug
  (rune target unify-subst relieve-hyp-failure-reason step-limit)
  t)

(defstub rw-cache-debug-action
  (rune target unify-subst relieve-hyp-failure-reason step-limit)
  t)

(defun rw-cache-debug-builtin (rune target unify-subst failure-reason
                                    step-limit)
  (declare (ignore rune target unify-subst failure-reason step-limit)
           (xargs :guard t))
  nil)

(defun rw-cache-debug-action-builtin (rune target unify-subst failure-reason
                                           step-limit)
  (declare (xargs :guard t))
  (cw "@@ rw-cache-debug:~|~x0~|"
      (list :step-limit step-limit
            :rune rune
            :target target
            :unify-subst unify-subst
            :relieve-hyp-failure-reason failure-reason)))

(encapsulate
 (((rw-cacheable-failure-reason *) => *
   :formals (failure-reason)
   :guard (and (consp failure-reason)
               (posp (car failure-reason)))))
 (logic)
 (local (defun rw-cacheable-failure-reason (failure-reason)
          failure-reason)))

(defun rw-cacheable-failure-reason-builtin (failure-reason)

; This function recognizes non-free-failure reasons.  The guard is important
; for note-relieve-hyp-failure, as noted in a comment in its definition.

  (declare (xargs :guard (and (consp failure-reason)
                              (posp (car failure-reason)))))
  (and (consp (cdr failure-reason))
       (member-eq (cadr failure-reason) '(rewrote-to syntaxp bind-free))))

(defattach (rw-cacheable-failure-reason rw-cacheable-failure-reason-builtin)
  :skip-checks t)

(defun rw-cacheable-nil-tag (failure-reason)

; Failure-reason is assumed to satisfy rw-cacheable-failure-reason.  We return
; true if it is a reason we want to put into the "nil" cache, i.e., one that we
; generally expect to remain suitable when we strengthen the original context
; of the failure.

  (and (consp (cdr failure-reason))
       (cond ((eq (cadr failure-reason) 'rewrote-to)
              (equal (cddr failure-reason) *nil*))
             (t
              (assert$ (member-eq (cadr failure-reason)
                                  '(syntaxp bind-free))

; Quoting :doc bind-free (and similarly for syntaxp): "every variable occurring
; freely in term occurs freely in lhs or in some hypi, i<n."  So the
; unify-subst for which we obtained this failure-reason will continue to yield
; this failure-reason in stronger contexts.

                       t)))))

(defun note-relieve-hyp-failure (rune unify-subst failure-reason ttree hyps
                                      step-limit)

; We return the given ttree but with its rw-cache possibly extended according
; to the indicated failure information.  See the Essay on Rw-cache.

; We considered checking (rw-cache-list-lookup rune unify-subst recs), where
; recs is the list of rw-cache-entry records that may be extended, before
; making any such extension.  However, our intended use of this function is
; only for situations where a relieve-hyps call fails after a cache miss.  So a
; cache hit here would mean that the same relieve-hyps call failed in the
; course of relieving the original hyps.  That seems sufficiently rare not to
; justify the cost of the lookup, since the penalty is just an occasional
; duplicate entry.  Indeed, using a preliminary version of our rw-cache
; implementation, we found no such cases in community books
; books/workshops/2004/legato/support/proof-by-generalization-mult.lisp,
; books/workshops/2004/smith-et-al/support/bags/eric-meta.lisp, or an
; "insert-proof" example sent to us by Dave Greve.

  (cond
   ((and failure-reason ; could be nil; see "save some conses" in relieve-hyps1
         (rw-cacheable-failure-reason failure-reason))

; Since failure-reason is non-nil, we expect (just as in the guard on
; rw-cacheable-failure-reason) that (consp failure-reason) and (posp (car
; failure-reason)).

    (let* ((hyp (nth (1- (car failure-reason)) hyps))
           (entry (make rw-cache-entry
                        :unify-subst
                        (restrict-alist-to-all-vars
                         unify-subst

; In the case of a synp hypothesis, our possible restriction of unify-subst is
; based on the variables occurring free in the term that is to be evaluated.

                         (cond ((ffn-symb-p hyp 'synp)
                                (let ((qterm (fargn hyp 3)))
                                  (cond ((quotep qterm)

; Probably qterm is always a quotep, but we prefer to be cautious here.

                                         (unquote qterm))
                                        (t hyp))))
                               (t hyp)))
                        :failure-reason failure-reason
                        :hyp-info hyp
                        :step-limit step-limit))
           (ttree
            (cond ((rw-cacheable-nil-tag failure-reason)
                   (push-rw-cache-entry entry 'rw-cache-nil-tag rune ttree))
                  (t ttree))))
      (push-rw-cache-entry entry 'rw-cache-any-tag rune ttree)))
   (t ttree)))

(defun replace-free-rw-cache-entry1 (unify-subst hyps entry recs)

; Recs is a psorted list of rw-cache-entry records.  If some record in recs
; whose :failure-reason satisfies free-failure-p has the given unify-subst and
; hyps fields, then we replace it by the given entry.

  (cond ((endp recs)
         (list entry))
        ((and (not (eq (car recs) t))
              (free-failure-p (access rw-cache-entry (car recs)
                                      :failure-reason))
              (equal unify-subst
                     (access rw-cache-entry (car recs) :unify-subst))
              (equal hyps
                     (access rw-cache-entry (car recs) :hyp-info)))
         (cons entry (cdr recs)))
        (t (cons (car recs)
                 (replace-free-rw-cache-entry1 unify-subst hyps entry
                                               (cdr recs))))))

(defun replace-free-rw-cache-entry (entry tag rune unify-subst hyps ttree)

; Some existing entry in the "any" or "nil" cache of ttree (depending on tag),
; stored under the base-symbol of rune as the key, may have the given
; unify-subst and hyps.  If so, we replace it with entry.  Otherwise, we simply
; extend the list of entries by adding that entry to those for the given
; base-symbol.

; The "Otherwise" case didn't occur for many years, so it is probably rare.  At
; one time we thought that such an entry always exists in recs.  However, an
; example arose in which that was not the case.  What happened was that
; relieve-hyps called note-relieve-hyps-failure-free, which passed in an "old"
; rw-cache entry obtained from the input ttree, yet another argument was a
; ttree (passed along to the present function) returned by a call of
; relieve-hyps1 that no longer had the unify-subst where one might expect.  As
; noted above, we handle this (rare) case simply by adding the new entry.
; We believe that this is sound, since soundness doesn't depend on the
; rw-cache, whose only function is to defeat the rewriter.

  (let* ((cache (tagged-objects tag ttree))
         (base (base-symbol rune))
         (recs (cdr (assoc-rw-cache base cache))))

; At one time we asserted here that recs is non-nil.  Perhaps that is a valid
; assertion, but given the comment above about changes in the ttree, we are no
; longer all that confident about it.  Since it seems harmless to to this
; extension when recs is nil, we no longer assert recs.

    (extend-tag-tree
     tag
     (put-assoc-rw-cache
      base
      (replace-free-rw-cache-entry1 unify-subst hyps entry recs)
      cache)
     (remove-tag-from-tag-tree tag ttree))))

(defun rw-cache-alist-nil-tag-p (alist)

; Alist is an rw-cache-alist, i.e., an alist mapping unify-substs to
; failure-reasons.  We return true when there is at least one normal-failure
; reason somewhere within one of these failure-reasons that could belong in a
; "nil" cache.

  (cond ((endp alist) nil)
        (t (or (let ((failure-reason (cdar alist)))
                 (cond ((free-failure-p failure-reason)
                        (rw-cache-alist-nil-tag-p (cdr failure-reason)))
                       (t (rw-cacheable-nil-tag failure-reason))))
               (rw-cache-alist-nil-tag-p (cdr alist))))))

(defabbrev merge-free-failure-reasons-nil-tag (r1 r2)

; R1 is a failure reason satisfying free-failure-p, as is r2 unless r2 is nil.
; This function is analogous to combine-free-failure-reasons, but where we are
; merging into r2 only those parts of r1 that are suitable for the "nil" cache.

  (mv-let (flg alist)
          (merge-free-failure-alists-nil-tag (cdr r1) (cdr r2))
          (cond (flg (mv t r2))
                (t (assert$
                    alist ; even if r2 is nil, flg implies alist is not nil
                    (mv nil (cons :RW-CACHE-ALIST alist)))))))

(defun merge-free-failure-alists-nil-tag (a1 a2)

; Each of the arguments is an rw-cache-alist.  We merge the part of a1 suitable
; for a "nil" cache into a2 to obtain an rw-cache-alist, alist.  We return (mv
; flg alist), where if flg is true then alist is a2.

; See also combine-free-failure-alists for a related function for the "any"
; cache.

  (cond
   ((endp a1) (mv t a2))
   (t
    (let* ((failure-reason (cdar a1))
           (free-p (free-failure-p failure-reason)))
      (cond
       ((and (not free-p)
             (not (rw-cacheable-nil-tag failure-reason)))
        (merge-free-failure-alists-nil-tag (cdr a1) a2))
       (t ; then first update a2 with (car a1)
        (mv-let
         (flg a2)
         (let ((pair (assoc-equal (caar a1) a2)))
           (cond
            ((and pair (not (free-failure-p (cdr pair))))
             (mv t a2))   ; keep normal-failure reason
            ((not free-p) ; then (rw-cacheable-nil-tag failure-reason)
             (mv nil
                 (cond (pair (put-assoc-equal (caar a1) failure-reason a2))
                       (t (acons (caar a1) failure-reason a2)))))
            (t
             (mv-let
              (flg2 sub-reason)
              (merge-free-failure-reasons-nil-tag failure-reason (cdr pair))
              (cond
               (flg2 (mv t a2))
               (pair (mv nil (put-assoc-equal (caar a1) sub-reason a2)))
               (t (mv nil (acons (caar a1) sub-reason a2))))))))
         (cond
          (flg (merge-free-failure-alists-nil-tag (cdr a1) a2))
          (t ; a2 has been updated, so returned flag must be nil
           (mv-let
            (flg alist)
            (merge-free-failure-alists-nil-tag (cdr a1) a2)
            (declare (ignore flg))
            (mv nil alist)))))))))))

(defun note-rw-cache-free-nil-tag (rune unify-subst hyps ttree
                                        new-rw-cache-alist step-limit)
  (cond
   ((rw-cache-alist-nil-tag-p new-rw-cache-alist)
    (let* ((cache (tagged-objects 'rw-cache-nil-tag ttree))
           (base (base-symbol rune))
           (recs (and cache ; optimization
                      (cdr (assoc-rw-cache base cache))))
           (entry (rw-cache-list-lookup unify-subst hyps recs))
           (failure-reason (and entry (access rw-cache-entry entry
                                              :failure-reason))))
      (cond
       ((and entry
             (not (free-failure-p failure-reason)))
        ttree) ; odd case; keep the old normal-failure reason
       (t
        (mv-let
         (flg alist)
         (merge-free-failure-alists-nil-tag new-rw-cache-alist
                                            (cdr failure-reason))
         (cond
          (flg ttree)
          (entry
           (replace-free-rw-cache-entry
            (change rw-cache-entry entry
                    :failure-reason (cons :RW-CACHE-ALIST alist))
            'rw-cache-nil-tag rune unify-subst hyps ttree))
          (t
           (let ((new-entry (make rw-cache-entry
                                  :unify-subst unify-subst
                                  :failure-reason (cons :RW-CACHE-ALIST alist)
                                  :hyp-info hyps
                                  :step-limit step-limit)))
             (cond
              ((null cache)
               (extend-tag-tree 'rw-cache-nil-tag
                                (list (cons base (list new-entry)))
                                ttree))
              ((null recs)
               (extend-tag-tree
                'rw-cache-nil-tag
                (acons ; put-assoc-rw-cache
                 base
                 (cons new-entry nil)
                 cache)
                (remove-tag-from-tag-tree 'rw-cache-nil-tag ttree)))
              (t
               (push-rw-cache-entry new-entry 'rw-cache-nil-tag rune
                                    ttree)))))))))))
   (t ttree)))

(defun note-relieve-hyps-failure-free (rune unify-subst hyps ttree old-entry
                                            old-rw-cache-alist
                                            new-rw-cache-alist step-limit)

; We update ttree by replacing the existing rw-cache-entry record for
; rune, unify-subst, and hyps, namely old-rw-cache-alist, by one that is based
; on new-rw-cache-alist.

  (assert$
   new-rw-cache-alist
   (mv-let
    (flg alist)
    (cond
     (old-rw-cache-alist
      (combine-free-failure-alists new-rw-cache-alist old-rw-cache-alist))
     (t (mv nil new-rw-cache-alist)))
    (cond
     (flg ; If the "any" cache is unchanged, then so is the "nil" cache.
      ttree)
     (t
      (let ((ttree (note-rw-cache-free-nil-tag rune unify-subst hyps ttree
                                               new-rw-cache-alist step-limit)))
        (cond
         (old-entry
          (replace-free-rw-cache-entry
           (change rw-cache-entry old-entry
                   :failure-reason (cons :RW-CACHE-ALIST alist))
           'rw-cache-any-tag rune unify-subst hyps ttree))
         (t
          (push-rw-cache-entry
           (make rw-cache-entry
                 :unify-subst unify-subst
                 :failure-reason (cons :RW-CACHE-ALIST alist)
                 :hyp-info hyps
                 :step-limit step-limit)
           'rw-cache-any-tag rune ttree)))))))))

(defun rw-cache-enter-context (ttree)

; Restrict the "any" cache to the "nil" cache.

  (maybe-extend-tag-tree 'rw-cache-any-tag
                         (tagged-objects 'rw-cache-nil-tag ttree)
                         (remove-tag-from-tag-tree 'rw-cache-any-tag ttree)))

(defun erase-rw-cache (ttree)

; Erase all rw-cache tagged objects from ttree.  See also
; erase-rw-cache-from-pspv.

  (remove-tag-from-tag-tree
   'rw-cache-nil-tag
   (remove-tag-from-tag-tree 'rw-cache-any-tag ttree)))

(defun rw-cache-exit-context (old-ttree new-ttree)

; Return the result of modifying new-ttree by restoring the "nil" cache from
; old-ttree and by combining the "any" caches of the two ttrees.

  (mv-let (flg new-any)
          (combine-rw-caches

; If we reverse the order of arguments just below, then in the case that flg is
; t, we could avoid modifying the "any" cache of new-ttree in the case that it
; contains the "any" cache of old-ttree.  However, since rw-cache-enter-context
; clears the "any" cache except for entries from the "nil" cache, it could be
; relatively rare for the "any" cache of new-ttree to have grown enough to
; contain that of old-ttree.  Indeed, we expect that in general new-ttree could
; have a much smaller "any" cache than that of old-ttree, in which case we may
; do less consing by combining new into old, which is what we do.

           (tagged-objects 'rw-cache-any-tag new-ttree)
           (tagged-objects 'rw-cache-any-tag old-ttree))
          (declare (ignore flg))
          (maybe-extend-tag-tree
           'rw-cache-any-tag
           new-any
           (maybe-extend-tag-tree
            'rw-cache-nil-tag
            (tagged-objects 'rw-cache-nil-tag old-ttree)
            (erase-rw-cache new-ttree)))))

(defun restore-rw-cache-any-tag (new-ttree old-ttree)

; New-ttree has an "any" cache that was constructed in a context we do not
; trust for further computation; for example, the fnstack may have extended the
; current fnstack.  We restore the "any" cache of new-ttree to that of
; old-ttree.  While we may be happy to preserve the "nil" cache of new-ttree,
; we have an invariant to maintain: the "nil" cache is always contained in the
; "any" cache.  In a preliminary implementation we kept these two caches
; separate, at the cost of maintaining a third "nil-saved" cache, which added
; complexity.  In the present implementation, we preserve the invariant by
; throwing away new "nil" cache entries.  Early experiments with the regression
; suite suggest that performance does not suffer significantly with such
; deletion.  But it would be interesting to experiment with the alternate
; approach of extending the old "any" cache with the new "nil" cache.

  (maybe-extend-tag-tree
   'rw-cache-any-tag
   (tagged-objects 'rw-cache-any-tag old-ttree)
   (maybe-extend-tag-tree
    'rw-cache-nil-tag
    (tagged-objects 'rw-cache-nil-tag old-ttree)
    (erase-rw-cache new-ttree))))

(defun cons-tag-trees-rw-cache (ttree1 ttree2)

; This is cons-tag-trees, but with normalized rw-caches in the result.  This
; function, as is probably the case for all rw-cache functions, is purely
; heuristic.  So, it is fine to call cons-tag-trees instead of this function.
; But we think that cons-tag-trees-rw-cache might sometimes produce better
; results, by avoiding duplicate keys (base-symbols of runes), since such
; duplicates would make the second occurrence of the key invisible to
; rw-cache-list-lookup.

; We avoid the expense of calling this function when we expect that at least
; one of the ttrees is lacking rw-cache tags, for example because it was
; produced by operations defined before the rewrite nest (such as type-set and
; assume-true-false).

  (let ((rw-cache-any1 (tagged-objects 'rw-cache-any-tag ttree1))
        (rw-cache-any2 (tagged-objects 'rw-cache-any-tag ttree2))
        (rw-cache-nil1 (tagged-objects 'rw-cache-nil-tag ttree1))
        (rw-cache-nil2 (tagged-objects 'rw-cache-nil-tag ttree2)))

; The code below could be simplified by using only the case that all four of
; the above caches are non-nil.  But since we know which ones are nil and which
; ones are not, we might as well use that information to save a bit of
; computation.

    (cond
     ((and rw-cache-any1 rw-cache-any2)
      (mv-let
       (flg-any cache-any)
       (combine-rw-caches rw-cache-any1 rw-cache-any2)
       (declare (ignore flg-any))
       (cond
        ((and rw-cache-nil1 rw-cache-nil2)
         (mv-let
          (flg-nil cache-nil)
          (combine-rw-caches rw-cache-nil1 rw-cache-nil2)
          (declare (ignore flg-nil))
          (extend-tag-tree
           'rw-cache-any-tag
           cache-any
           (extend-tag-tree
            'rw-cache-nil-tag
            cache-nil
            (cons-tag-trees (erase-rw-cache ttree1)
                            (erase-rw-cache ttree2))))))
        (t
         (extend-tag-tree
          'rw-cache-any-tag
          cache-any
          (cons-tag-trees (remove-tag-from-tag-tree
                           'rw-cache-any-tag
                           ttree1)
                          (remove-tag-from-tag-tree
                           'rw-cache-any-tag
                           ttree2)))))))
     ((and rw-cache-nil1 rw-cache-nil2)
      (mv-let
       (flg-nil cache-nil)
       (combine-rw-caches rw-cache-nil1 rw-cache-nil2)
       (declare (ignore flg-nil))
       (extend-tag-tree
        'rw-cache-nil-tag
        cache-nil
        (cons-tag-trees (remove-tag-from-tag-tree
                         'rw-cache-nil-tag
                         ttree1)
                        (remove-tag-from-tag-tree
                         'rw-cache-nil-tag
                         ttree2)))))
     (t (cons-tag-trees ttree1 ttree2)))))

(defun normalize-rw-any-cache (ttree)
  (let ((cache (tagged-objects 'rw-cache-any-tag ttree)))
    (cond ((or (null cache)
               (sorted-rw-cache-p cache))
           ttree)
          (t (extend-tag-tree
              'rw-cache-any-tag
              (cons t (cdr-sort-rw-cache cache))
              (remove-tag-from-tag-tree
               'rw-cache-any-tag
               ttree))))))

(defun cons-tag-trees-rw-cache-first (ttree1 ttree2)

; Combine the two tag-trees, except that the rw-cache of the result is taken
; solely from ttree1.

  (maybe-extend-tag-tree
   'rw-cache-any-tag
   (tagged-objects 'rw-cache-any-tag ttree1)
   (maybe-extend-tag-tree
    'rw-cache-nil-tag
    (tagged-objects 'rw-cache-nil-tag ttree1)
    (cons-tag-trees (erase-rw-cache ttree1)
                    (erase-rw-cache ttree2)))))

(defmacro tag-tree-tags-subsetp (ttree tags)

; Note: Tag-tree primitive

  `(alist-keys-subsetp ,ttree ,tags))

(defun rw-cache (ttree)

; Restrict ttree to its rw-cache tagged objects.

  (cond ((tag-tree-tags-subsetp ttree
                                '(rw-cache-nil-tag rw-cache-any-tag))
         ttree)
        (t (maybe-extend-tag-tree
            'rw-cache-any-tag
            (tagged-objects 'rw-cache-any-tag ttree)
            (maybe-extend-tag-tree
             'rw-cache-nil-tag
             (tagged-objects 'rw-cache-nil-tag ttree)
             nil)))))

(defun rw-cached-failure-pair (unify-subst rw-cache-alist)

; We assume that rw-cache-active-p holds for the current rewrite-constant.

; This function returns (mv cached-free-failure-reason
; cached-normal-failure-reason), where at most one of the two returned values
; is non-nil and as the names suggest: the second is a normal sort of
; failure-reason (as recognized by rw-cacheable-failure-reason), while the
; first is a failure-reason satisfying free-failure-p.

  (let* ((cached-failure-reason-raw
          (and rw-cache-alist ; cheap optimization for (perhaps) common case
               (cdr (assoc-equal unify-subst rw-cache-alist))))
         (cached-failure-reason-free-p
          (and (consp cached-failure-reason-raw)
               (free-failure-p cached-failure-reason-raw))))
    (mv (and cached-failure-reason-free-p
             cached-failure-reason-raw)
        (and (not cached-failure-reason-free-p)
             cached-failure-reason-raw))))

(defun extend-rw-cache-alist-free (rcnst new-unify-subst
                                         inferior-rw-cache-alist-new
                                         rw-cache-alist-new)

; This function ultimately supports the extension of an rw-cache in the
; free-failure case.  If the rw-cache is active (as per rcnst), then we extend
; rw-cache-alist-new by associating a non-nil inferior-rw-cache-alist-new, an
; rw-cache-alist (see the definition of record structure rw-cache-entry) with
; new-unify-subst (which we generally expect to have no such association in
; rw-cache-alist).  See also rw-cache-add-failure-reason, which extends
; new-unify-subst in the case of a normal-failure reason.

  (cond ((and inferior-rw-cache-alist-new
              (rw-cache-active-p rcnst))
         (put-assoc-equal new-unify-subst
                          (cons :RW-CACHE-ALIST
                                inferior-rw-cache-alist-new)
                          rw-cache-alist-new))
        (t rw-cache-alist-new)))

(defun rw-cache-add-failure-reason (rcnst new-unify-subst
                                          failure-reason
                                          rw-cache-alist-new)

; If the rw-cache is active (as per rcnst), then this function extends
; rw-cache-alist-new by associating failure-reason, a normal-failure reason,
; with new-unify-subst (which we generally expect to have no such association
; in rw-cache-alist).  See also extend-rw-cache-alist-free, which is analogous
; but for a free-failure reason.

  (cond ((and (rw-cache-active-p rcnst)
              failure-reason ; always true?
              (rw-cacheable-failure-reason failure-reason))
         (acons new-unify-subst
                failure-reason
                rw-cache-alist-new))
        (t rw-cache-alist-new)))

(defun add-linear-lemma-finish (concl force-flg rune rewritten-p
                                      term type-alist wrld state
                                      simplify-clause-pot-lst rcnst ttree)

; We return (mv contradictionp new-pot-lst failure-reason brr-result), where
; new-pot-lst can be new-pot-lst can be :null-lst when rewritten-p is true, to
; indicate that another try is coming.

  (let ((lst (linearize concl
                        t
                        type-alist
                        (access rewrite-constant rcnst
                                :current-enabled-structure)
                        force-flg
                        wrld
                        (push-lemma rune ttree)
                        state)))
    (cond
     ((and (null lst) rewritten-p) ; another try is coming
      (mv nil :null-lst 'irrelevant 'irrelevant))
     ((cdr lst)
      (mv nil
          simplify-clause-pot-lst
          (if rewritten-p
              'linearize-rewritten-produced-disjunction
            'linearize-unrewritten-produced-disjunction)
          nil))
     ((null lst)

; This case is an optimization of the final case.  We do not know if this case
; can actually occur, but even if not, it's a cheap check and it is nice to
; have in case it could occur in the future even if not now.

      (mv nil simplify-clause-pot-lst nil nil))
     ((new-and-ugly-linear-varsp
       (car lst)
       (<= *max-linear-pot-loop-stopper-value*
           (loop-stopper-value-of-var
            term
            simplify-clause-pot-lst))
       term)
      (mv nil simplify-clause-pot-lst 'linear-possible-loop nil))
     (t
      (mv-let
       (contradictionp new-pot-lst)
       (add-polys (car lst)
                  simplify-clause-pot-lst
                  (access rewrite-constant rcnst :pt)
                  (access rewrite-constant rcnst :nonlinearp)
                  type-alist
                  (access rewrite-constant rcnst
                          :current-enabled-structure)
                  force-flg
                  wrld)
       (cond
        (contradictionp (mv contradictionp nil nil (car lst)))
        (t (mv nil
               (set-loop-stopper-values
                (new-vars-in-pot-lst new-pot-lst
                                     simplify-clause-pot-lst
                                     nil)
                new-pot-lst
                term
                (loop-stopper-value-of-var
                 term simplify-clause-pot-lst))
               nil
               (car lst)))))))))

(defun make-stack-from-alist (term alist)

; We wish to make a stack representing alist, so that term/stack is
; term/alist.  The stack will consist of a single frame.  We used to
; do this with

; (if alist (list (cons (strip-cars alist) (strip-cdrs alist))) nil).

; But that was incorrect.  The free variables of term must be among
; the vars bound by the frame.  (That is, we must imagine that term is
; the body of a lambda expression whose formals are the vars of the
; frame.)  So if term contains a variable not bound in alist then we
; must capture that variable and bind it to itself.

  (if alist
      (let* ((vars-of-term (all-vars term))
             (formals (strip-cars alist))
             (actuals (strip-cdrs alist))
             (free (set-difference-eq vars-of-term formals)))
        (list (cons (append free formals)
                    (append free actuals))))
    nil))

; The following two functions help us implement lambda-hide commuting,
; e.g., ((LAMBDA (x) (HIDE body)) arg) => (HIDE ((LAMBDA (x) body) arg)).

(defun lambda-nest-hidep (term)

; We return t iff term is a lambda nest with a HIDE as the inner-most
; body.  E.g.,
; (let ((st ...))
;   (let ((st ...))
;     (let ((st ...))
;       (HIDE ...))))

  (and (lambda-applicationp term)
       (let ((body (lambda-body (ffn-symb term))))
         (cond ((variablep body) nil)
               ((fquotep body) nil)
               ((eq (ffn-symb body) 'hide) t)
               (t (lambda-nest-hidep body))))))

(defun lambda-nest-unhide (term)

; We remove the HIDE from a lambda-nest-hidep term.

  (if (lambda-applicationp term)
      (make-lambda-application
       (lambda-formals (ffn-symb term))
       (lambda-nest-unhide (lambda-body (ffn-symb term)))
       (fargs term))
    (fargn term 1)))

(defabbrev memo-activep (memo)
  (or (eq memo :start) (consp memo)))

(defabbrev activate-memo (memo)
  (if (eq memo t) :start memo))

(defun intersection1-eq (x y)
  (declare (xargs :guard (and (true-listp x)
                              (true-listp y)
                              (or (symbol-listp x)
                                  (symbol-listp y)))))
  (cond ((endp x) nil)
        ((member-eq (car x) y) (car x))
        (t (intersection1-eq (cdr x) y))))

(defun forbidden-fns-in-term (term forbidden-fns)
  (intersection-eq (all-fnnames term) forbidden-fns))

(defun forbidden-fns-in-term-list (lst forbidden-fns)
  (intersection-eq (all-fnnames-lst lst) forbidden-fns))

(defun all-fnnames-lst-lst1 (cl-lst acc)
  (cond ((endp cl-lst) acc)
        (t (all-fnnames-lst-lst1 (cdr cl-lst)
                                 (all-fnnames1 t (car cl-lst) acc)))))

(defun forbidden-fns-in-term-list-list (cl-lst forbidden-fns)
  (intersection-eq (all-fnnames-lst-lst1 cl-lst nil) forbidden-fns))

(defun forbidden-fns (wrld state)

; We compute a value of forbidden-fns using the values of globals
; 'untouchable-fns and 'temp-touchable-fns and constant *ttag-fns*.  We might
; expect it to be necessary be concerned about untouchable variables, perhaps
; simply forbidding calls of makunbound-global and put-global; but the event
; (def-glcp-interp-thm glcp-generic-interp-w-state-preserved ...) in community
; book books/centaur/gl/gl-generic-interp.lisp actually calls put-global.  But
; the live state won't be an argument to any function call in the generated
; clause, so this isn't a concern.

  (let* ((forbidden-fns0 (cond ((eq (f-get-global 'temp-touchable-fns state)
                                    t)
                                nil)
                               ((f-get-global 'temp-touchable-fns state)
                                (set-difference-eq
                                 (global-val 'untouchable-fns wrld)
                                 (f-get-global 'temp-touchable-fns state)))
                               (t (global-val 'untouchable-fns wrld)))))
    (reverse-strip-cars
     (and (not (ttag wrld))

; Although translate11 allows the use of *ttag-fns* during the boot-strap, we
; would be surprised to see such use.  So we save the cost of the following
; test, but note here that it is likely OK to uncomment this test.

;         (not (global-val 'boot-strap-flg wrld))
          *ttag-fns*)
     forbidden-fns0)))

(set-table-guard skip-meta-termp-checks-table
                 (and (or (null val)
                          (ttag world))
                      (eq key t)
                      (or (eq val t)
                          (symbol-listp val)))
                 :topic set-skip-meta-termp-checks
                 :coda (and val
                            (not (ttag world))
                            (msg "An active trust tag is required for setting ~
                                  ~x0 except when clearing it."
                                 'skip-meta-termp-checks-table)))

(defmacro set-skip-meta-termp-checks! (x)
  (declare (xargs :guard (or (booleanp x)
                             (symbol-listp x))))
  `(table skip-meta-termp-checks-table t ',x))

(defmacro set-skip-meta-termp-checks (x)
  `(local (set-skip-meta-termp-checks! ,x)))

(defun skip-meta-termp-checks (fn wrld)
  (let ((val (cdr (assoc-eq t (table-alist 'skip-meta-termp-checks-table
                                           wrld)))))
    (or (eq val t)
        (and val ; optimization
             (member-eq fn val)))))

(defun collect-bad-fn-arity-info (alist wrld bad-arity-alist non-logic-fns)
  (cond
   ((endp alist)
    (if (or bad-arity-alist non-logic-fns)
        (cons (reverse bad-arity-alist) ; preserve original order
              non-logic-fns)
      nil))
   (t (let ((arity (arity (car (car alist)) wrld)))
        (collect-bad-fn-arity-info
         (cdr alist)
         wrld
         (if (or (null arity) ; handled below
                 (eql arity (cdr (car alist))))
             bad-arity-alist
           (cons (car alist) bad-arity-alist))
         (if (or (null arity)
                 (programp (car (car alist)) wrld))
             (cons (car (car alist))
                   non-logic-fns)
           non-logic-fns))))))

(defun bad-arities-msg (name token fn hyp-fn wf-thm-name1 wf-thm-name2
                             bad-arity-info)
  (msg
   "The ~s0 ~x1 has a now-invalid well-formedness guarantee.  Its ~s2, ~x3, ~
    ~#4~[was proved in ~x7 to return a ~x6~/and its corresponding hypothesis ~
    metafunction, ~x5, were proved in ~x7 and ~x8 to return ~x6s~] under the ~
    assumption that certain function symbols were in :logic mode and had ~
    certain arities.  But that assumption is now invalid, presumably because of ~
    redefinition.  ~@9We cannot trust the well-formedness guarantee."
   (if (eq token :META)
       "metatheorem"
     "clause-processor correctness theorem")
   name
   (if (eq token :META)
       (if fn
           "metafunction"
         "hypothesis metafunction")
     "clause-processor")
   (or fn hyp-fn)
   (if (and fn hyp-fn) 1 0)
   hyp-fn
   (if (eq token :META)
       'LOGIC-TERMP
     'LOGIC-TERM-LIST-LISTP)
   wf-thm-name1
   wf-thm-name2
   (let ((bad-arities-alist (car bad-arity-info))
         (non-logic-fns (cdr bad-arity-info)))
     (msg "~@0~@1"
          (if (null bad-arities-alist)
              ""
            (msg "The following alist pairs function symbols with their ~
                  assumed arities: ~X01.  Each symbol had the specified arity ~
                  when ~x2 was proved but this is no longer the case.  "
                 bad-arities-alist nil name))
          (if (null non-logic-fns)
              ""
            (msg "The symbol~#0~[ ~x0 is no longer a :logic mode function ~
                  symbol~/s ~&0 are no longer :logic mode function symbols~] ~
                  even though this was the case when ~x2 was proved.  "
                 non-logic-fns nil name))))))

; The following pair of macro definitions replaces function definitions that
; unnecessarily duplicated all-fnnames1 (and all-fnnames, all-fnnames-lst).
; This replacement doesn't perfectly preserve functionality, because the
; original versions below could return the list of function symbols in a
; different order than is returned by all-fnnames1 (and all-fnnames,
; all-fnnames-lst).  Perhaps we will eliminate these macros in the future.
(defmacro all-ffn-symbs (term ans)
  `(all-fnnames1 nil ,term ,ans))
(defmacro all-ffn-symbs-lst (lst ans)
  `(all-fnnames1 t ,lst ,ans))

(defun apply$-rule-name (fn)
  (declare (xargs :guard (symbolp fn)))
  (intern-in-package-of-symbol
   (coerce (append '(#\A #\P #\P #\L #\Y #\$ #\-)
                   (coerce (symbol-name fn) 'list))
           'string)
   fn))

(defun push-warrants (fns target type-alist ens wrld ok-to-force ttree ttree0)

; See the Essay on Evaluation of Apply$ and Loop$ Calls During Proofs.

; This function is called when *aokp* is nil and *warrant-reqs* is non-nil.

; Fns is a list of warranted function symbols, each an argument to
; apply$-userfn or badge-userfn during evaluation of target, which is the
; application of some function symbol to constants and may have subsidiary
; calls of apply$-userfn.  If ok-to-force is true, then we update ttree by
; forcing warrants that are not known, to justify the evaluation of target.
; Since one of the arguments is type-alist, we do not expect to call this
; function during preprocess-clause.  (This is reasonable since execution that
; is conditional on warrants isn't "simple", just as rules with hypotheses
; aren't simple.)

; We return (mv erp ttree), where if erp is nil then ttree extends the input
; ttree (which is initially ttree0) to justify that every symbol in fns has a
; warrant and to record the application of each rule APPLY$-fn.  This is a
; no-change loser: if erp is non-nil then the returned ttree is ttree0.  Note
; however that if ok-to-force is true, then erp will be nil.  If erp is
; non-nil, then the result depends on whether or not the apply$-rule-name is
; enabled.  If so, then erp is the function whose warrant is either false in
; the given context or else cannot be forced.  Otherwise, erp is a one-element
; list containing the apply$-rule-name.

; We overload ok-to-force just a bit.  At the top level it is Boolean.
; Otherwise, it can be :immediate or :force, meaning that it is ok to force
; (the top-level value of ok-to-force is t) and the mode is :immediate or not,
; respectively.

  (cond
   ((endp fns) (mv nil ttree))
   (t
    (let* ((fn (car fns))
           (warrant-name (warrant-name fn))
           (warrant (fcons-term* warrant-name))
           (apply$-rule-name (apply$-rule-name fn))
           (fn-apply$-rule (list :rewrite apply$-rule-name)))
      (assert$
       (and (function-symbolp warrant-name wrld)
            (logicp warrant-name wrld))
       (cond
        ((enabled-runep fn-apply$-rule ens wrld)
         (mv-let (knownp nilp ttree)
           (known-whether-nil warrant type-alist ens nil nil wrld ttree)
           (cond
            (knownp
             (cond
              ((not nilp)
               (push-warrants (cdr fns) target type-alist ens wrld ok-to-force
                              (push-lemma fn-apply$-rule ttree)
                              ttree0))
              (t

; The warrant is known to be false, which is presumably rare.  There is no
; point in trying to force the warrant, so we cause an error.

               (mv fn ttree0))))
            (ok-to-force
             (let* ((ok-to-force
                     (cond ((not (eq ok-to-force t))
                            ok-to-force)
; Else ok-to-force is t, and we convert it to :immediate or :force.
                           ((enabled-numep *immediate-force-modep-xnume*
                                           ens)
                            :immediate)
                           (t :force)))
                    (immediatep (eq ok-to-force :immediate)))
               (mv-let (force-flg ttree)
                 (force-assumption fn-apply$-rule target warrant type-alist nil
                                   immediatep t
                                   (push-lemma fn-apply$-rule ttree))
                 (declare (ignore force-flg)) ; still t
                 (push-warrants (cdr fns) target type-alist ens wrld ok-to-force
                                ttree ttree0))))
            (t ; Forcing is disallowed, so we cause an error.
             (mv fn ttree0)))))
        (t (mv (list apply$-rule-name) ttree0))))))))

(defconst *fake-rune-for-cert-data*
  '(:FAKE-RUNE-FOR-CERT-DATA nil))

(defconst *fake-rune-alist*

; We use this constant for dealing with fake runes in tag-trees.  We ignore
; *fake-rune-for-anonymous-enabled-rule*, because push-lemma is careful not to
; put it into any tag-trees.

  (list (cons (car *fake-rune-for-linear*)
              "linear arithmetic")
        (cons (car *fake-rune-for-linear-equalities*)
              "equality generation from inequalities")
        (cons (car *fake-rune-for-type-set*)
              "primitive type reasoning")
        (cons (car *fake-rune-for-cert-data*)
              "previously-computed data")))

(defun merge-runes (l1 l2)
  (cond ((null l1) l2)
        ((null l2) l1)
        ((rune-< (car l1) (car l2))
         (cons (car l1) (merge-runes (cdr l1) l2)))
        (t (cons (car l2) (merge-runes l1 (cdr l2))))))

(defun merge-sort-runes (l)
  (cond ((null (cdr l)) l)
        (t (merge-runes (merge-sort-runes (evens l))
                        (merge-sort-runes (odds l))))))

(defun fn-slot-from-geneqvp (geneqv)
  (cond ((endp geneqv) nil)
        ((eq 'fn-equal (access congruence-rule (car geneqv) :equiv))
         t)
        (t (fn-slot-from-geneqvp (cdr geneqv)))))

(defun partition-userfns-by-warrantp (fns wrld haves have-nots)

; Background: Rewrite-lambda-object, defined in the rewrite clique below, tries
; to rewrite the body of a well-formed quoted lambda object.  But it must first
; make sure that every function symbol occurring in the body either has a
; warrant or doesn't need one (by virtue of being an apply$ primitive or boot
; function).  If all the fns that need a warrant have one, it rewrites the body
; and then forces all the warrants that aren't among the hyps.  But if there
; are fns that don't even have warrants, it doesn't rewrite at all and, at
; most, prints a warning message that the lambda can't be rewritten for that
; reason.  So rewrite-lambda-object needs the list of all fns in the body that
; must have warrants to be apply$d and it needs the list of all fns in the body
; that don't have warrants.  (Note that the question of whether the required
; warrants are assumed true in the context is left unasked here.)

; So let fns be the list of all function symbols occurring the body, then this
; function ``partitions'' fns into those having warrants and those not having
; warrants but requiring them.  We quote ``partitions'' because apply$ primitives
; and apply$ boot functions are just left out all together!

  (cond ((endp fns) (mv haves have-nots))
        ((or
; The following hons-get is equivalent to (apply$-primp (car fns)).
          (hons-get (car fns) ; *badge-prim-falist* is not yet defined!
                    (unquote
                     (getpropc '*badge-prim-falist*
                               'const nil wrld)))
; We similarly inspect the value of *apply$-boot-fns-badge-alist*
          (assoc-eq (car fns)
                    (unquote
                     (getpropc '*apply$-boot-fns-badge-alist*
                               'const nil wrld))))
         (partition-userfns-by-warrantp (cdr fns) wrld haves have-nots))
        ((get-warrantp (car fns) wrld)
         (partition-userfns-by-warrantp (cdr fns) wrld
                                        (add-to-set-eq (car fns) haves)
                                        have-nots))
        (t
         (partition-userfns-by-warrantp (cdr fns) wrld
                                        haves
                                        (add-to-set-eq (car fns) have-nots)))))

(defun rewrite-lambda-object-pre-warning
    (evg not-well-formedp progs pre-have-no-warrants wrld)

; Evg is a lambda object whose body we did not even try to rewrite.  We explain
; why.  Not-well-formedp = t means that evg is not well-formed.  Otherwise,
; progs is the list of :program mode function symbols in the body and
; pre-have-no-warrants is the list of function symbols in the body for which no
; warrants have been issued but would require warrants for apply$ to handle
; them.  We print a rather verbose warning.  This warning can be avoided by
; doing (set-inhibit-warnings "rewrite-lambda-object").

; Note: Wrld is used in the expansion of warning$-cw1.

; Historical Note: Rewrite-lambda-object-pre-warning and
; rewrite-lambda-object-post-warning are sort of parallel, one reporting why we
; avoided rewriting and the other reporting why we rejected the rewrite we did.
; But they are structured somewhat differently for mainly historical reasons.
; The post-warning was done first and no explanation was ever offered for the
; not trying rewriting.  The pre-warning was added only after :program mode
; functions could find their way into well-formed lambdas.  The post-warning
; takes pains to warn the user about combinations of conditions while the
; pre-warning just warns of the first problem detected.  The post-warning
; recomputes the reasons even though the caller, rewrite-lambda-object,
; ``knew'' them, whereas the pre-warning is passed the information it needs to
; avoid recomputation.  These differences are largely just due to laziness!

  (let* ((violations
          (if not-well-formedp
              0
              (if progs
                  1
                  (if pre-have-no-warrants
                      2
                      3)))))
; violations =
; 0 - not well-formed
; 1 - one or more :program mode functions in body
; 2 - one or more symbols without warrants
; 3 - unknown reason for rejection

    (let ((state-vars (default-state-vars nil)))
      (warning$-cw1 'rewrite-lambda-object
                    "rewrite-lambda-object"
                    "We refused to try to rewrite the quoted lambda-like ~
                     object~%~Y01because ~#2~[it is not well-formed (e.g., ~
                     contains free variables, has a body that is not a term, ~
                     or that contains unbadged function symbols)~/it contains ~
                     the :program mode function symbol~#3~[~/s~] ~&3~/it ~
                     contains the function symbol~#4~[~/s~] ~&4 for which no ~
                     warrant~#4~[ has~/s have~] been issued~/we didn't like ~
                     it but failed to record why~].  See :DOC ~
                     rewrite-lambda-object."
                    evg
                    nil
                    violations
                    progs
                    pre-have-no-warrants))))

(defun rewrite-lambda-object-post-warning
    (evg rewritten-body post-have-no-warrants ttree wrld)

; Evg is a well-formed quoted lambda object whose body has been rewritten to
; rewritten-body using the runes in ttree.  Post-have-no-warrants is the list
; of function symbols (if any) in rewritten-body for which no warrants have
; been issued.  However, rewritten-body has been rejected for various reasons.
; We print a rather verbose warning explaining why.  This warning can be
; avoided by doing (set-inhibit-warnings "rewrite-lambda-object").

; Historical Note: See the note in rewrite-lambda-object-pre-warning about the
; differing styles of this function and its pre-warning version.

  (let* ((free-vars (set-difference-eq (all-vars rewritten-body)
                                       (lambda-object-formals evg)))
         (untamep (not (executable-tamep rewritten-body wrld)))
         (violations
          (if free-vars
              (if (cdr free-vars)
                  (if untamep 0 1)
                  (if untamep 2 3))
              (if untamep
                  4
                  (if post-have-no-warrants 5 6)))))
; violations =
; 0 - multiple free vars and untame
; 1 - multiple free vars [but tame]
; 2 - a single free var and untame
; 3 - a single free var [but tame]
; 4 - [no free vars] untame
; 5 - [no free vars and tame] but some fns have no warrants
; 6 - [no free vars, tame, fully warranted] some warrant assumed false

    (let ((state-vars (default-state-vars nil)))
      (warning$-cw1 'rewrite-lambda-object
                    "rewrite-lambda-object"
                    "The body of the well-formed (and tame) lambda ~
                     object~%~Y01rewrote to~%~Y21which was rejected because ~
                     ~#3~[it contains the variables ~&4 not listed among the ~
                     formals, and it is not tame~/it contains the variables ~
                     ~&4 not listed among the formals~/it contains the ~
                     variable ~&4 not listed among the formals, and it is not ~
                     tame~/it contains the variable ~&4 not listed among the ~
                     formals~/it is not tame~/it contains the function ~
                     symbol~#5~[ ~&5 for which no warrant has~/s ~&5 for ~
                     which no warrants have~] been issued~/some necessary ~
                     warrant is not assumed true in the current prover ~
                     environment~].  The following runes were used to produce ~
                     this rejected object: ~X61.  See :DOC ~
                     rewrite-lambda-object."
                    evg            ; lambda object
                    nil            ; evisc tuple -- print everything
                    `(lambda ,(lambda-object-formals evg)
                       ,rewritten-body) ; rejected body
                    violations     ; 0, 1, 2, 3, 4, 5, or 6
                    free-vars
                    post-have-no-warrants
                    (merge-sort-runes (all-runes-in-ttree ttree nil))))))

(defun collect-0-ary-hyps (type-alist)

; This function returns a type-alist to be used while rewriting the body of a
; quoted lambda object.  We collect every triple in type-alist that assigns a
; type-set to a call of a 0-ary function.  We are actually interested only in
; warrant hypotheses, but there is no harm in collecting other variable-free
; assumptions.  We could even collect the bindings for terms not sharing any
; variables with the locals of the target lambda object, but that might invite
; the introduction of an unbound free var into the rewritten body.  For
; example, the type-alist might include the assumption of (INTEGERP I) and
; while the lambda object formals are just LOOP$-GVARS and LOOP$-IVARS.  But if
; a rewrite rule has a free variable to be assigned by finding some integer,
; the inclusion of this (INTEGERP I) hyp might cause the rewritten body to
; mention I, which would invalidate the lambda body and cause the entire
; rewrite to be abandoned.  So we just don't ``import'' anything but
; variable-free assumptions at the moment.

  (cond ((endp type-alist) nil)
        ((and (consp (car (car type-alist)))
              (null (cdr (car (car type-alist)))))
         (cons (car type-alist)
               (collect-0-ary-hyps (cdr type-alist))))
        (t (collect-0-ary-hyps (cdr type-alist)))))

; Essay on Rewriting Quoted Constants

; ACL2 (and Nqthm before it) never rewrote quoted constants.  In the days
; before user-defined equivalence relations there was no point, since no two
; distinct quoted constants are EQUAL.  (The special handling of IFF slots is
; the exception that proves the utility of the idea, as illustrated below.)
; However, with user-defined equivalences, it is conceivable that two distinct
; (mod EQUAL) constants are equivalent and that one is preferred over the
; other.  It is sort of surprising that ACL2 has supported user-defined
; equivalence and congruence based rewriting for 15 years or so without
; identifying this little weakness in its rewriter.

; For example,

; Example A: one might wish to replace '23 by 'T in a slot where IFF is being
;            maintained.

; Example B: one might wish to replace '(C A B A . 77) by '(A B C) in a slot
;            where SET-EQUALP is being maintained.

; Example C: one might wish to replace '(LAMBDA (X) X) by 'IDENTITY in a slot
;            where FN-EQUAL is being maintained.

; Such replacements cannot be done now because ACL2 won't apply a rewrite rule
; to a quoted constant.  (One can phrase rewrite rules that operate on the
; parent term containing the constant, e.g., if foo is a function that admits
; IFF as as a congruence in its first argument, one might prove (equal (foo 23
; lst) (foo t lst)).  Another such example would be:

; (set-equal (set-union '(C A B A . 77) u)
;            (set-union '(A B C) u))

; but this workaround is unsatisfactory because one needs such a rule for each
; function admitting the equivalence relation as a congruence.  We suspect that
; the reason this weakness in the rewriter was never identified is that user's
; employed this workaround on an as-needed basis.

; To facilitate the rewriting of quoted constants we will add a new rule-class,
; :rewrite-quoted-constant, and a new world global called
; rewrite-quoted-constant-rules which is just a list of ordinary :rewrite rule
; records (but tagged :rewrite-quoted-constant in the :subclass), each of which
; is derived from a corollary of one of these three forms:

; [1] (IMPLIES hyps (equiv 'lhs-evg 'rhs-evg))
; [2] (IMPLIES hyps (equiv (fn x) x)), where x is a variable.
; [3] (IMPLIES hyps (equiv lhs-term rhs-term))

; We now explain how such rules are used.  When the rewriter encounters (QUOTE
; target-evg), it will scan down rewrite-quoted-constant-rules processing each
; rule in turn until it finds the first ``applicable'' rule.  Then it does the
; ``replacement'' described below.

; A rule is ``applicable'' exactly in the sense that an ordinary :rewrite rule
; is, except for how we match the lhs of the rule with the target.  In
; particular, to be applicable the rule must be enabled, the equiv of the rule
; must refine the equiv being maintained by the rewriter, the lhs of the rule
; must ``match'' the target-evg as described below, and the hyps must be
; relieved, etc.  In addition, for a form [2] rule to be applicable, the
; executable counterpart of the fn named in the rule must be enabled.

; The notion of ``match'' for evgs is a bit strange:
;  - a form [1] rule matches when lhs-evg is exactly target-evg.
;  - a form [2] rule matches any target-evg!
;  - a form [3] rule matches if its lhs one-way-unifies with (QUOTE target-evg).

; The ``replacement'' directed by an applicable rule is as follows:
;  - a form [1] rule replaces the target-evg by the rhs-evg
;  - a form [2] rule replaces the target-evg by the (non-erroneous) result of
;    calling the executable counterpart of fn on the target-evg.
;  - a form [3] rule replaces (QUOTE target-evg) by the (rewritten) instantiated
;    rhs-term.

; Notice that the replacement performed by a form [3] rule might not yield a
; quoted constant, but that's ok.

; Rewrite rules generally have a loop-stopper entry in the :heuristic-info
; field of the record.  In the case of rewrite-quoted-constant rules -- which
; are in fact represented by rewrite-rule records but stored in the
; rewrite-quoted-constant-rules global variable -- the :heuristic-info is (n
; . loop-stopper), where n is the form number.  Rules of form [1] and [2] can't
; actually have non-nil loop-stoppers because the variables mentioned in the
; loop-stopper must be distinct and occur in both the lhs and rhs.  But we go
; ahead and compute and store the (usually nil) loop-stopper.

; Worked Examples:

; Here are :rewrite-quoted-constant rules for addressing Examples A, B, and C
; above.  We also add an Example D that illustrates why some Form [1] rules
; might require hypotheses even though the conclusion of a Form [1] rule is a
; ground term.

; Example A: one might wish to replace '23 by 'T in a slot where IFF is being
;            maintained.

; Solution:
; (IFF '23 'T)                                     ; Form [1]
; or, more generally,
; (IMPLIES (AND X (SYNTAXP (NOT (EQUAL X ''NIL)))) ; Form [3]
;          (IFF X 'T))

; The Form [3] rule shown above illustrates why :rewrite-quoted-constant rules
; can't be easily stored as normal :rewrite rules, i.e., on the lemmas property
; of the top function symbol of the lhs.  Here there is no ``top function
; symbol.''

; Example B: one might wish to replace '(C A B A . 77) by '(A B C) in a slot
;            where SET-EQUALP is being maintained.

; Solution:
; (SET-EQUALP (NORMALIZE-SET X) X)                 ; Form [2]

; where NORMALIZE-SET is a function that coerces a non-true-list to a
; true-list, removes duplicates, and sorts a list.  Of course, this example
; could also be coded as the Form [1] rule (SET-EQUALP '(C A B A . 77) '(A B
; C)).  But that raises the question: does it work recursively down the
; cdr-chain of a set?  For example, would the user expect the Form [1] rule to
; replace '(D C A B A . 77) by '(D A B C)?  After all, the lhs-evg does occur
; in a SET-EQUALP slot of the target-evg.  But we decided Form [1] rules will
; only hit at the top-level so that the regression isn't slowed down by them
; when large quoted constants arise.  If you want to sweep the target-evg for
; opportunities, use a Form [2] rule and code the sweep yourself.  Form [2]
; rules are like metafunctions, but only apply to quoted constant terms and so
; the Form [2] rule itself is all you need to prove to effect the
; transformation.

; Example C: one might wish to replace '(LAMBDA (X) X) by 'IDENTITY in a slot
;            where FN-EQUAL is being maintained.
; Solution:
; (FN-EQUAL '(LAMBDA (X) X) 'IDENTITY)             ; Form [1]
; or more generally
; (IMPLIES (SYMBOLP V)                             ; Form [3]
;          (FN-EQUAL (LIST 'LAMBDA (LIST V) V)
;                    'IDENTITY))

; Example D: one might wish to replace '(LAMBDA (X) (FOO X)) by
;            '(LAMBDA (X) (BAR X)) in a slot where FN-EQUAL is
;            being maintained.

; Solution:
; (IMPLIES (WARRANT FOO BAR)                      ; Form [1]
;          (FN-EQUAL '(LAMBDA (X) (FOO X))
;                    '(LAMBDA (X) (BAR X))))
; This illustrates how the equivalence of two quoted constants might
; require a hypothesis.

(defconst *rewrite-lambda-modep-xrune*
  '(:EXECUTABLE-COUNTERPART REWRITE-LAMBDA-MODEP))

(defconst *rewrite-lambda-modep-def-rune*
  '(:DEFINITION REWRITE-LAMBDA-MODEP))

(defun formal-cons-to-components (term)

; Term is a translated term.  This function returns (mv flg car cdr).  If flg
; is nil, term does not represent a CONS term.  Otherwise it does and car and
; cdr are the first and second args of that CONS term.  The only tricky thing
; about this function is that term might be a quoted constant.

  (cond ((variablep term) (mv nil nil nil))
        ((fquotep term)
         (let ((evg (unquote term)))
           (if (consp evg)
               (mv t
                   (kwote (car evg))
                   (kwote (cdr evg)))
               (mv nil nil nil))))
        ((eq (ffn-symb term) 'cons)
         (mv t (fargn term 1) (fargn term 2)))
        (t (mv nil nil nil))))

(defun recover-subst-from-formal-var-alist (term)

; We return (mv flg sigma).  If flg is t then term is the translation of (list
; (cons 'var1 val1) ... (cons 'vark valk)), where each vari is a legal variable
; name and sigma is the substitution ((var1 . val1) ... (vark . valk)).  Else,
; we return (mv nil nil).  (Technically, a substitution should have no
; duplicate keys, but sublis-var ignores all but the first binding.)

; Note the similarity of this function with formal-alist-to-alist-on-vars.  But
; that function also strips out assoc-eq-safe calls from the vals!  So don't be
; confused!

  (cond
   ((variablep term) (mv nil nil))
   ((equal term *nil*) (mv t nil))
   (t (mv-let (flg pair rest)
        (formal-cons-to-components term)
        (cond
         ((null flg) (mv nil nil))
         (t (mv-let (flg key val)
              (formal-cons-to-components pair)
              (cond
               ((null flg) (mv nil nil))
               ((and (quotep key)
                     (eq (legal-variable-or-constant-namep (unquote key))
                         'variable))
                (mv-let (flg sigma)
                  (recover-subst-from-formal-var-alist rest)
                  (cond
                   ((null flg) (mv nil nil))
                   (t (mv t (cons (cons (unquote key) val) sigma))))))
               (t (mv nil nil))))))))))

(defun extend-subst-on-unbound-vars (vars alist)

; For every var in vars that is not already bound in alist we add (var . 'nil)
; to alist.

  (cond
   ((endp vars) alist)
   ((assoc-eq (car vars) alist)
    (extend-subst-on-unbound-vars (cdr vars) alist))
   (t (cons (cons (car vars) *nil*)
            (extend-subst-on-unbound-vars (cdr vars) alist)))))

(defmacro rewrite-standard-exit (fn rewritten-args)
  `(sl-let
    (rewritten-term ttree)
    (rewrite-entry
     (rewrite-primitive ,fn ,rewritten-args))
    (rewrite-entry
     (rewrite-with-lemmas
      rewritten-term))))

(mutual-recursion

; State is an argument of rewrite only to permit us to call ev.  In general,
; wrld may be an extension of (f-get-global 'current-acl2-world state), but we
; use state only to pass it down to ev.

; Keep this nest in sync with mfc-rw+ and pc-rewrite*.

(defun rewrite (term alist bkptr ; &extra formals
                     rdepth step-limit
                     type-alist obj geneqv pequiv-info wrld state fnstack
                     ancestors backchain-limit
                     simplify-clause-pot-lst rcnst gstack ttree)

; Comments on the function REWRITE

; The Input
; c term:        the "matrix" term we are to rewrite.
; c alist:       a substitution we are to apply to term before rewriting it.
; h type-alist:  a list of assumptions governing this rewrite
;   obj:         (objective of rewrite) t, nil, or ? - of heuristic use only.
; c geneqv:      a generated equivalence relation to maintain
; c pequiv-info: info on patterned equivalence relations (pequivs) to maintain
;   wrld:        the current world
;   fnstack:     fns and terms currently being expanded - of heuristic use only
; h ancestors:   a list of terms assumed true, modified as we backchain.
; h backchain-limit: of heuristic use only
; h simplify-clause-pot-lst: a pot-lst of polys
; h rcnst:       the rewrite constant arguments
; h ttree:       the evolving ttree describing the rewrites.
;   rdepth:      maximum allowed stack depth - of heuristic use only
;   step-limit:  number of recursive calls permitted for rewrite

; The Output:
; a new step-limit, a term term', and a tag-tree ttree'

; The Specification of Rewrite: The axioms in wrld permit us to infer that the
; Rewrite Assumption implies that term' is equivalent via geneqv+pequiv-info to
; term/alist.  One can write this "wrld |- h -> c."  The args are tagged with h
; and c according to how they are involved in this spec.

; The Rewrite Assumption: the conjunction of (a) the assumptions in type-alist,
; (b) the assumptions in ancestors, (c) the assumption of every "active" poly
; in simplify-clause-pot-lst (where a poly is inactive iff its tag-tree
; contains a 'pt containing some literal number that occurs in the :pt field of
; rcnst), and (d) the 'assumptions in the final tag-tree ttree'.

; Observe that if there are 'assumptions in the incoming ttree they are unioned
; into those made by this rewrite.  Thus, unless you want the assumptions to
; accumulate across many rewrites, you must use the empty initial tag-tree.  It
; would be incorrect to attempt to split on the "new" assumptions in the new
; tag-tree because of the unioning.

; The first value is the rewritten term.  The second is the final
; value of ttree.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (let ((gstack (push-gframe 'rewrite bkptr term alist obj geneqv))
         (rdepth (adjust-rdepth rdepth)))
     (declare (type #.*fixnat-type* rdepth))
     (cond
      ((zero-depthp rdepth)
       (rdepth-error
        (mv step-limit (sublis-var alist term) ttree)))
      ((time-limit5-reached-p
        "Out of time in the rewriter (rewrite).") ; nil, or throws
       (mv step-limit nil nil))
      ((variablep term)
       (rewrite-entry
        (rewrite-solidify-plus (let ((temp (assoc-eq term alist)))
                                 (cond (temp (cdr temp))
                                       (t term))))))
      ((fquotep term)
       (rewrite-entry
        (rewrite-quoted-constant term)))
      ((eq (ffn-symb term) 'if)

; Normally we rewrite (IF a b c) by rewriting a and then one or both
; of b and c, depending on the rewritten a.  But in the special case
; (IF a b b) we just rewrite and return b.  We have seen examples
; where this comes up, e.g., before nth-update-rewriter was removed in
; Version_7.0, it could produce such IFs.

       (cond
        ((equal (fargn term 2) (fargn term 3))
         (rewrite-entry
          (rewrite (fargn term 2) alist 2)))
        (t
         (sl-let (rewritten-test ttree)
                 (rewrite-entry
                  (rewrite (fargn term 1) alist 1)

; When we rewrite the test of the if we use geneqv iff.  What about
; obj.  Mostly we'll use '?.  But there are a few special cases.
; Suppose you are rewriting (if t1 'nil 't) with the objective t.
; Then you should rewrite t1 with the objective nil.  This actually
; comes up in the handling of (<= x y).  That term opens to (if (< y
; x) 'nil 't).  If we had an obj of t initially, and we don't look
; into the if to see which way the branches go, then we rewrite the (<
; y x) with obj '? and miss an opportunity to use linear arithmetic.

; After Version_3.2.1 we added some more special cases.  Consider the
; following example supplied by Robert Krug.

;    (defstub quux (x) t)
;
;    (defaxiom quux-thm-1
;      (<= x (quux x))
;      :rule-classes :linear)
;
;    (defaxiom quux-thm-2
;      (integerp (quux x)))
;
;    ; Good
;
;    (defstub foo-1 (x) t)
;
;    (defun bar-1 (x)
;      (or (not (integerp x))
;          (< 4 x)))
;
;    (defaxiom foo-1-thm
;      (implies (bar-1 (quux x))
;               (foo-1 x)))
;
;    (thm  ; good
;     (implies (and (integerp x)
;                   (integerp y)
;                   (< 2 x)
;                   (< 2 y))
;              (foo-1 (+ x y))))

; Robert pointed out that if instead we switched the order of
; disjuncts in bar-1, the thm fails: (< 4 x) has moved to a test
; position and we had only passed a t or nil :obj down to the true and
; false branches.

;    (defstub foo-2 (x) t)
;
;    (defun bar-2 (x)
;      (or (< 4 x)
;          (not (integerp x))))
;
;    (defaxiom foo-2-thm
;      (implies (bar-2 (quux x))
;               (foo-2 x)))
;
;    (thm  ; bad
;     (implies (and (integerp x)
;                   (integerp y)
;                   (< 2 x)
;                   (< 2 y))
;              (foo-2 (+ x y))))

; Our goal, then, is to recognize the symmetry of OR, AND, and the
; like.  But if we do that naively then we miss the proof of the thm
; in the following case, because (or u v) expands to (if u u v) rather than to
; (if u t v).

;    (defstub foo-3 (x) t)
;
;    (defstub bar-3 (x) t)
;
;    (defaxiom bar-3-open
;      (equal (bar-3 x)
;             (or (< 4 x)
;                 (foo-3 (append x x)) ; optional extra challenge, since this
;                                      ; doesn't rewrite to a constant
;                 (not (integerp x)))))
;
;    (defaxiom foo-3-thm
;      (implies (bar-3 (quux x))
;               (foo-3 x)))
;
;    (thm  ; bad
;     (implies (and (integerp x)
;                   (integerp y)
;                   (< 2 x)
;                   (< 2 y))
;              (foo-3 (+ x y))))

; Therefore, we treat (if u u v) the same as (if u t v) for purposes
; of establishing the :obj.

                  :obj
                  (cond
                   ((eq obj '?) '?)
                   (t (let ((arg2 (if (equal (fargn term 1)
                                             (fargn term 2))
                                      *t*
                                    (fargn term 2))))
                        (cond ((quotep arg2)

; Since (if u  t  v) is essentially (or u v), :obj is same for u and v
; Since (if u nil v) is essentially (and (not u) v), :obj flips for u and v

                               (if (unquote arg2) obj (not obj)))
                              (t (let ((arg3 (fargn term 3)))
                                   (cond ((quotep arg3)

; Since (if u v  t ) is essentially (or (not u) v), :obj flips for u and v
; Since (if u v nil) is essentially (and u v), :obj is same for u and v

                                          (if (unquote arg3) (not obj) obj))
                                         (t '?))))))))
                  :geneqv *geneqv-iff*
                  :pequiv-info nil)
                 (rewrite-entry (rewrite-if rewritten-test
                                            (fargn term 1)
                                            (fargn term 2)
                                            (fargn term 3)
                                            alist))))))
      ((and (eq (ffn-symb term) 'return-last)

; We avoid special treatment for a return-last term when the first argument is
; 'progn, since the user may have intended the first argument to be rewritten
; in that case; consider for example (prog2$ (cw ...) ...).  But it is useful
; in the other cases, in particular for calls of return-last generated by calls
; of mbe, to avoid spending time rewriting the next-to-last argument.

            (not (equal (fargn term 1) ''progn)))
       (rewrite-entry
        (rewrite (fargn term 3) alist 3)
        :ttree (push-lemma
                (fn-rune-nume 'return-last nil nil wrld)
                ttree)))
      ((eq (ffn-symb term) 'hide)

; We are rewriting (HIDE x).  Recall the substitution alist.  We must
; stuff it into x.  That is, if the term is (HIDE (fn u v)) and alist
; is ((u . a) (v . b)), then we must return something equal to (HIDE
; (fn a b)).  We used to sublis-var the alist into the term.  But that
; may duplicate large terms.  So as of Version  2.6 we actually create
; (HIDE ((lambda (u v) x) a b)) or, equivalently, (HIDE (LET ((u a) (v
; b)) x)).

; Care must be taken to ensure that there are no free vars in the
; lambda.  We therefore use make-stack-from-alist to create a stack.
; This stack contains (at most) a single frame consisting of the
; appropriate formals and actuals.

; Also recall :EXPAND hints.  We must check whether we have been told
; to expand this guy.  But which guy?  (HIDE (fn a b)) or (HIDE (LET
; ((u a) (v b)) x))?  We actually ask about the latter because the
; former may be prohibitive to compute.  The fact that HIDEs are
; changed a little may make it awkward for the user to formulate
; :EXPAND or HIDE-rewrite hints without waiting to see what comes out.


       (let* ((stack (make-stack-from-alist (fargn term 1) alist))
              (inst-term (if alist
                             (fcons-term* 'hide
                                          (make-lambda-application
                                           (caar stack)
                                           (fargn term 1)
                                           (cdar stack)))
                           term))
              (new-rcnst (expand-permission-p inst-term rcnst geneqv
                                              wrld)))
         (cond
          (new-rcnst

; We abandon inst-term and rewrite the hidden part under the alist.

           (rewrite-entry (rewrite (fargn term 1) alist 1)
                          :ttree (push-lemma
                                  (fn-rune-nume 'hide nil nil wrld)
                                  ttree)
                          :rcnst new-rcnst))
          (t (rewrite-entry
              (rewrite-with-lemmas inst-term))))))
      ((lambda-nest-hidep term)

; This clause of rewrite implements ``lambda-hide commuting''.  The
; idea is that ((LAMBDA (x) (HIDE body)) actual) can be rewritten to
; (HIDE ((LAMBDA (x) body) actual)).  But, as above, we must be
; careful with the free vars.  (Note: the term is a well-formed lambda
; application, so we know the obvious about the free vars of its body
; versus its formals.  But that is not the question!  The question is:
; what variables are bound in alist?  There is no a priori
; relationship between term and alist.)

       (let* ((new-body (lambda-nest-unhide term))
              (stack (make-stack-from-alist new-body alist))
              (inst-term
               (fcons-term* 'HIDE
                            (if alist
                                (make-lambda-application
                                 (caar stack)
                                 new-body
                                 (cdar stack))
                              new-body)))
              (new-rcnst (expand-permission-p inst-term rcnst geneqv
                                              wrld)))
         (cond
          (new-rcnst

; We rewrite the ``instantiated'' term under the empty substitution.

           (rewrite-entry (rewrite (fargn inst-term 1) nil 1)
                          :ttree (push-lemma
                                  (fn-rune-nume 'hide nil nil wrld)
                                  ttree)
                          :rcnst new-rcnst))
          (t (rewrite-entry
              (rewrite-with-lemmas inst-term))))))
      ((eq (ffn-symb term) 'IMPLIES)

; We handle IMPLIES specially.  We rewrite both the hyps and the
; concl under the original type-alist, and then immediately return the
; resulting expansion.  This prevents the concl from being rewritten
; under the (presumably) more powerful type-alist gotten from assuming
; the hyps true until after any normalization has occurred.  See the
; mini-essay at assume-true-false-if.

; It is possible that this rewriting will force some hypotheses in a
; ``context free'' way, i.e., forcing might occur while rewriting the
; concl but the forced assumption won't record the hypotheses that
; might actually be necessary to establish the assumption.  This is
; not supposed to happen because the only IMPLIES we should see
; (barring any introduced by user supplied rewrite rules) are in :USE
; hyps, and their hyps are normally provable under the hyps of the
; original theorem -- and those original hyps are in the type-alist
; defining this context.

       (sl-let
        (rewritten-test ttree)
        (rewrite-entry (rewrite (fargn term 1) alist 1)
                       :obj '?
                       :geneqv *geneqv-iff*
                       :pequiv-info nil)
        (cond
         ((equal rewritten-test *nil*)
          (mv step-limit *t* ttree))
         (t
          (sl-let (rewritten-concl ttree)
                  (rewrite-entry (rewrite (fargn term 2) alist 2)
                                 :obj '?
                                 :geneqv *geneqv-iff*
                                 :pequiv-info nil)
                  (cond
                   ((equal rewritten-concl *nil*)
                    (mv step-limit
                        (dumb-negate-lit rewritten-test)
                        ttree))
                   ((or (quotep rewritten-concl) ; not *nil*
                        (equal rewritten-test rewritten-concl))
                    (mv step-limit *t* ttree))
                   ((quotep rewritten-test) ; not *nil*

; We already handle the case above that rewritten-test is *nil*.  So (implies
; test concl) almost simplifies to rewritten-concl, the issue being that
; implies returns a boolean but rewritten-concl might not be Boolean.  At this
; point we have already handled the case that rewritten-concl is a quotep (so,
; there is no opportunity at this point to simplify, for example, '3 to 't);
; but we could perhaps simplify here by checking that the rewritten-concl has a
; Boolean type-set.  However, it seems unlikely that such extra computational
; effort would be worthwhile, since calls of implies can generally be expected
; to be in a Boolean context, and we already optimize for that case just below.

                    (let ((rune
                           (geneqv-refinementp 'iff geneqv wrld)))
                      (cond
                       (rune (mv step-limit
                                 rewritten-concl
                                 (push-lemma rune ttree)))
                       (t (mv step-limit
                              (fcons-term* 'if
                                           rewritten-concl
                                           *t*
                                           *nil*)
                              ttree)))))
                   (t (mv step-limit
                          (subcor-var

; It seems reasonable to keep this in sync with the corresponding use of
; subcor-var in rewrite-atm.

                           (formals 'IMPLIES wrld)
                           (list rewritten-test rewritten-concl)
                           (bbody 'IMPLIES))
                          ttree))))))))
      ((eq (ffn-symb term) 'double-rewrite)
       (sl-let
        (term ttree)
        (rewrite-entry (rewrite (fargn term 1) alist 1))
        (rewrite-entry (rewrite term nil bkptr)
                       :ttree (push-lemma (fn-rune-nume 'double-rewrite
                                                        nil nil wrld)
                                          ttree))))
      ((not-to-be-rewrittenp
        term
        alist
        (access rewrite-constant rcnst
                :terms-to-be-ignored-by-rewrite))
       (prepend-step-limit
        2
        (rewrite-solidify (sublis-var alist term)
                          type-alist obj geneqv
                          (access rewrite-constant rcnst
                                  :current-enabled-structure)
                          wrld ttree
                          simplify-clause-pot-lst
                          (access rewrite-constant rcnst :pt))))
      (t
       (let ((fn (ffn-symb term)))
         (mv-let (term ttree)
           (if (and (eq fn 'DO$)
                    (quotep (fargn term 6))
                    (unquote (fargn term 6)))

; We rewrite any non-nil quoted irrelevant arg of a DO$ call to 'nil and blame
; DO$.  It's a mild stretch to blame this on DO$ since technically it's an
; inductively proved lemma about DO$.

               (mv (cons-term fn
                              (list (fargn term 1)
                                    (fargn term 2)
                                    (fargn term 3)
                                    (fargn term 4)
                                    (fargn term 5)
                                    *nil*))
                   (push-lemma (fn-rune-nume 'do$ nil nil wrld)
                               ttree))
               (mv term ttree))
           (mv-let (mv-nth-result mv-nth-rewritep)
             (if (eq fn 'mv-nth)
                 (simplifiable-mv-nth term alist)
                 (mv nil nil))
             (cond
              (mv-nth-result

; This is a special case.  We are looking at a term/alist of the form (mv-nth
; 'i (cons x0 (cons x1 ... (cons xi ...)...))) and we immediately rewrite it to
; xi.  The mv-nth-result either needs further rewriting under the alist (when
; mv-nth-rewritep is t) or was taken from the alist and needs no further
; rewriting (in which case we finish by calling rewrite-solidify-plus, since
; this case is similar to the variablep case of rewrite).  Before we did this,
; we would rewrite x0, x1, etc., all of which are irrelevant.  This code is
; helpful because of the way (mv-let (v0 v1 ... vi ...) (foo ...)  (p v0 ...))
; is translated.  Note however that the bkptr we report in the rewrite entry
; below is 2, i.e., we say we are rewriting the 2nd arg of the mv-nth, when in
; fact we are rewriting a piece of it (namely xi).

               (let ((ttree (push-lemma
                             (fn-rune-nume 'mv-nth nil nil wrld)
                             ttree))
                     (step-limit (1+f step-limit)))
                 (declare (type #.*fixnum-type* step-limit))
                 (if mv-nth-rewritep
                     (rewrite-entry
                      (rewrite mv-nth-result alist 2))
                     (rewrite-entry
                      (rewrite-solidify-plus mv-nth-result)))))
              (t
               (let ((ens (access rewrite-constant rcnst
                                  :current-enabled-structure)))
                 (mv-let
                   (deep-pequiv-lst shallow-pequiv-lst)
                   (pequivs-for-rewrite-args fn geneqv pequiv-info wrld ens)
                   (sl-let
                    (rewritten-args ttree)
                    (rewrite-entry
                     (rewrite-args (fargs term) alist 1 nil
                                   deep-pequiv-lst shallow-pequiv-lst
                                   geneqv fn)
                     :obj '?
                     :geneqv
                     (geneqv-lst fn geneqv ens wrld)
                     :pequiv-info nil ; ignored
                     )
                    (cond
                     ((and
                       (or (flambdap fn)
                           (logicp fn wrld))
                       (all-quoteps rewritten-args)
                       (or
                        (flambda-applicationp term)
                        (and (enabled-xfnp fn ens wrld)

; We don't mind disallowing constrained functions that have attachments,
; because the call of ev-fncall below disallows the use of attachments (last
; parameter, aok, is nil).  Indeed, we rely on this check in chk-live-state-p.

                             (not (getpropc fn 'constrainedp nil wrld)))))

; Note: The test above, if true, leads here where we execute the
; executable-counterpart of the fn (or just go into the lambda
; expression if it's a lambda application).  The test however is
; obscure.  What it says is "run the function if (a) it is either a
; lambda or a :logic function symbol, (b) all of its args are quoted
; constants, and either (c1) the fn is a lambda expression, or (c2)
; the fn is enabled and fn is not a constrained fn."  Thus,
; constrained fns fail the test.  Defined functions pass the test
; provided such functions are currently toggled.  Undefined functions
; (e.g., car) pass the test.

                      (cond
                       ((flambda-applicationp term)
                        (rewrite-entry
                         (rewrite (lambda-body fn)
                                  (pairlis$ (lambda-formals fn)
                                            rewritten-args)
                                  'lambda-body)))
                       (t
                        (let ((ok-to-force (ok-to-force rcnst)))
                          (mv-let
                            (erp val apply$ed-fns)
                            (pstk
                             (ev-fncall+ fn
                                         (strip-cadrs rewritten-args)

; The strictp argument is nil here, as we will deal with required true warrants
; in push-warrants, below.  See the Essay on Evaluation of Apply$ and Loop$
; Calls During Proofs.

                                         nil
                                         state))
                            (mv-let
                              (erp2 ttree)
                              (cond ((or erp

; No special action is necessary if apply$ed-fns is nil, as opposed to a
; non-empty list.

                                         (null apply$ed-fns))
                                     (mv erp ttree))
                                    (t (push-warrants
                                        apply$ed-fns
                                        (cons-term fn rewritten-args)
                                        type-alist ens wrld ok-to-force
                                        ttree ttree)))
                              (cond
                               (erp2

; We following a suggestion from Matt Wilding and attempt to rewrite the term
; before applying HIDE.  This is really a heuristic choice; we could choose
; always to apply HIDE, as we did before v2-8.  So we do not apply
; rewrite-primitive (as in the last COND clause, below) as this would only
; apply in the rare case that the current function symbol (whose evaluation has
; errored out) is a compound recognizer.

                                (let ((new-term1
                                       (cons-term fn rewritten-args)))
                                  (sl-let
                                   (new-term2 ttree)
                                   (rewrite-entry
                                    (rewrite-with-lemmas new-term1))
                                   (cond
                                    ((equal new-term1 new-term2)
                                     (mv step-limit
                                         (hide-with-comment
                                          (if erp
                                              (cons :non-executable erp)
                                              (cons :missing-warrant erp2))
                                          new-term1
                                          wrld state)
                                         (push-lemma
                                          (fn-rune-nume 'hide nil nil
                                                        wrld)
                                          ttree)))
                                    (t (mv step-limit new-term2 ttree))))))
                               (t (mv step-limit
                                      (kwote val)
                                      (push-lemma
                                       (fn-rune-nume fn nil t wrld)
                                       ttree))))))))))
                     ((and (eq fn 'EV$)
                           (global-val 'projects/apply/base-includedp wrld)
                           (active-runep '(:rewrite ev$-opener)) ; uses ens!
                           (quotep (car rewritten-args)))

; We're looking at (EV$ 'x y).  Under certain conditions we'll rewrite this EV$
; call by rewriting x under sigma'.  If those conditions are not met we just
; ``fall through'' to the rewriter's normal handling of a non-special-case
; function call.

; The conditions are that x must be a tame term, every function in it has been
; warranted, all the warrants are true in type-alist or can be forced, we can
; recover from y a substitution, sigma.  Sigma', mentioned above, is just the
; extension of sigma obtained by binding to 'nil all free variables of x that
; are not bound in sigma.

; This special processing of certain EV$ calls can be skipped by disabling
; (:rewrite ev$-opener), a rewrite rule in projects/apply/base.lisp.  We
; confirm that that book has been included so that we know the rewrite rule of
; that name really is our rule.

                     (let ((x (unquote (car rewritten-args)))
                           (y (cadr rewritten-args)))
                       (mv-let (flg sigma)
                         (recover-subst-from-formal-var-alist y)
                         (cond
                          ((null flg)
                           (rewrite-standard-exit fn rewritten-args))
                          ((not (and (termp x wrld)
                                     (executable-tamep x wrld)))
                           (rewrite-standard-exit fn rewritten-args))
                          (t (mv-let (warranted-fns unwarranted-fns)
                             (partition-userfns-by-warrantp (all-fnnames x)
                                                            wrld nil nil)
                             (cond
                              (unwarranted-fns
                               (rewrite-standard-exit fn rewritten-args))
                              (t (let ((new-alist
                                        (extend-subst-on-unbound-vars
                                         (all-vars x)
                                         sigma)))
                                   (mv-let (erp ttree1)
                                     (push-warrants
                                      warranted-fns
                                      term type-alist ens wrld
                                      (ok-to-force rcnst)
                                      (push-lemma?
                                       (active-runep '(:rewrite ev$-opener))
                                       ttree)
                                      ttree)
                                  (cond
                                   (erp
                                    (rewrite-standard-exit fn rewritten-args))
                                   (t

; Note that every variable in x is bound in new-alist to a term that has been
; recovered from rewritten-args, so the type-alist and the other data being
; passed into this recursive call of rewrite legitimately describes the current
; context.  Note also that as soon as rewrite sees a variable symbol it looks
; it up in alist, transferring its attention to the binding.

                                    (rewrite-entry
                                     (rewrite x new-alist
                                              'expansion)
                                     :ttree ttree1)))))))))))))
                     (t (rewrite-standard-exit fn rewritten-args))))))))))))))))

(defun rewrite-solidify-plus (term ; &extra formals
                              rdepth step-limit
                              type-alist obj geneqv pequiv-info wrld state
                              fnstack ancestors backchain-limit
                              simplify-clause-pot-lst rcnst gstack ttree)

; This function allows us one more try at relieving a hypothesis by rewriting
; with lemmas when rewrite-solidify isn't sufficient.  The call of
; rewrite-with-lemmas1 below can allow a hypothesis to be relieved when the
; term in question was previously rewritten in an equality context, rather than
; the more generous propositional context that we have available when relieving
; a hypothesis.

; For a motivating example, see the item in note-2-9 (proofs) starting with:
; "The rewriter has been modified to work slightly harder in relieving
; hypotheses."

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (mv-let (new-term new-ttree)
           (rewrite-solidify term type-alist obj geneqv
                             (access rewrite-constant rcnst
                                     :current-enabled-structure)
                             wrld ttree
                             simplify-clause-pot-lst
                             (access rewrite-constant rcnst :pt))
           (cond ((or (eq obj '?)

; Keep the next four conditions in sync with those in rewrite-with-lemmas.

                      (variablep new-term)
                      (fquotep new-term)
                      (member-equal (ffn-symb new-term)
                                    (access rewrite-constant rcnst
                                            :fns-to-be-ignored-by-rewrite))
                      (flambda-applicationp term)
                      (not (equal geneqv *geneqv-iff*))
                      (not (equal term new-term)))
                  (mv step-limit new-term new-ttree))
                 (t
                  (sl-let (rewrittenp term1 ttree)
                          (rewrite-entry

; We are tempted to call rewrite here.  But the point of this call is to handle
; the case that term was the result of looking up a variable in an alist, where
; the term has already been rewritten but perhaps not under *geneqv-iff*.  All
; we really want to do here is to make another pass through the lemmas in case
; one of them applies this time.

                           (rewrite-with-lemmas1
                            term
                            (getpropc (ffn-symb new-term) 'lemmas nil wrld)))
                          (declare (ignore rewrittenp))
                          (mv step-limit term1 ttree)))))))

(defun assume-true-false-heavy-linearp (test ; &extra formals
                                        rdepth step-limit
                                        type-alist obj geneqv pequiv-info
                                        wrld state
                                        fnstack ancestors
                                        backchain-limit
                                        simplify-clause-pot-lst
                                        rcnst gstack ttree)

; This is the interface to assume-true-false when rewriting is done when rcst
; specifies the use of heavy-linearp.

  (declare (ignore obj))
  (mv-let (must-be-true
           must-be-false
           true-type-alist
           false-type-alist
           ts-ttree)

; See the long comment above the calls of assume-true-false in rewrite-if.

    (assume-true-false test nil
                       (ok-to-force rcnst)
                       nil type-alist
                       (access rewrite-constant rcnst
                               :current-enabled-structure)
                       wrld
                       simplify-clause-pot-lst
                       (access rewrite-constant rcnst :pt)
                       nil)
    (cond
     ((or must-be-true must-be-false)
      (mv step-limit must-be-true must-be-false
          true-type-alist false-type-alist
          simplify-clause-pot-lst simplify-clause-pot-lst ts-ttree))
     (t ; Note that ts-ttree is irrelevant.
      (let ((test+ (list test)))
      (sl-let
         (contradictionp true-pot-lst)
         (rewrite-entry
          (add-terms-and-lemmas test+ nil t)
          :obj t)
         (cond
          (contradictionp
           (mv step-limit nil t nil false-type-alist
               nil simplify-clause-pot-lst
               (push-lemma
                *fake-rune-for-linear*
                (access poly contradictionp :ttree))))
          (t
           (sl-let
            (contradictionp false-pot-lst)
            (rewrite-entry
             (add-terms-and-lemmas test+ nil nil)
             :obj nil)
            (cond
             (contradictionp
              (mv step-limit t nil true-type-alist nil
                  simplify-clause-pot-lst nil
                  (push-lemma
                   *fake-rune-for-linear*
                   (access poly contradictionp :ttree))))
             (t (mv step-limit nil nil true-type-alist false-type-alist
                    true-pot-lst false-pot-lst nil))))))))))))

(defun rewrite-if-finish (test unrewritten-test left right alist
                               swapped-p
                               must-be-true must-be-false
                               true-type-alist false-type-alist
                               true-pot-lst false-pot-lst
                               ts-ttree ; &extra formals
                               rdepth step-limit
                               type-alist obj geneqv pequiv-info wrld state
                               fnstack ancestors backchain-limit
                               simplify-clause-pot-lst rcnst gstack ttree)
  (cond
   (must-be-true
    (if (and unrewritten-test
             (geneqv-refinementp 'iff geneqv wrld)
             (equal unrewritten-test left))
        (mv step-limit *t* (cons-tag-trees ts-ttree ttree))
      (rewrite-entry (rewrite left alist 2)
                     :type-alist true-type-alist
                     :simplify-clause-pot-lst true-pot-lst
                     :ttree (cons-tag-trees ts-ttree ttree))))
   (must-be-false
    (rewrite-entry (rewrite right alist 3)
                   :type-alist false-type-alist
                   :simplify-clause-pot-lst false-pot-lst
                   :ttree (cons-tag-trees ts-ttree ttree)))
   (t (let ((ttree (normalize-rw-any-cache ttree)))
        (sl-let
         (rewritten-left ttree)
         (if (and unrewritten-test
                  (geneqv-refinementp 'iff geneqv wrld)
                  (equal unrewritten-test left))
             (mv step-limit *t* ttree)
           (sl-let (rw-left ttree1)
                   (rewrite-entry (rewrite left alist 2)
                                  :type-alist true-type-alist
                                  :simplify-clause-pot-lst true-pot-lst
                                  :ttree (rw-cache-enter-context ttree))
                   (mv step-limit
                       rw-left
                       (rw-cache-exit-context ttree ttree1))))
         (sl-let (rewritten-right ttree1)
                 (rewrite-entry (rewrite right alist 3)
                                :type-alist false-type-alist
                                :simplify-clause-pot-lst false-pot-lst
                                :ttree (rw-cache-enter-context
                                        ttree))
                 (mv-let
                   (rewritten-term ttree)
                   (rewrite-if1 test
                                rewritten-left rewritten-right
                                swapped-p
                                type-alist geneqv
                                (access rewrite-constant rcnst
                                        :current-enabled-structure)
                                (ok-to-force rcnst)
                                wrld
                                (rw-cache-exit-context ttree ttree1))
                   (rewrite-entry
                    (rewrite-with-lemmas
                     rewritten-term)))))))))

(defun rewrite-if (test unrewritten-test left right alist ; &extra formals
                        rdepth step-limit
                        type-alist obj geneqv pequiv-info wrld state fnstack
                        ancestors backchain-limit
                        simplify-clause-pot-lst rcnst gstack ttree)

; Test is the result of rewriting unrewritten-test under the same alist and
; extra formals.  Except, unrewritten-test can be nil, in which case we of
; course make no such claim.

; Warning: If you modify this function, consider modifying the code below a
; comment mentioning rewrite-if in rewrite-with-lemmas.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (mv-let
     (test unrewritten-test left right swapped-p)
     (cond
      ((and (ffn-symb-p test 'if)
            (equal (fargn test 2) *nil*)
            (equal (fargn test 3) *t*))

; Note: In Nqthm the equality test against *t* was a known-whether-nil check.
; But unrewritten-test has been rewritten under equiv = 'iff.  Hence, its two
; branches were rewritten under 'iff.  Thus, if one of them is known non-nil
; under the type-alist then it was rewritten to *t*.

       (mv (fargn test 1) nil right left t))
      (t (mv test unrewritten-test left right nil)))
     (cond
      ((quotep test)

; It often happens that the test rewrites to *t* or *nil* and we can
; avoid the assume-true-false below.

       (if (cadr test)
           (if (and unrewritten-test ; optimization (see e.g. rewrite-if above)
                    (geneqv-refinementp 'iff geneqv wrld)
                    (equal unrewritten-test left))

; We are in the process of rewriting a term of the form (if x x y), which
; presumably came from an untranslated term of the form (or x y).  We do not
; want to rewrite x more than once if we can get away with it.  We are using
; the fact that the following is a theorem:  (iff (if x x y) (if x t y)).
; We will use this observation later in the body of this function as well.

               (mv step-limit *t* ttree)
             (rewrite-entry (rewrite left alist 2)))
         (rewrite-entry (rewrite right alist 3))))
      ((eq (access rewrite-constant rcnst :heavy-linearp) :heavy)
       (sl-let (must-be-true
                must-be-false
                true-type-alist
                false-type-alist
                true-pot-lst
                false-pot-lst
                ts-ttree)
               (rewrite-entry (assume-true-false-heavy-linearp test))
               (rewrite-entry
                (rewrite-if-finish test unrewritten-test left right alist
                                   swapped-p
                                   must-be-true must-be-false
                                   true-type-alist false-type-alist
                                   true-pot-lst false-pot-lst
                                   ts-ttree))))
      (t (mv-let (must-be-true
                  must-be-false
                  true-type-alist
                  false-type-alist
                  ts-ttree)

; Once upon a time, the call of assume-true-false below was replaced by a call
; of repetitious-assume-true-false.  See the Essay on Repetitive Typing.  This
; caused a terrible slowdown in the proof of the Nqthm package theorems (e.g.,
; the proof of AX-20-2 seemed never to complete but was not apparently
; looping).  It was apparently due to the opening of MEMBER on a long constant
; list and each time doing a repetition on an increasingly long type-alist (but
; this is just speculation).  For a simple example of a problem that arises if
; repetition is used here, consider the example problem shown with the Satriani
; hack above.  (Search for make-standard-codes.)  Try that thm both with an
; assume-true-false and a repetitious-assume-true-false here.  The former takes
; 3.87 seconds; the latter takes about 13.37 seconds.  The problem is that we
; keep assuming tests of the form (EQUAL X '#\a) on a type-alist that contains
; a litany of all the chars X is not equal to, i.e., a type-alist containing
; such triples as ((EQUAL X '#\b) 64 ; (*ts-nil*)) for lots of different #\b's.
; On the true branch, we add the pair that X is of type *ts-character* and then
; reconsider every one of the (EQUAL X '#\b) assumptions previously posted.

; Note: Running that example will also illustrate another oddity.  You will see
; successive duplicate calls of assume-true-false on the (EQUAL X '#\a)'s.
; What is happening?  In opening (MEMBER X '(#\a ...)) in rewrite-fncall we
; rewrite the body of member, producing the first call of assume-true-false
; when we consider (equal x (car lst)).  The result of rewriting the body is
; essentially an instance of the body; the recursive call within it is unopened
; because member is recursive (!).  Then we decide to keep the rewrite and
; rewrite the body again.  So we again assume-true-false the instance of the
; just produced (EQUAL X '#\a).

; If ancestors is non-nil, ACL2 is backchaining to relieve the hypothesis of
; some rule.  Conversely, if ancestors is nil, ACL2 is rewriting a term in the
; current clause.  As of v2_8 if ACL2 is backchaining, we use the new and
; stronger assume-true-false capability of milking the linear pot.  We apply
; the extra power when backchaining because ACL2's operations are largely
; invisible to the user when backchaining.  The main effect of using
; assume-true-false this way is to cause recursive definitions to open up a
; little more aggressively.  (Since the simplify-clause-pot-lst is passed in,
; linear arithmetic --- via type-reasoning --- can decide the truth or falsity
; of more inequalities than otherwise, causing more if expressions to
; collapse.  This may eliminate recursive calls that would otherwise be passed
; up to rewrite-fncallp and have to be accepted as heuristically simpler.  It
; could also change the too-many-ifs situation.)  We do not apply the extra
; power when rewriting the current clause, because it is potentially expensive
; and the user can see (and therefore change) what is going on.

           (if ancestors
               (assume-true-false test nil
                                  (ok-to-force rcnst)
                                  nil type-alist
                                  (access rewrite-constant rcnst
                                          :current-enabled-structure)
                                  wrld
                                  simplify-clause-pot-lst
                                  (access rewrite-constant rcnst :pt)
                                  nil)
             (assume-true-false test nil
                                (ok-to-force rcnst)
                                nil type-alist
                                (access rewrite-constant rcnst
                                        :current-enabled-structure)
                                wrld nil nil nil))
           (rewrite-entry
            (rewrite-if-finish test unrewritten-test left right alist
                               swapped-p
                               must-be-true must-be-false
                               true-type-alist false-type-alist
                               simplify-clause-pot-lst simplify-clause-pot-lst
                               ts-ttree))))))))

(defun rewrite-args (args alist bkptr rewritten-args-rev
                          deep-pequiv-lst shallow-pequiv-lst
                          parent-geneqv parent-fn ; &extra formals
                          rdepth step-limit
                          type-alist obj geneqv pequiv-info wrld state fnstack
                          ancestors backchain-limit
                          simplify-clause-pot-lst rcnst gstack ttree)

; Note: In this function, the extra formal geneqv is actually a list of geneqvs
; or nil denoting a list of nil geneqvs.

; See the Essay on Patterned Congruences and Equivalences for a discussion of
; non-&extra formals of this function.  Note our assumption in function
; geneqv-for-rewrite that every pequiv in shallow-pequiv-lst has an enabled
; :congruence-rule; this holds because of how shallow-pequiv-lst is created by
; the call of pequivs-for-rewrite-args in rewrite.  Also note that pequiv-info
; is ignored in this function and that deep-pequiv-lst can be the special
; value, :none, which is handled by function pequiv-info-for-rewrite.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit)
           (ignore pequiv-info))
  (the-mv
   3
   #.*fixnum-type*
   (cond ((null args)
          (mv step-limit (reverse rewritten-args-rev) ttree))
         (t (mv-let
             (child-geneqv child-pequiv-info)
             (geneqv-and-pequiv-info-for-rewrite
              parent-fn bkptr rewritten-args-rev args alist
              parent-geneqv
              (car geneqv)
              deep-pequiv-lst
              shallow-pequiv-lst
              wrld)
             (sl-let
              (rewritten-arg ttree)
              (rewrite-entry (rewrite (car args) alist bkptr)
                             :geneqv child-geneqv
                             :pequiv-info child-pequiv-info)
              (rewrite-entry
               (rewrite-args (cdr args) alist (1+ bkptr)
                             (cons rewritten-arg rewritten-args-rev)
                             deep-pequiv-lst shallow-pequiv-lst
                             parent-geneqv parent-fn)
               :pequiv-info nil ; ignored
               :geneqv (cdr geneqv))))))))

(defun rewrite-primitive (fn args ; &extra formals
                             rdepth step-limit
                             type-alist obj geneqv pequiv-info wrld state
                             fnstack ancestors backchain-limit
                             simplify-clause-pot-lst rcnst gstack
                             ttree)

  (declare (ignore geneqv pequiv-info obj)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((flambdap fn) (mv step-limit (fcons-term fn args) ttree))
    ((eq fn 'equal)
     (rewrite-entry (rewrite-equal (car args) (cadr args) nil nil)
                    :obj '?
                    :geneqv nil
                    :pequiv-info nil ; ignored
                    ))
    (t (let* ((ens (access rewrite-constant rcnst
                           :current-enabled-structure))
              (recog-tuple (most-recent-enabled-recog-tuple fn wrld ens)))
         (cond
          (recog-tuple
           (prepend-step-limit
            2
            (rewrite-recognizer recog-tuple (car args) type-alist
                                ens
                                (ok-to-force rcnst)
                                wrld
                                ttree
                                simplify-clause-pot-lst
                                (access rewrite-constant rcnst :pt))))
          (t (mv step-limit (cons-term fn args) ttree))))))))

(defun rewrite-equal (lhs rhs lhs-ancestors rhs-ancestors ; &extra formals
                          rdepth step-limit
                          type-alist obj geneqv pequiv-info wrld state fnstack
                          ancestors backchain-limit
                          simplify-clause-pot-lst rcnst gstack ttree)

; We rewrite and return a term equivalent to (EQUAL lhs rhs), plus a ttree.
; We keep lists lhs-ancestors and rhs-ancestors of lhs and rhs parameters from
; superior calls, in order to break loops as explained below.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((equal lhs rhs)
     (mv step-limit *t* (puffert ttree)))
    ((and (quotep lhs)
          (quotep rhs))
     (mv step-limit *nil* (puffert ttree)))
    (t
     (mv-let
      (ts-lookup ttree-lookup)
      (assoc-type-alist (fcons-term* 'equal lhs rhs) type-alist wrld)
      (cond
       ((and ts-lookup (ts= ts-lookup *ts-t*))
        (mv step-limit *t* (cons-tag-trees ttree-lookup ttree)))
       ((and ts-lookup (ts= ts-lookup *ts-nil*))
        (mv step-limit *nil* (cons-tag-trees ttree-lookup ttree)))
       (t
        (let ((ens (access rewrite-constant rcnst
                           :current-enabled-structure))
              (ok-to-force (ok-to-force rcnst)))
          (mv-let
           (ts-lhs ttree-lhs)
           (type-set lhs ok-to-force nil
                     type-alist ens wrld ttree
                     simplify-clause-pot-lst
                     (access rewrite-constant rcnst :pt))
           (mv-let
            (ts-rhs ttree+)
            (type-set rhs ok-to-force nil
                      type-alist ens wrld ttree-lhs
                      simplify-clause-pot-lst
                      (access rewrite-constant rcnst :pt))
            (mv-let
             (ts-equality ttree-equality)
             (type-set-equal ts-lhs ts-rhs ttree+ ttree)
             (cond
              ((ts= ts-equality *ts-t*)
               (mv step-limit *t* ttree-equality))
              ((ts= ts-equality *ts-nil*)
               (mv step-limit *nil* ttree-equality))

; The commented-out case just below, here explicitly before we added the above
; call of type-set-equal, is handled by that call.

;           ((ts-disjointp ts-lhs ts-rhs)
;            (mv *nil* (puffert ttree+)))

              ((equal-x-cons-x-yp lhs rhs)

; Recall that the correctness of a positive answer by equal-x-cons-x-yp doesn't
; rely on type-set knowledge.

               (mv step-limit *nil* (puffert ttree)))
              ((and (ts-subsetp ts-lhs *ts-boolean*)
                    (equal rhs *t*))
               (mv step-limit lhs (puffert ttree-lhs)))
              ((and (ts-subsetp ts-rhs *ts-boolean*)
                    (equal lhs *t*))
               (mv step-limit rhs (puffert ttree+)))
              ((equal lhs *nil*)
               (mv step-limit (mcons-term* 'if rhs *nil* *t*) (puffert ttree)))
              ((equal rhs *nil*)
               (mv step-limit (mcons-term* 'if lhs *nil* *t*) (puffert ttree)))
              ((equalityp lhs)
               (mv step-limit (mcons-term* 'if
                                           lhs
                                           (mcons-term* 'equal rhs *t*)
                                           (mcons-term* 'if rhs *nil* *t*))
                   (puffert ttree)))
              ((equalityp rhs)
               (mv step-limit
                   (mcons-term* 'if
                                rhs
                                (mcons-term* 'equal lhs *t*)
                                (mcons-term* 'if lhs *nil* *t*))
                   (puffert ttree)))
              ((and (ts-subsetp ts-lhs *ts-cons*)
                    (ts-subsetp ts-rhs *ts-cons*)
                    (not (member-equal lhs lhs-ancestors))
                    (not (member-equal rhs rhs-ancestors)))

; If lhs and rhs are both of type cons, we (essentially) recursively rewrite
; the equality of their cars and then of their cdrs.  If either of these two
; tests fails, this equality is nil.  If both succeed, this one is t.
; Otherwise, we don't rewrite term.

; Before attempting to add complete equality we did not do anything like this
; and relied solely on elim to do it for us.  In the first attempt to add it to
; rewrite we just rewrote all such (EQUAL lhs rhs) to the conjunction of the
; equalities of the components.  That was unsatisfactory because it caused such
; equalities as (EQUAL (ADDTOLIST X L) B) to be torn up all the time.  That
; caused us to fail to prove thms like SORT-OF-ORDERED-NUMBER-LIST because weak
; subgoals are pushed -- subgoals about (CAR (ADDTOLIST X L)) and (CDR
; (ADDTOLIST X L)) instead about (ADDTOLIST X L) itself.

; In Version_3.3 and earlier (even as far back as Version_2.2) we rewrote
; equality terms (equal (car lhs) (car rhs)) and (equal (cdr lhs) (cdr rhs)),
; with variables lhs and rhs bound to the parameters lhs and rhs.  But now we
; instead call the rewriter separately on the car and cdr of lhs and rhs (hence
; "essentially" in a paragraph above).  Then to check equality we finish using
; a recursive call of rewrite-equal with lhs and rhs pushed on to the stacks
; lhs-ancestors and rhs-ancestors (respectively).  We avoid making a recursive
; call if we see that we have looped back to a call with the same lhs or rhs,
; which indicates a potential infinite loop.  When we formerly called the full
; rewriter on (equal (car lhs) (car rhs)) and (equal (cdr lhs) (cdr rhs)), We
; did not make such a check and we found an infinite loop in the following
; example (a slight simplification of one Sol Swords sent to us); see just
; below for analysis.

; (thm (implies (and (consp y)
;                    (consp (car y))
;                    (equal (caar y) y))
;               (equal y (car y))))

; If you try the following trace on the above example using Version_3.3, where
; we called rewrite on applications of equal to the two cars and the two cdrs

; (trace$ (rewrite :entry (list 'rewrite term alist type-alist))
;         (rewrite-equal :entry (list 'r-e lhs rhs type-alist)))

; then you will see a loop as follows.

;  98> (R-E Y
;           (CAR Y)
;           (((CAR (CAR Y)) 1536)
;            ((EQUAL (CAR (CAR Y)) Y) 128) ; 128 = *ts-t*
;            ((CAR Y) 1536)
;            (Y 1536)))
;  99> (REWRITE (EQUAL (CAR LHS) (CAR RHS))
;               ((LHS . Y) (RHS CAR Y))
;               (((CAR (CAR Y)) 1536)
;                ((EQUAL (CAR (CAR Y)) Y) 128)
;                ((CAR Y) 1536)
;                (Y 1536)))
;  .... (CAR LHS) rewrites to (CAR Y) and (CAR RHS) rewrites to Y ....
;  .... Then: ....
;  100> (R-E (CAR Y)
;            Y
;            (((CAR (CAR Y)) 1536)
;             ((EQUAL (CAR (CAR Y)) Y) 128)
;             ((CAR Y) 1536)
;             (Y 1536)))

; The calls of rewrite-equal keep toggling between argument list (Y (CAR Y))
; and ((CAR Y) Y), because when we take the CAR, Y becomes (CAR Y), but (CAR Y)
; becomes (CAR (CAR Y)) which simplifies to Y.  Our loop-breaking mechanism
; clearly avoids this problem.  (An elim is still needed to finish the proof,
; but that's fine.)

               (let ((alist (list (cons 'lhs lhs)
                                  (cons 'rhs rhs))))
                 (sl-let
                  (equal-cars new-ttree)
                  (sl-let
                   (cars ttree0)
                   (rewrite-entry (rewrite-args '((car lhs) (car rhs))
                                                alist 1 nil nil nil nil 'equal)
                                  :obj '?
                                  :geneqv nil
                                  :pequiv-info nil ; ignored
                                  :ttree ttree+)
                   (rewrite-entry (rewrite-equal
                                   (car cars)
                                   (cadr cars)

; We considered an alternative to adding the lhs-ancestors and rhs-ancestors
; arguments, namely adding a flag saying whether we could move into this branch
; at all (in place of the member-equal tests above).  With that alternative we
; considered calling rewrite-equal here with that flag set to nil.  However,
; the following example failed when we attempted to make such a restriction on
; making recursive calls.

; (progn (defstub fn (x) t)
;        (defthm test
;          (implies (and (consp (fn x))
;                        (consp (car (fn x)))
;                        (null (cdar (fn x))))
;                   (equal (cons (cons (caar (fn x))
;                                      nil)
;                                (cdr (fn x)))
;                          (fn x)))))

                                   (cons lhs lhs-ancestors)
                                   (cons rhs rhs-ancestors))
                                  :obj nil ; ignored
                                  :geneqv nil ; ignored
                                  :pequiv-info nil ; ignored
                                  :ttree ttree0))

; Note that we pass ttree+ (which includes ttree) into the rewrite of
; the car equality and getting back new-ttree.  We will pass new-ttree
; into the rewrite of the cdr equality and get back new-ttree.  If we
; succeed, we'll return new-ttree, which includes ttree, ttree+, and
; the rewriting; otherwise, we'll stick with the original ttree.

                  (cond
                   ((equal equal-cars *t*)
                    (sl-let
                     (equal-cdrs new-ttree)
                     (sl-let
                      (cdrs ttree0)
                      (rewrite-entry (rewrite-args '((cdr lhs) (cdr rhs))
                                                   alist 1 nil nil nil nil
                                                   'equal)
                                     :obj '?
                                     :geneqv nil
                                     :pequiv-info nil ; ignored
                                     :ttree new-ttree)
                      (rewrite-entry (rewrite-equal
                                      (car cdrs)
                                      (cadr cdrs)
                                      (cons lhs lhs-ancestors)
                                      (cons rhs rhs-ancestors))
                                     :obj nil ; ignored
                                     :geneqv nil ; ignored
                                     :pequiv-info nil ; ignored
                                     :ttree ttree0))
                     (cond ((equal equal-cdrs *t*)
                            (mv step-limit *t* (puffert new-ttree)))
                           ((equal equal-cdrs *nil*)
                            (mv step-limit *nil* (puffert new-ttree)))
                           (t (mv step-limit
                                  (mcons-term* 'equal lhs rhs)
                                  (accumulate-rw-cache t new-ttree ttree))))))
                   ((equal equal-cars *nil*)
                    (mv step-limit *nil* (puffert new-ttree)))
                   (t
                    (let ((ttree (accumulate-rw-cache t new-ttree ttree)))

; If we fail to get a definitive answer then we still might be able to
; answer negatively by rewriting the cdrs.  We have been asymmetric
; for a long time without knowing it; at this point we used to simply
; return (mcons-term* 'equal lhs rhs).  In fact, the following theorem
; didn't prove --

; (implies (equal (cons a b) (cons x y))
;          (equal b y))

; even though the analogous one for the cars did prove:

; (implies (equal (cons a b) (cons x y))
;          (equal a x))

; If the cdrs aren't known to be different, then we do simply return
; the obvious equality.  That is what we would have done had lhs or
; rhs not been of type *ts-cons* -- see the (t (mv (mcons-term* ...)
; ttree)) clause at the very end of this function.  The explicit
; returning of the equality forces us to consider the (and (ts-subsetp
; ts-lhs *ts-cons*) (ts-subsetp ts-rhs *ts-cons*)) case as the second
; to last case in the main cond.  We could have coded the and above
; differently so that if both were conses and the rewrites decide it
; then we return appropriately and otherwise we fall through to
; whatever other rewrites we consider.  But we didn't.

                      (sl-let (equal-cdrs new-ttree)
                              (sl-let
                               (cdrs ttree0)
                               (rewrite-entry
                                (rewrite-args '((cdr lhs) (cdr rhs))
                                              alist 1 nil nil nil nil 'equal)
                                :obj '?
                                :geneqv nil
                                :pequiv-info nil ; ignored
                                :ttree ttree)
                               (rewrite-entry
                                (rewrite-equal
                                 (car cdrs)
                                 (cadr cdrs)
                                 (cons lhs lhs-ancestors)
                                 (cons rhs rhs-ancestors))
                                :obj nil ; ignored
                                :geneqv nil ; ignored
                                :pequiv-info nil ; ignored
                                :ttree ttree0))
                              (cond ((equal equal-cdrs *nil*)
                                     (mv step-limit *nil* (puffert new-ttree)))
                                    (t
                                     (mv step-limit
                                         (mcons-term* 'equal lhs rhs)
                                         (accumulate-rw-cache t
                                                              new-ttree
                                                              ttree)))))))))))
              (t (mv step-limit
                     (mcons-term* 'equal lhs rhs)
                     ttree))))))))))))))

(defun relieve-hyp
  (rune target hyp0 unify-subst bkptr memo ; &extra formals
        rdepth step-limit
        type-alist obj geneqv pequiv-info wrld state fnstack ancestors
        backchain-limit
        simplify-clause-pot-lst rcnst gstack ttree)

; We are trying to rewrite hyp0 to true, where hyp0 is the hypothesis of rune
; at (one-based) position bkptr, and target is an instantiated term to which
; rune is being applied.

; We return six results.  Most often they are interpreted as indicated by the
; names:

; (mv step-limit wonp failure-reason unify-subst' ttree' memo').

; Here wonp is t, nil, :unify-subst-list, or a term.  If it is t, nil, or
; :unify-subst-list, then interpretation of the results is as hinted above:
; wonp indicates whether hyp0 was relieved, failure-reason is nil or else a
; token indicating why we failed, and the rest are extended versions of the
; corresponding inputs except for the case :unify-subst-list, where
; unify-subst' is actually a list of unifying substitutions, each of which is
; sufficient for relieving the remaining hypotheses.

; But there is a special case where they are interpreted quite differently: if
; wonp is a term then it means that hyp0 contains free-vars, it was not
; relieved, and the six results are to be interpreted as follows,
; where the last three are unchanged.

; (mv step-limit term typ unify-subst ttree memo)

; This signals that the caller of relieve-hyp is responsible for relieving the
; hypothesis and may do so in either of two ways: Extend unify-subst to make
; term have typ in the original type-alist or extend unify-subst to make hyp0
; true via ground units.  This is called the SPECIAL CASE.

; This function is a No-Change Loser modulo rw-cache: only the values of
; 'rw-cache-any-tag and 'rw-cache-nil-tag may differ between the input and
; output ttrees.

; Below we describe the memo argument, but first, here is an example that
; illustrates how it is used.

; (defstub p1 (x) t)
; (defstub p2 (x) t)
; (defstub p3 (x) t)
; (defaxiom ax (implies (and (p1 x) (p2 y) (consp x) (symbolp y)) (p3 x)))
; (thm (implies (and (p1 a) (p2 b) (p2 c) (consp a) (symbolp b)) (p3 a)))

; In the proof of thm, a rewrite of (p3 a) triggers application of ax.  Note
; that (p2 c) is in front of (p2 b) on the type-alist.  So, the second
; hypothesis of ax first binds y to c.  Since (symbolp y) fails with this
; binding, we backtrack in the relieving of hyps for ax, and now bind y to b.
; But note that we encounter (consp x) again.  Rather than have to rewrite
; (consp x) again, we save the fact that it was relieved when that happened the
; first time, when y was bound to c.  How do we do this?

; Memo (called "allp" in other functions in this nest) can be an alist with
; entries of the form (n vars (subst0 . ttree0) ... (substk . ttreek)), where n
; is a bkptr, vars is (all-vars hyp0), and ttreei is the result of successfully
; calling relieve-hyp with the following arguments: ttree=nil; bkptr=n;
; unify-subst is some substitution whose restriction to vars is substi; and the
; other arguments are the same.  In these cases substi should bind all the free
; variables of hyp0.  The other legal values of memo are nil, t and :start.  If
; memo is nil or t then we do not memoize, though in the case of t we may start
; memoizing in later calls because we have a free variable.  If memo is :start
; or an alist then we return an extended memo (where :start is viewed as the
; empty memo) if this call of relieve-hyp succeeds and all variables of hyp0
; are bound in unify-subst.

; Note that unlike some other functions in the rewrite clique, here we really
; do care that bkptr is a number representing the hypothesis.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   6
   #.*fixnum-type*
   (cond ((ffn-symb-p hyp0 'synp)
          (mv-let (wonp failure-reason unify-subst ttree)
                  (relieve-hyp-synp rune hyp0 unify-subst rdepth type-alist wrld
                                    state fnstack ancestors backchain-limit
                                    simplify-clause-pot-lst rcnst gstack ttree
                                    bkptr)
                  (mv step-limit wonp failure-reason unify-subst ttree memo)))
         (t (mv-let
             (forcep1 bind-flg)
             (binding-hyp-p hyp0 unify-subst wrld)
             (let ((hyp (if forcep1 (fargn hyp0 1) hyp0)))
               (cond
                (bind-flg
                 (sl-let
                  (rewritten-rhs ttree)
                  (rewrite-entry
                   (rewrite (fargn hyp 2)
                            unify-subst
                            (if (or (f-get-global 'gstackp state)
                                    (f-get-global 'dmrp state))
                                (cons 'rhs bkptr)
                              nil))
                   :obj '?
                   :ancestors
                   (cons (make-ancestor-binding-hyp hyp unify-subst)
                         ancestors)
                   :geneqv (and (not (eq (ffn-symb hyp) 'equal))
                                (cadr (geneqv-lst
                                       (ffn-symb hyp)
                                       *geneqv-iff*
                                       (access rewrite-constant rcnst
                                               :current-enabled-structure)
                                       wrld)))
                   :pequiv-info nil)
                  (mv step-limit
                      t
                      nil
                      (cons (cons (fargn hyp 1) rewritten-rhs)
                            unify-subst)
                      ttree
                      memo)))
                ((free-varsp hyp unify-subst)

; See comment above about "SPECIAL CASE".

                 (mv-let (term typ compound-rec-rune?)
                   (term-and-typ-to-lookup
                    hyp wrld (access rewrite-constant
                                     rcnst
                                     :current-enabled-structure))
                   (mv step-limit term typ unify-subst
                       (push-lemma? compound-rec-rune? ttree)
                       memo)))
                (t
                 (let* ((memo-active (memo-activep memo))
                        (memo-entry (and (consp memo)
                                         (cdr (assoc bkptr memo))))
                        (hyp-vars (if memo-entry
                                      (car memo-entry)
                                    (and memo-active ; optimization
                                         (all-vars hyp0))))
                        (restricted-unify-subst
                         (and memo-active ; optimization
                              (restrict-alist hyp-vars unify-subst)))
                        (old-entry (and memo-entry
                                        (assoc-equal restricted-unify-subst
                                                     (cdr memo-entry)))))
                   (cond
                    (old-entry
                     (mv step-limit t nil unify-subst
                         (cons-tag-trees-rw-cache (cdr old-entry) ttree)
                         memo))
                    (t
                     (sl-let
                      (relieve-hyp-ans failure-reason unify-subst ttree0)
                      (let ((ttree (if memo-active

; If memo-active is true, we may be storing a ttree from the work done below,
; and we do not want to accumulate the existing ttree into that one.  Later
; below, if memo-active is true, then we will cons ttree0 (bound above) with
; ttree.

                                       (rw-cache ttree)
                                     ttree)))
                        (mv-let
                         (lookup-hyp-ans unify-subst ttree)
                         (lookup-hyp hyp type-alist wrld unify-subst ttree
                                     (access rewrite-constant
                                             rcnst
                                             :current-enabled-structure))

; We know that unify-subst is not extended, since (free-varsp hyp unify-subst)
; is false, but it still seems appropriate to use the existing code in
; one-way-unify1 under search-type-alist (under lookup-hyp).

                         (cond
                          (lookup-hyp-ans
                           (mv step-limit t nil unify-subst ttree))
                          (t
                           (let* ((inst-hyp (sublis-var unify-subst hyp))
                                  (forcer-fn (and forcep1 (ffn-symb hyp0)))
                                  (force-flg (ok-to-force rcnst))
                                  (forcep (and forcep1 force-flg)))
                             (mv-let
                              (knownp nilp nilp-ttree)
                              (known-whether-nil
                               inst-hyp type-alist
                               (access rewrite-constant rcnst
                                       :current-enabled-structure)
                               force-flg
                               nil ; dwp
                               wrld
                               ttree)
                              (cond
                               (knownp
                                (cond
                                 (nilp
                                  (mv step-limit
                                      nil
                                      'known-nil
                                      unify-subst
                                      ttree))
                                 (t
                                  (mv step-limit
                                      t
                                      nil
                                      unify-subst
                                      nilp-ttree))))
                               (t
                                (mv-let
                                 (on-ancestorsp assumed-true)
                                 (ancestors-check inst-hyp ancestors (list rune))
                                 (cond
                                  ((and on-ancestorsp assumed-true)
                                   (mv step-limit t nil unify-subst ttree))
                                  ((or on-ancestorsp ; and (not assumed-true)
                                       (backchain-limit-reachedp
                                        backchain-limit
                                        ancestors))
                                   (mv-let
                                    (force-flg ttree)
                                    (cond
                                     ((not forcep)
                                      (mv nil ttree))
                                     (t
                                      (force-assumption
                                       rune target inst-hyp
                                       type-alist nil
                                       (immediate-forcep
                                        forcer-fn
                                        (access rewrite-constant rcnst
                                                :current-enabled-structure))
                                       force-flg
                                       ttree)))
                                    (cond
                                     (force-flg
                                      (mv step-limit t nil unify-subst ttree))
                                     (t
                                      (mv step-limit
                                          nil
                                          (if on-ancestorsp
                                              'ancestors
                                            (cons 'backchain-limit ancestors))
                                          unify-subst ttree)))))
                                  (t
                                   (mv-let
                                    (not-flg atm)
                                    (strip-not hyp)
                                    (sl-let
                                     (rewritten-atm new-ttree)
                                     (rewrite-entry (rewrite atm
                                                             unify-subst
                                                             bkptr)
                                                    :obj (if not-flg nil t)
                                                    :geneqv *geneqv-iff*
                                                    :pequiv-info nil
                                                    :ancestors
                                                    (push-ancestor
                                                     (dumb-negate-lit
                                                      inst-hyp)
                                                     (list rune)
                                                     ancestors
                                                     bkptr))
                                     (cond
                                      (not-flg
                                       (if (equal rewritten-atm *nil*)
                                           (mv step-limit t nil unify-subst
                                               new-ttree)
                                         (mv-let
                                          (force-flg new-ttree)
                                          (if (and forcep

; Since we rewrote under *geneqv-iff*, the only way that rewritten-atm
; is known not to be nil is if it's t.

                                                   (not (equal rewritten-atm
                                                               *t*)))
                                              (force-assumption
                                               rune
                                               target
                                               (mcons-term* 'not rewritten-atm)
                                               type-alist
; Note:  :rewrittenp = instantiated unrewritten term.
                                               (mcons-term*
                                                'not
                                                (sublis-var unify-subst atm))
                                               (immediate-forcep
                                                forcer-fn
                                                (access
                                                 rewrite-constant
                                                 rcnst
                                                 :current-enabled-structure))
                                               force-flg
                                               new-ttree)
                                            (mv nil new-ttree))
                                          (cond
                                           (force-flg
                                            (mv step-limit t nil unify-subst
                                                new-ttree))
                                           (t
                                            (mv step-limit
                                                nil
                                                (cons 'rewrote-to
                                                      (dumb-negate-lit
                                                       rewritten-atm))
                                                unify-subst
                                                (accumulate-rw-cache
                                                 t new-ttree ttree)))))))
                                      ((if-tautologyp rewritten-atm)
                                       (mv step-limit t nil unify-subst
                                           new-ttree))
                                      (t (mv-let
                                          (force-flg new-ttree)
                                          (cond
                                           ((and forcep
                                                 (not (equal rewritten-atm
                                                             *nil*)))
                                            (force-assumption
                                             rune
                                             target
                                             rewritten-atm
                                             type-alist
; Note:  :rewrittenp = instantiated unrewritten term.
                                             (sublis-var unify-subst atm)
                                             (immediate-forcep
                                              forcer-fn
                                              (access
                                               rewrite-constant
                                               rcnst
                                               :current-enabled-structure))
                                             force-flg
                                             new-ttree))
                                           (t (mv nil new-ttree)))
                                          (cond
                                           (force-flg
                                            (mv step-limit t nil unify-subst
                                                new-ttree))
                                           (t (mv step-limit
                                                  nil
                                                  (cons 'rewrote-to
                                                        rewritten-atm)
                                                  unify-subst
                                                  (accumulate-rw-cache
                                                   t
                                                   new-ttree
                                                   ttree))))))))))))))))))))
                      (cond
                       (relieve-hyp-ans
                        (mv step-limit relieve-hyp-ans failure-reason
                            unify-subst
                            (if memo-active
                                (cons-tag-trees-rw-cache-first ttree ttree0)
                              ttree0)
                            (cond
                             (memo-entry
                              (put-assoc-eql
                               bkptr
                               (list* hyp-vars
                                      (cons (cons restricted-unify-subst ttree0)
                                            (cdr memo-entry)))
                               memo))
                             (memo-active
                              (put-assoc-eql
                               bkptr
                               (list* hyp-vars
                                      (cons (cons restricted-unify-subst ttree0)
                                            nil))
                               (if (eq memo :start) nil memo)))
                             (t memo))))
                       (t (mv step-limit relieve-hyp-ans failure-reason
                              unify-subst
                              (accumulate-rw-cache t ttree0 ttree)
                              memo)))))))))))))))

(defun relieve-hyps1-unify-subst-lst (unify-subst-lst
                                      rune target hyps backchain-limit-lst
                                      unify-subst bkptr
                                      unify-subst0
                                      ttree0 allp
                                      rw-cache-alist
                                      rw-cache-alist-new ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info
                                      wrld state
                                      fnstack ancestors backchain-limit
                                      simplify-clause-pot-lst rcnst gstack
                                      ttree)

; WARNING: Keep this in sync with relieve-hyps1-free-1.

; This function calls relieve-hyps1 on each alist in unify-subst-list (which is
; non-empty) until the hypotheses are relieved, extending the given unify-subst
; by that alist for each such call.  Note that if this function fails, then the
; failure-reason will be reported based on the last one tried.  That seems the
; simplest approach both for this implementation and for reporting to the
; user.  If there are user complaints about that, we can consider a more
; elaborate form of failure reporting.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   7
   #.*fixnum-type*

; In relieve-hyps1-free-1 we extend unify-subst to new-unify-subst by searching
; a type-alist.  Here we perform that extension by taking the first element of
; unify-subst-list.

   (let ((new-unify-subst
          (extend-unify-subst (car unify-subst-lst) unify-subst)))
     (mv-let
       (cached-failure-reason-free cached-failure-reason)
       (rw-cached-failure-pair new-unify-subst rw-cache-alist)
       (sl-let
        (relieve-hyps-ans failure-reason unify-subst1 ttree1 allp
                          inferior-rw-cache-alist-new)
        (cond
         (cached-failure-reason
          (mv step-limit nil
              (and (f-get-global 'gstackp state) ; cons optimization
                   (cons 'cached cached-failure-reason))
              unify-subst ttree allp nil))
         (t
          (rewrite-entry
           (relieve-hyps1 rune target (cdr hyps)
                          (cdr backchain-limit-lst)
                          new-unify-subst
                          (1+ bkptr) unify-subst0 ttree0 allp
                          (cdr cached-failure-reason-free)
                          nil)
           :obj nil :geneqv nil :pequiv-info nil ; all ignored
           )))
        (let ((rw-cache-alist-new
               (extend-rw-cache-alist-free rcnst
                                           new-unify-subst
                                           inferior-rw-cache-alist-new
                                           rw-cache-alist-new)))

          (cond
           (relieve-hyps-ans
            (mv step-limit relieve-hyps-ans nil unify-subst1 ttree1 allp
                rw-cache-alist-new))
           (t
            (let ((rw-cache-alist-new ; add normal-failure reason
                   (rw-cache-add-failure-reason rcnst
                                                new-unify-subst
                                                failure-reason
                                                rw-cache-alist-new)))
              (cond
               ((endp (cdr unify-subst-lst))
                (mv step-limit nil
                    (and (f-get-global 'gstackp state) ; cons optimization
                         (list (cons new-unify-subst
                                     failure-reason)))
                    unify-subst0
                    (accumulate-rw-cache t ttree1 ttree0)
                    nil ; allp
                    rw-cache-alist-new))
               (t ; try the next unify-subst in unify-subst-lst
                (rewrite-entry-extending-failure
                 new-unify-subst
                 failure-reason
                 (relieve-hyps1-unify-subst-lst
                  (cdr unify-subst-lst)
                  rune target hyps backchain-limit-lst
                  unify-subst bkptr
                  unify-subst0 ttree0 allp
                  rw-cache-alist rw-cache-alist-new)
                 :obj nil :geneqv nil :pequiv-info nil ; all ignored
                 :ttree (accumulate-rw-cache t ttree1 ttree0)))))))))))))

(defun relieve-hyps1 (rune target hyps backchain-limit-lst
                           unify-subst bkptr unify-subst0
                           ttree0 allp
                           rw-cache-alist rw-cache-alist-new ; &extra formals
                           rdepth step-limit
                           type-alist obj geneqv pequiv-info wrld state fnstack
                           ancestors backchain-limit
                           simplify-clause-pot-lst rcnst gstack
                           ttree)

; In order to make relieve-hyps a No-Change Loser (modulo rw-cache) without
; making it have to test the answer to its own recursive calls, we have to pass
; down the original unify-subst and ttree so that when it fails it can return
; them instead of the accumulated ones it otherwise would have.

; Parameter allp is nil iff rune has behavior :match-free :once (as opposed to
; :match-free :all).  Its legal non-nil values are explained in a comment in
; relieve-hyp (where it is called memo).  NOTE: if allp is not nil or t then
; allp does not change if we fail, but if allp is :start or an alist then its
; returned value can change even if relieve-hyps1 fails, in order for it to
; serve its memoization purpose.

; We accumulate updates to make to rw-cache-alist into parameter
; rw-cache-alist-new, which is ultimately returned.  Note that
; relieve-hyps1-free-1 and relieve-hyps1-free-2 take responsibility for
; extending rw-cache-alist-new.  Note that rw-cache-alist-new contains only new
; entries, rather than extending rw-cache-alist.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   7
   #.*fixnum-type*
   (cond
    ((null hyps)
     (mv step-limit t nil unify-subst ttree allp rw-cache-alist-new))
    (t
     (sl-let
      (relieve-hyp-ans failure-reason new-unify-subst new-ttree allp)
      (with-accumulated-persistence
       rune
       ((the #.*fixnum-type* step-limit)
        relieve-hyp-ans failure-reason new-unify-subst new-ttree allp)

; Even in the "special case" for relieve-hyp, we can mark this as a success
; because it will ultimately be counted as a failure if the surrounding call of
; relieve-hyps fails.

       relieve-hyp-ans
       (rewrite-entry (relieve-hyp rune target (car hyps)
                                   unify-subst bkptr allp)
                      :backchain-limit
                      (new-backchain-limit (car backchain-limit-lst)
                                           backchain-limit
                                           ancestors)
                      :obj nil :geneqv nil :pequiv-info nil ; all ignored
                      )
       bkptr)
      (cond
       ((eq relieve-hyp-ans t)
        (rewrite-entry (relieve-hyps1 rune target (cdr hyps)
                                      (cdr backchain-limit-lst)
                                      new-unify-subst
                                      (1+ bkptr)
                                      unify-subst0 ttree0
                                      allp
                                      rw-cache-alist rw-cache-alist-new)
                       :obj nil :geneqv nil :pequiv-info nil ; all ignored
                       :ttree new-ttree))
       ((eq relieve-hyp-ans :unify-subst-list)

; The hypothesis (car hyps) is a call of bind-free that has produced a list of
; unify-substs.

        (sl-let (relieve-hyps-ans failure-reason-lst unify-subst
                                  ttree allp rw-cache-alist-new)
                (rewrite-entry (relieve-hyps1-unify-subst-lst
                                new-unify-subst ; a list of alists
                                rune target hyps
                                backchain-limit-lst
                                unify-subst bkptr
                                unify-subst0
                                ttree0
                                (activate-memo allp)
                                rw-cache-alist
                                rw-cache-alist-new)
                               :obj nil :geneqv nil :pequiv-info nil ; all ignored
                               )
                (mv step-limit relieve-hyps-ans
                    (and (null relieve-hyps-ans)
                         (cond ((null (f-get-global 'gstackp state))
                                nil) ; save some conses
                               (t    ; hence (consp failure-reason-lst)
                                (list* bkptr
                                       'free-vars

; Note that we use 'free-vars here for bind-free; the function
; tilde-@-failure-reason-phrase1 distinguishes between bind-free hypotheses and
; hypotheses that have free variables.

; Note that we reverse below even though we do not reverse in the analogous
; function, relieve-hyps1-free-1.  That is because in relieve-hyps1-free-1, the
; failure-reason-lst is built by traversing a type-alist whose entries are
; in reverse order from the order of hypotheses encountered that created those
; entries; but here, the unify-subst-lst is processed in order.

                                       (reverse failure-reason-lst)))))
                    unify-subst ttree allp rw-cache-alist-new)))
       (relieve-hyp-ans

; As explained in the "SPECIAL CASE" comment in relieve-hyp, relieve-hyp
; returned (mv step-limit term typ unify-subst ttree allp).  We enter a loop in
; which we try to relieve the current hypothesis and subsequent hypotheses by
; instantiating the variables in term that are free with respect to
; unify-subst.

        (let* ((hyp (car hyps))
               (forcep1 (and (nvariablep hyp)
;                            (not (fquotep hyp))
                             (or (eq (ffn-symb hyp) 'force)
                                 (eq (ffn-symb hyp) 'case-split))))
               (forcer-fn (and forcep1 (ffn-symb hyp)))
               (hyp (if forcep1 (fargn hyp 1) (car hyps)))
               (force-flg (ok-to-force rcnst))
               (forcep (and forcep1 force-flg)))

; The following call of relieve-hyps1-free-1 will return an "activated" allp
; structure even if the current allp is t.  But if the current allp is t, then
; we are just now seeing our first free variable as we work our way through the
; hyps.  Since there is no search above us, there will be no further calls of
; relieve-hyps1 under the call of relieve-hyps that we are inside.  So, the
; returned value for allp is irrelevant if the current allp is t.

          (sl-let (relieve-hyps-ans failure-reason-lst unify-subst
                                    ttree allp rw-cache-alist-new)
                  (rewrite-entry
                   (relieve-hyps1-free-1 relieve-hyp-ans ; term
                                         failure-reason  ; typ
                                         hyp
                                         type-alist
                                         forcer-fn
                                         forcep
                                         force-flg
                                         rune target hyps
                                         backchain-limit-lst
                                         unify-subst bkptr
                                         unify-subst0
                                         ttree0
                                         (activate-memo allp)
                                         rw-cache-alist
                                         rw-cache-alist-new)
                   :obj nil :geneqv nil :pequiv-info nil ; all ignored
                   )
                  (mv step-limit relieve-hyps-ans
                      (and (null relieve-hyps-ans)
                           (cond ((null (f-get-global 'gstackp state))
                                  nil) ; save some conses
                                 (failure-reason-lst
                                  (list* bkptr
                                         'free-vars
                                         failure-reason-lst))
                                 (t ; There were no variable bindings.
                                  (list* bkptr 'free-vars 'hyp-vars
                                         (reverse
                                          (set-difference-assoc-eq
                                           (all-vars hyp)
                                           unify-subst))))))
                      unify-subst ttree allp rw-cache-alist-new))))
       (t (mv step-limit nil (cons bkptr failure-reason) unify-subst0
              (accumulate-rw-cache t new-ttree ttree0)
              allp rw-cache-alist-new))))))))

(defun relieve-hyps1-free-1
  (term typ hyp rest-type-alist forcer-fn forcep force-flg
        rune target hyps backchain-limit-lst
        unify-subst bkptr unify-subst0
        ttree0 allp rw-cache-alist rw-cache-alist-new ; &extra formals
        rdepth step-limit
        type-alist obj geneqv pequiv-info wrld state fnstack ancestors
        backchain-limit
        simplify-clause-pot-lst rcnst gstack
        ttree)

; WARNING: Keep this in sync with relieve-hyps1-unify-subst-lst.

; We search the type-alist in order to extend unify-subst so that a
; corresponding instance of term has type typ.  Then (with a call to
; relieve-hyps1-free-2) we search ground units in an attempt to extend
; unify-subst to make term true.

; We return seven values: a new step-limit, a relieve-hyps-ans, a
; failure-reason-lst that is a list of pairs (cons extended-unify-subst_i
; failure-reason_i), a unify-subst extending the given unify-subst, a ttree, a
; resulting allp, and an alist extending rw-cache-alist-new that will
; ultimately (in relieve-hyps) be merged into rw-cache-alist (and a
; corresponding alist for the "nil" cache).  Each failure-reason_i corresponds
; to the attempt to relieve hyps using extended-unify-subst_i, an extension of
; unify-subst.  The failure-reason-lst is used in
; tilde-@-failure-reason-free-phrase to explain why each attempt at extending
; the unify-subst failed to succeed, except if this list is empty, then a
; 'hyp-vars token is used in its place (see relieve-hyps1).

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   7
   #.*fixnum-type*
   (mv-let
    (ans new-unify-subst new-ttree new-rest-type-alist)
    (search-type-alist+ term typ rest-type-alist unify-subst ttree wrld)
    (cond
     (ans
      (mv-let
       (cached-failure-reason-free cached-failure-reason)
       (rw-cached-failure-pair new-unify-subst rw-cache-alist)
       (sl-let
        (relieve-hyps-ans failure-reason unify-subst1 ttree1 allp
                          inferior-rw-cache-alist-new)
        (cond
         (cached-failure-reason
          (mv step-limit nil
              (and (f-get-global 'gstackp state) ; cons optimization
                   (cons 'cached cached-failure-reason))
              unify-subst ttree allp nil))
         (t
          (rewrite-entry (relieve-hyps1 rune target (cdr hyps)
                                        (cdr backchain-limit-lst)
                                        new-unify-subst
                                        (1+ bkptr)
                                        unify-subst0 ttree0 allp
                                        (cdr cached-failure-reason-free)
                                        nil)
                         :obj nil :geneqv nil :pequiv-info nil ; all ignored
                         :ttree new-ttree)))
        (let ((rw-cache-alist-new
               (extend-rw-cache-alist-free rcnst
                                           new-unify-subst
                                           inferior-rw-cache-alist-new
                                           rw-cache-alist-new)))
          (cond
           (relieve-hyps-ans
            (mv step-limit relieve-hyps-ans nil unify-subst1 ttree1 allp
                rw-cache-alist-new))
           (t
            (let ((rw-cache-alist-new ; add normal-failure reason
                   (rw-cache-add-failure-reason rcnst
                                                new-unify-subst
                                                failure-reason
                                                rw-cache-alist-new)))
              (cond
               ((not allp) ; hence original allp is nil
                (mv step-limit nil
                    (and (f-get-global 'gstackp state) ; cons optimization
                         (list (cons new-unify-subst
                                     failure-reason)))
                    unify-subst0
                    (accumulate-rw-cache t ttree1 ttree0)
                    nil ; allp
                    rw-cache-alist-new))
               (t ; look for the next binding in the type-alist
                (rewrite-entry-extending-failure
                 new-unify-subst
                 failure-reason
                 (relieve-hyps1-free-1 term typ hyp new-rest-type-alist
                                       forcer-fn forcep force-flg
                                       rune target hyps
                                       backchain-limit-lst
                                       unify-subst
                                       bkptr
                                       unify-subst0 ttree0 allp
                                       rw-cache-alist rw-cache-alist-new)
                 :obj nil :geneqv nil :pequiv-info nil ; all ignored
                 :ttree (accumulate-rw-cache t ttree1 ttree)))))))))))
     (t ; failed to relieve hyp using rest-type-alist
      (rewrite-entry
       (relieve-hyps1-free-2 hyp
                             (relevant-ground-lemmas hyp wrld)
                             forcer-fn forcep
                             (access rewrite-constant rcnst
                                     :current-enabled-structure)
                             force-flg
                             rune target hyps
                             backchain-limit-lst
                             unify-subst
                             bkptr
                             unify-subst0 ttree0 allp
                             rw-cache-alist rw-cache-alist-new)
       :obj nil :geneqv nil :pequiv-info nil ; all ignored
       ))))))

(defun relieve-hyps1-free-2
    (hyp lemmas forcer-fn forcep ens force-flg
         rune target hyps backchain-limit-lst
         unify-subst bkptr unify-subst0
         ttree0 allp rw-cache-alist rw-cache-alist-new ; &extra formals
         rdepth step-limit
         type-alist obj geneqv pequiv-info wrld state fnstack ancestors
         backchain-limit
         simplify-clause-pot-lst rcnst gstack
         ttree)

; We search ground units in an attempt to extend unify-subst to make term true,
; As with relieve-hyps1-free-1, we return a relieve-hyps-ans, a
; failure-reason-lst that is a list of pairs (cons new-unify-subst
; failure-reason), a unify-subst extending the given unify-subst, a ttree, and
; a resulting allp.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

  (the-mv
   7
   #.*fixnum-type*
   (cond
    ((endp lemmas)

; If we have to force this hyp, we make sure all its free vars are bound by
; fully-bound-unify-subst, an extension of unify-subst.

     (let ((fully-bound-unify-subst
            (if force-flg
                (bind-free-vars-to-unbound-free-vars
                 (all-vars hyp)
                 unify-subst)
              unify-subst)))
       (mv-let
         (force-flg ttree)
         (cond
          ((not forcep)
           (mv nil ttree))
          (t (force-assumption
              rune
              target
              (sublis-var fully-bound-unify-subst hyp)
              type-alist
              nil
              (immediate-forcep
               forcer-fn
               (access rewrite-constant rcnst
                       :current-enabled-structure))
              force-flg
              ttree)))
         (cond
          (force-flg
           (mv-let
             (cached-failure-reason-free cached-failure-reason)
             (rw-cached-failure-pair fully-bound-unify-subst rw-cache-alist)
             (cond
              (cached-failure-reason
               (mv step-limit nil
                   (and (f-get-global 'gstackp state) ; cons optimization
                        (list                         ; failure-reason-lst
                         (cons fully-bound-unify-subst
                               (cons 'cached cached-failure-reason))))
                   unify-subst0
                   (accumulate-rw-cache t ttree ttree0)
                   allp rw-cache-alist-new))
              (t
               (sl-let
                (relieve-hyps-ans failure-reason unify-subst1 ttree1 allp
                                  inferior-rw-cache-alist-new)
                (rewrite-entry
                 (relieve-hyps1 rune target (cdr hyps)
                                (cdr backchain-limit-lst)
                                fully-bound-unify-subst
                                (1+ bkptr)
                                unify-subst0 ttree0 allp
                                (cdr cached-failure-reason-free)
                                nil)
                 :obj nil :geneqv nil :pequiv-info nil ; all ignored
                 )
                (let ((rw-cache-alist-new
                       (extend-rw-cache-alist-free
                        rcnst
                        fully-bound-unify-subst
                        inferior-rw-cache-alist-new
                        rw-cache-alist-new)))
                  (cond (relieve-hyps-ans
                         (mv step-limit relieve-hyps-ans
                             nil ; failure-reason-lst
                             unify-subst1 ttree1 allp rw-cache-alist-new))
                        (t
                         (mv step-limit nil
                             (and (f-get-global 'gstackp state) ; cons optimization
                                  (list (cons fully-bound-unify-subst
                                              failure-reason)))
                             unify-subst0
                             (accumulate-rw-cache t ttree1 ttree0)
                             allp
                             (rw-cache-add-failure-reason
                              rcnst
                              fully-bound-unify-subst
                              failure-reason
                              rw-cache-alist-new))))))))))
          (t (mv step-limit nil
                 nil ; failure-reason-lst
                 unify-subst0
                 (accumulate-rw-cache t ttree ttree0)
                 allp rw-cache-alist-new))))))
    (t
     (mv-let
       (winp new-unify-subst new-ttree rest-lemmas)
       (search-ground-units1 hyp unify-subst lemmas type-alist ens force-flg
                             wrld ttree)
       (cond
        (winp
         (mv-let
           (cached-failure-reason-free cached-failure-reason)
           (rw-cached-failure-pair new-unify-subst rw-cache-alist)
           (sl-let
            (relieve-hyps-ans failure-reason unify-subst1 ttree1 allp
                              inferior-rw-cache-alist-new)
            (cond
             (cached-failure-reason
              (mv step-limit nil
                  (and (f-get-global 'gstackp state) ; cons optimization
                       (list                         ; failure-reason-lst
                        (cons new-unify-subst
                              (cons 'cached cached-failure-reason))))
                  unify-subst ttree allp nil))
             (t
              (rewrite-entry (relieve-hyps1 rune target (cdr hyps)
                                            (cdr backchain-limit-lst)
                                            new-unify-subst
                                            (1+ bkptr)
                                            unify-subst0 ttree0 allp
                                            (cdr cached-failure-reason-free)
                                            nil)
                             :obj nil :geneqv nil :pequiv-info nil ; all ignored
                             :ttree new-ttree)))
            (let ((rw-cache-alist-new
                   (extend-rw-cache-alist-free rcnst
                                               new-unify-subst
                                               inferior-rw-cache-alist-new
                                               rw-cache-alist-new)))
              (cond
               (relieve-hyps-ans
                (mv step-limit relieve-hyps-ans nil unify-subst1 ttree1 allp
                    rw-cache-alist-new))
               (t
                (let ((rw-cache-alist-new ; add normal-failure reason
                       (rw-cache-add-failure-reason rcnst
                                                    new-unify-subst
                                                    failure-reason
                                                    rw-cache-alist-new)))
                  (cond
                   ((not allp) ; hence original allp is nil
                    (mv step-limit nil
                        (and (f-get-global 'gstackp state) ; cons optimization
                             (list                         ; failure-reason-lst
                              (cons new-unify-subst
                                    failure-reason)))
                        unify-subst0
                        (accumulate-rw-cache t ttree1 ttree0)
                        nil rw-cache-alist-new))
                   (t
                    (rewrite-entry-extending-failure
                     new-unify-subst
                     failure-reason
                     (relieve-hyps1-free-2
                      hyp rest-lemmas forcer-fn forcep ens force-flg rune
                      target hyps backchain-limit-lst unify-subst bkptr
                      unify-subst0 ttree0 allp rw-cache-alist rw-cache-alist-new)
                     :obj nil :geneqv nil :pequiv-info nil ; all ignored
                     :ttree (accumulate-rw-cache t ttree1 ttree)))))))))))
        (t (rewrite-entry
            (relieve-hyps1-free-2
             hyp nil forcer-fn forcep ens force-flg rune
             target hyps backchain-limit-lst unify-subst bkptr
             unify-subst0 ttree0 allp rw-cache-alist rw-cache-alist-new)
            :obj nil :geneqv nil :pequiv-info nil ; all ignored
            ))))))))

(defun relieve-hyps (rune target hyps backchain-limit-lst
                          unify-subst allp ; &extra formals
                          rdepth step-limit
                          type-alist obj geneqv pequiv-info wrld state fnstack
                          ancestors backchain-limit
                          simplify-clause-pot-lst rcnst gstack ttree)

; We return t or nil indicating success, a token indicating why we failed (or
; nil if we succeeded), an extended unify-subst and a new ttree.  Allp is
; either t or nil, according to whether or not we are to attempt all free
; variable matches until we succeed.

; This function is a No-Change Loser modulo rw-cache: only the values of
; 'rw-cache-any-tag and 'rw-cache-nil-tag may differ between the input and
; output ttrees.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   5
   #.*fixnum-type*
   (cond
    ((null hyps)

; For an empty list of hypotheses, there is no reason to consider the rw-cache
; at all, so we make a trivial successful return.  We rely on this in
; rewrite-with-lemma in the comment: "If hyps is nil, then relieve-hyps returns
; immediately with nil as the unifying substitution."

     (mv step-limit t nil unify-subst ttree))
    (t
     (let* ((ttree-saved ttree)
            (rw-cache-active-p (rw-cache-active-p rcnst))
            (cached-failure-entry
             (and rw-cache-active-p
                  (relieve-hyp-failure-entry rune unify-subst hyps ttree
                                             step-limit)))
            (cached-failure-reason-raw
             (and cached-failure-entry
                  (access rw-cache-entry cached-failure-entry :failure-reason)))
            (cached-failure-reason-free-p
             (and (consp cached-failure-reason-raw)
                  (free-failure-p cached-failure-reason-raw)))
            (cached-failure-reason-free
             (and cached-failure-reason-free-p
                  (equal (access rw-cache-entry cached-failure-entry
                                 :hyp-info)
                         hyps)
                  cached-failure-reason-raw))
            (cached-failure-reason
             (and (not cached-failure-reason-free-p)
                  cached-failure-reason-raw))
            (debug
             (and cached-failure-reason
                  (rw-cache-debug rune target unify-subst
                                  cached-failure-reason step-limit))))
       (cond
        ((and cached-failure-reason
              (not debug))
         (mv step-limit nil
             (and (f-get-global 'gstackp state) ; cons optimization
                  (cons 'cached cached-failure-reason))
             unify-subst ttree))
        (t (let ((step-limit-saved step-limit)
                 (unify-subst-saved unify-subst)
                 (old-rw-cache-alist (cdr cached-failure-reason-free)))
             (sl-let (relieve-hyps-ans failure-reason unify-subst ttree allp
                                       new-rw-cache-alist)
                     (rewrite-entry
                      (relieve-hyps1 rune target hyps backchain-limit-lst
                                     unify-subst 1 unify-subst ttree allp
                                     old-rw-cache-alist nil)
                      :obj nil :geneqv nil :pequiv-info nil ; all ignored

; If we are doing non-linear arithmetic, we will be rewriting linear
; terms under a different theory than the standard one.  However, when
; relieving hypotheses, we want to use the standard one, so we make
; sure that that is what we are using.

                      :rcnst
                      (if (eq (access rewrite-constant rcnst
                                      :active-theory)
                              :standard)
                          rcnst
                        (change rewrite-constant rcnst
                                :active-theory :standard)))
                     (declare (ignore allp))
                     (cond ((and debug relieve-hyps-ans)
                            (prog2$
                             (rw-cache-debug-action
                              rune target unify-subst-saved
                              cached-failure-reason step-limit-saved)
                             (mv step-limit nil cached-failure-reason
                                 unify-subst-saved ttree-saved)))
                           (t (mv step-limit relieve-hyps-ans failure-reason
                                  unify-subst
                                  (cond
                                   ((or relieve-hyps-ans
                                        backchain-limit
                                        (not rw-cache-active-p))
                                    ttree)
                                   (new-rw-cache-alist ; free vars case
                                    (note-relieve-hyps-failure-free
                                     rune unify-subst hyps
                                     ttree
                                     cached-failure-entry
                                     old-rw-cache-alist
                                     new-rw-cache-alist

; At one time we only saved the step-limit in debug mode, so that when we merge
; rw-caches after calls of cons-tag-trees, we avoid essentially duplicated
; rw-cache-entry records, differing only in their :step-limit fields.  However,
; we now save the step-limit unconditionally, because we may be calling
; merge-lexorder-fast a lot and the :step-limit field of a rw-cache-entry
; record can give a quick result.  The potential for rare duplication seems
; harmless.

                                     step-limit-saved))
                                   (t

; We cache the rewriting failure into the ttree.  It would be a mistake to
; extend the rw-cache if there is a backchain-limit, because a later lookup
; might be made with a different backchain-limit.  This may be why
; Prime-property-lemma, in community book
; workshops/2006/cowles-gamboa-euclid/Euclid/ed3.lisp, fails with
; :rw-cache-state :atom.

                                    (note-relieve-hyp-failure
                                     rune unify-subst failure-reason
                                     ttree hyps

; See comment above about regarding our formerly saving the step-limit only in
; debug mode.

                                     step-limit-saved)))))))))))))))

(defun rewrite-with-lemma (term lemma ; &extra formals
                                rdepth step-limit
                                type-alist obj geneqv pequiv-info wrld state
                                fnstack ancestors
                                backchain-limit
                                simplify-clause-pot-lst rcnst gstack
                                ttree)

; The four values returned by this function are: a new step-limit, t or nil
; indicating whether lemma was used to rewrite term, the rewritten version of
; term, and the final version of ttree.

; This function is a No-Change Loser modulo rw-cache: only the values of
; 'rw-cache-any-tag and 'rw-cache-nil-tag may differ between the input and
; output ttrees.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   4
   #.*fixnum-type*
   (let ((gstack (push-gframe 'rewrite-with-lemma nil term lemma geneqv))
         (rdepth (adjust-rdepth rdepth)))
     (declare (type #.*fixnat-type* rdepth))
     (cond ((zero-depthp rdepth)
            (rdepth-error
             (mv step-limit nil term ttree)))
           ((eq (access rewrite-rule lemma :subclass) 'meta)

; See the Essay on Correctness of Meta Reasoning, above, and :doc meta.

            (cond
             ((geneqv-refinementp (access rewrite-rule lemma :equiv)
                                  geneqv
                                  wrld)

; We assume that the meta function has defun-mode :logic.  How could it
; be :program if we proved it correct?

; Metafunctions come in two flavors.  Vanilla metafunctions take just
; one arg, the term to be rewritten.  Extended metafunctions take
; three args.  We cons up the args here and use this list of args
; twice below, once to eval the metafunction and once to eval the hyp
; fn.  The :rhs of the rewrite-rule is the special flag 'extended
; if we are in the extended case; otherwise, :rhs is nil.  We must
; manufacture a context in the former case.

              (let* ((meta-fn (access rewrite-rule lemma :lhs))
                     (args
                      (cond
                       ((eq (access rewrite-rule lemma :rhs)
                            'extended)
                        (list term
                              (make metafunction-context
                                    :rdepth rdepth
                                    :type-alist type-alist
                                    :obj obj
                                    :geneqv geneqv
                                    :wrld wrld
                                    :fnstack fnstack
                                    :ancestors ancestors
                                    :backchain-limit backchain-limit
                                    :simplify-clause-pot-lst
                                    simplify-clause-pot-lst
                                    :rcnst rcnst
                                    :gstack gstack
                                    :ttree ttree
                                    :unify-subst nil)
                              (coerce-state-to-object state)))
                       (t (list term))))
                     (rune (access rewrite-rule lemma :rune)))
                (with-accumulated-persistence
                 rune
                 ((the #.*fixnum-type* step-limit) flg term ttree)
                 flg
                 (mv-let
                  (erp val latches)
                  (pstk
                   (ev-fncall-meta meta-fn args state))
                  (declare (ignore latches))
                  (cond
                   (erp
                    (mv step-limit nil term ttree))
                   ((equal term val)
                    (mv step-limit nil term ttree))
                   (t

; Skip logic-termp checks if either we're told to via skip-meta-termp-checks
; or they are unnecessary because of the meta fn (and its hyp-fn) have
; well-formedness guarantees.  If we skip the checks because of guarantees, we
; must check the arity assumptions.

                    (let* ((user-says-skip-termp-checkp
                            (skip-meta-termp-checks meta-fn wrld))
                           (well-formedness-guarantee
                            (access rewrite-rule lemma :heuristic-info))
                           (not-skipped
                            (and (not user-says-skip-termp-checkp)
                                 (not well-formedness-guarantee)))
                           (bad-arity-info
                            (if (and well-formedness-guarantee
                                     (not user-says-skip-termp-checkp))
                                (collect-bad-fn-arity-info
                                 (cdr well-formedness-guarantee)
                                 wrld nil nil)
                              nil)))
                      (cond
                       (bad-arity-info
                        (let ((name (nth 0 (car well-formedness-guarantee)))
                              (fn (nth 1 (car well-formedness-guarantee)))
                              (thm-name1
                               (nth 2 (car well-formedness-guarantee)))
                              (hyp-fn (nth 3 (car well-formedness-guarantee)))
                              (thm-name2
                               (nth 4 (car well-formedness-guarantee))))
                          (mv step-limit
                              (er hard 'rewrite-with-lemma
                                  "~@0"
                                  (bad-arities-msg name :META fn hyp-fn
                                                   thm-name1 thm-name2
                                                   bad-arity-info))
                              term ttree)))
; Check logic-termp by checking both termp and (not (program-termp)).
                       ((and not-skipped
                             (not (termp val wrld)))
                        (mv step-limit
                            (er hard 'rewrite-with-lemma
                                "The metafunction ~x0 produced the non-termp ~
                                 ~x1 on the input term ~x2. The proof of the ~
                                 correctness of ~x0 establishes that the ~
                                 quotations of these two s-expressions have ~
                                 the same value, but our implementation ~
                                 additionally requires that ~x0 produce a ~
                                 term.  See :DOC termp.  You might consider ~
                                 proving a well-formedness guarantee to avoid ~
                                 this runtime test altogether.  See :DOC ~
                                 well-formedness-guarantee."
                                meta-fn val term)
                            term ttree))
                       ((and not-skipped
                             (not (logic-termp val wrld)))
                        (mv step-limit
                            (er hard 'rewrite-with-lemma
                                "The metafunction ~x0 produced the termp ~x1 ~
                                 on the input term ~x2.  The proof of the ~
                                 correctness of ~x0 establishes that the ~
                                 quotations of these two s-expressions have ~
                                 the same value, but our implementation ~
                                 additionally requires that ~x0 produce a ~
                                 term with no :program mode function symbols. ~
                                 ~ The term produced has :program mode ~
                                 function symbol~#3~[~/s~] ~&3.  You might ~
                                 consider proving a well-formedness guarantee ~
                                 to avoid this runtime test altogether.  See ~
                                 :DOC well-formedness-guarantee."
                                meta-fn val term
                                (collect-programs (all-ffn-symbs val nil)
                                                  wrld))
                            term ttree))
                       ((and not-skipped
                             (forbidden-fns-in-term
                              val
                              (access rewrite-constant rcnst :forbidden-fns)))
                        (mv step-limit
                            (er hard 'rewrite-with-lemma
                                "The metafunction ~x0 produced the termp ~x1 ~
                                 on the input term ~x2.  The proof of the ~
                                 correctness of ~x0 establishes that the ~
                                 quotations of these two s-expressions have ~
                                 the same value, but our implementation ~
                                 additionally requires that certain forbidden ~
                                 function symbols not be called.  However, ~
                                 the forbidden function symbol~#3~[ ~&3 is~/s ~
                                 ~&3 are~] called in the term produced by ~
                                 ~x0.  See :DOC meta and :DOC ~
                                 set-skip-meta-termp-checks and :DOC ~
                                 well-formedness-guarantee."
                                meta-fn val term
                                (forbidden-fns-in-term
                                 val
                                 (access rewrite-constant rcnst :forbidden-fns)))
                            term ttree))
                       (t
                        (mv-let
                         (extra-evaled-hyp val)
                         (cond ((and (ffn-symb-p val 'if)
                                     (equal (fargn val 3) term))
                                (mv (fargn val 1) (fargn val 2)))
                               (t (mv *t* val)))
                         (let ((hyp-fn (access rewrite-rule lemma :hyps)))
                           (mv-let
                            (erp evaled-hyp latches)
                            (if (eq hyp-fn nil)
                                (mv nil *t* nil)
                              (pstk
                               (ev-fncall-meta hyp-fn args state)))
                            (declare (ignore latches))
                            (cond
                             (erp
                              (mv step-limit nil term ttree))
                             (t
                              (let* ((user-says-skip-termp-checkp
                                      (skip-meta-termp-checks hyp-fn wrld))
;                                    (well-formedness-guarantee  ; already bound
;                                     (access rewrite-rule lemma
;                                             :heuristic-info))
                                     (not-skipped
                                      (and (not user-says-skip-termp-checkp)
                                           (not well-formedness-guarantee)))

; It is easy to think that it is unnecessary to do this computation and binding
; because the non-nil result will be exactly the same as it was above
; (depending as it does only on the guarantee and the wrld) and we have already
; (above) checked and caused an error if it is non-nil.  But that reasoning is
; faulty.  Suppose the user told us to skip the termp check on metafn's output
; but to do the check on hyp-fn's output.  Then the earlier binding of
; bad-arity-info is nil but this binding may find something.

                                     (bad-arity-info
                                      (if (and
                                           well-formedness-guarantee
                                           (not user-says-skip-termp-checkp))
                                          (collect-bad-fn-arity-info
                                           (cdr well-formedness-guarantee)
                                           wrld nil nil)
                                        nil)))
                                (cond
                                 (bad-arity-info
                                  (let ((name
                                         (nth 0
                                              (car well-formedness-guarantee)))
                                        (hyp-fn
                                         (nth 3
                                              (car well-formedness-guarantee)))
                                        (thm-name2
                                         (nth 4
                                              (car well-formedness-guarantee))))
                                    (mv step-limit
                                        (er hard 'rewrite-with-lemma
                                            "~@0"
                                            (bad-arities-msg name
                                                             :META
                                                             nil ; fn
                                                             hyp-fn
                                                             thm-name2
                                                             nil
                                                             bad-arity-info))
                                        term ttree)))
                                 ((and not-skipped
                                       (not (termp evaled-hyp wrld)))
                                  (mv step-limit
                                      (er hard 'rewrite-with-lemma
                                          "The hypothesis metafunction ~x0 ~
                                           produced the non-termp ~x1 on the ~
                                           input term ~x2.  Our ~
                                           implementation requires that ~x0 ~
                                           produce a term.  See :DOC termp.  ~
                                           You might consider proving a ~
                                           well-formedness guarantee.  See ~
                                           :DOC well-formedness-guarantee to ~
                                           avoid this runtime check ~
                                           altogether.  See :DOC ~
                                           well-formedness-guarantee."
                                          hyp-fn evaled-hyp term)
                                      term ttree))
                                 ((and not-skipped
                                       (not (logic-termp evaled-hyp wrld)))
                                  (mv step-limit
                                      (er hard 'rewrite-with-lemma
                                          "The hypothesis metafunction ~x0 ~
                                           produced the termp ~x1 on the ~
                                           input term ~x2.  The proof of the ~
                                           correctness of ~x0 establishes ~
                                           that the quotations of these two ~
                                           s-expressions have the same value, ~
                                           but our implementation ~
                                           additionally requires that ~x0 ~
                                           produce a term with no :program ~
                                           mode function symbols.  The term ~
                                           produced has :program mode ~
                                           function symbol~#3~[~/s~] ~&3.  ~
                                           You might consider proving a ~
                                           well-formedness guarantee to avoid ~
                                           this runtime test altogether.  See ~
                                           :DOC well-formedness-guarantee."
                                          hyp-fn evaled-hyp term
                                          (collect-programs
                                           (all-ffn-symbs evaled-hyp nil)
                                           wrld))
                                      term ttree))
                                 ((and not-skipped
                                       (forbidden-fns-in-term
                                        evaled-hyp
                                        (access rewrite-constant rcnst
                                                :forbidden-fns)))
                                  (mv step-limit
                                      (er hard 'rewrite-with-lemma
                                          "The hypothesis metafunction ~x0 ~
                                           produced the termp ~x1 on the ~
                                           input term ~x2.  Our ~
                                           implementation additionally ~
                                           requires that certain forbidden ~
                                           function symbols not be called.  ~
                                           However, the forbidden function ~
                                           symbol~#3~[ ~&3 is~/s ~&3 are~] ~
                                           called in the term produced by ~
                                           ~x0.  See :DOC meta and :DOC ~
                                           set-skip-meta-termp-checks and ~
                                           :DOC well-formedness-guarantee."
                                          hyp-fn evaled-hyp term
                                          (forbidden-fns-in-term
                                           evaled-hyp
                                           (access rewrite-constant rcnst
                                                   :forbidden-fns)))
                                      term ttree))
                                 (t
                                  (let* ((hyps0 (flatten-ands-in-lit

; Note: The quote-normal-form call below normalizes the explicit constant
; constructors, e.g., (cons '1 '2) becomes '(1 . 2).  See the comment in
; extend-unify-subst.

                                                 (quote-normal-form
                                                  evaled-hyp)))
                                         (extra-hyps (flatten-ands-in-lit

; Note: The quote-normal-form call below normalizes the explicit constant
; constructors, e.g., (cons '1 '2) becomes '(1 . 2).  See the comment in
; extend-unify-subst.

                                                 (quote-normal-form
                                                  extra-evaled-hyp)))
                                         (hyps (append? hyps0 extra-hyps))
                                         (vars (and hyps

; We avoid the cost of computing (all-vars term) when there are no hypotheses
; (which is presumably a common case).  We have seen this reduce an event's
; processing time from 67 seconds to 19 seconds.

                                                    (all-vars term)))
                                         (rule-backchain-limit
                                          (access rewrite-rule lemma
                                                  :backchain-limit-lst))
                                         (bad-synp-hyp-msg
                                          (and hyps0

; Vars should be (all-vars term) if we call bad-synp-hyp-msg, but if hyps0 is
; nil then bad-synp-hyp-msg returns nil regardless of vars, so we avoid calling
; it.

                                               (bad-synp-hyp-msg hyps0 vars nil
                                                                 wrld)))
                                         (bad-synp-hyp-msg-extra
                                          (and extra-hyps ; optimize, as above
                                               (bad-synp-hyp-msg extra-hyps
                                                                 vars nil
                                                                 wrld))))
                                    (cond
                                     (bad-synp-hyp-msg
                                      (mv step-limit
                                          (er hard 'rewrite-with-lemma
                                              "The hypothesis metafunction ~
                                               ~x0, when applied to the input ~
                                               term ~x1, produced a term ~
                                               whose use of synp is illegal ~
                                               because ~@2"
                                              hyp-fn term bad-synp-hyp-msg)
                                          term ttree))
                                     (bad-synp-hyp-msg-extra
                                      (mv step-limit
                                          (er hard 'rewrite-with-lemma
                                              "The metafunction ~x0, when ~
                                               applied to the input term ~x1, ~
                                               produced a term with an ~
                                               implicit hypothesis (see :DOC ~
                                               meta-implicit-hypothesis), ~
                                               whose use of synp is illegal ~
                                               because ~@2"
                                              meta-fn term
                                              bad-synp-hyp-msg-extra)
                                          term ttree))
                                     (t
                                      (sl-let
                                       (relieve-hyps-ans failure-reason
                                                         unify-subst
                                                         ttree)
                                       (rewrite-entry
                                        (relieve-hyps

; The next argument of relieve-hyps is a rune on which to "blame" a
; possible force.  We could blame such a force on a lot of things, but
; we'll blame it on the metarule and the term that it's applied to.

                                         rune
                                         term
                                         hyps
                                         (and rule-backchain-limit
                                              (assert$
                                               (natp rule-backchain-limit)
                                               (make-list
                                                (length hyps)
                                                :initial-element
                                                rule-backchain-limit)))

; The meta function has rewritten term to val and has generated a
; hypothesis called evaled-hyp.  Now ignore the metafunction and just
; imagine that we have a rewrite rule (implies evaled-hyp (equiv term
; val)).  The unifying substitution just maps the vars of term to
; themselves.  There may be additional vars in both evaled-hyp and in
; val.  But they are free at the time we do this relieve-hyps.

; If hyps is nil, then relieve-hyps returns immediately with nil as the
; unifying substitution.  That's OK, as explained in a comment below ("At one
; point we ignored the unify-subst....").

                                         (and hyps
                                              (pairlis$ vars vars))
                                         nil ; allp=nil for meta rules
                                         )
                                        :obj nil         ; ignored
                                        :geneqv nil      ; ignored
                                        :pequiv-info nil ; ignored
                                        )

; If relieve hyps succeeds we get back a unifying substitution that extends
; the identity substitution above.  This substitution might bind free vars
; in the evaled-hyp.

; Why are we ignoring failure-reason?  Do we need to be calling one of the
; brkpt functions?  No, because we don't break on meta rules.  But perhaps we
; should consider allowing breaks on meta rules.

                                       (declare (ignore failure-reason))
                                       (cond
                                        (relieve-hyps-ans
                                         (sl-let
                                          (rewritten-rhs ttree)
                                          (with-accumulated-persistence
                                           rune
                                           ((the #.*fixnum-type* step-limit)
                                            rewritten-rhs ttree)

; This rewrite of the body is considered a success unless the parent with-acc-p
; fails.

                                           t
                                           (rewrite-entry (rewrite

; Note: The quote-normal-form call below normalizes the explicit constant
; constructors, e.g., (cons '1 '2) becomes '(1 . 2).  See the comment in
; extend-unify-subst.

                                                 (quote-normal-form val)

; At one point we ignored the unify-subst constructed above and used a nil
; here.  That was unsound if val involved free vars bound by the relief of the
; evaled-hyp.  We must rewrite val under the extended substitution.  Often that
; is just the identity substitution.  If there are no hypotheses, however, then
; there are no such free vars, so it is fine to rewrite with nil as the
; unify-subst.

                                                           unify-subst
                                                           'meta))
                                           :conc
                                           hyps)
                                          (mv step-limit t rewritten-rhs

; Should we be pushing executable-counterparts into ttrees when we applying
; metafunctions on behalf of meta rules?  NO:  We should only do that if the
; meta-rule's use is sensitive to whether or not they're enabled, and it's not
; -- all that matters is if the rule itself is enabled.

                                              (push-lemma
                                               (geneqv-refinementp
                                                (access rewrite-rule lemma
                                                        :equiv)
                                                geneqv
                                                wrld)
                                               (push-lemma+ rune ttree rcnst ancestors
                                                            val rewritten-rhs)))))
                                        (t (mv step-limit nil term ttree))))))))))))))))))))))))
             (t (mv step-limit nil term ttree))))
           ((not (geneqv-refinementp (access rewrite-rule lemma :equiv)
                                     geneqv
                                     wrld))
            (progn$
             (refinement-failure-brkpt1 lemma term type-alist geneqv
                                        ancestors ttree
                                        gstack rcnst
                                        simplify-clause-pot-lst
                                        state)
             (brkpt2 nil 'refinement-failure
                     nil ; unify-subst
                     gstack nil nil
                     rcnst ancestors state)
             (mv step-limit nil term ttree)))
           ((eq (access rewrite-rule lemma :subclass) 'definition)
            (sl-let (rewritten-term ttree)
                    (rewrite-entry (rewrite-fncall lemma term))
                    (mv step-limit
                        (not (equal term rewritten-term))
                        rewritten-term
                        ttree)))
           ((and (or (null (access rewrite-rule lemma :hyps))
                     (not (eq obj t))
                     (not (equal (access rewrite-rule lemma :rhs) *nil*)))
                 (or (flambdap (ffn-symb term)) ; hence not on fnstack
                     (not (being-openedp (ffn-symb term)
                                         fnstack
                                         (recursivep (ffn-symb term) t wrld)
                                         (eq (access rewrite-constant rcnst
                                                     :rewriter-state)
                                             'settled-down)))
                     (not (ffnnamep (ffn-symb term)
                                    (access rewrite-rule lemma :rhs)))))
            (let ((lhs (access rewrite-rule lemma :lhs))
                  (rune (access rewrite-rule lemma :rune)))
              (mv-let (unify-ans unify-subst)
                      (one-way-unify-restrictions
                       lhs
                       term
                       (cdr (assoc-equal
                             rune
                             (access rewrite-constant rcnst
                                     :restrictions-alist))))
                      (cond
                       ((and unify-ans
                             (null (brkpt1 lemma term unify-subst
                                           type-alist geneqv ancestors
                                           ttree
                                           gstack rcnst simplify-clause-pot-lst
                                           state)))
                        (cond
                         ((null (loop-stopperp
                                 (access rewrite-rule lemma :heuristic-info)
                                 unify-subst
                                 wrld))
                          (prog2$
                           (brkpt2 nil 'loop-stopper
                                   unify-subst gstack nil nil
                                   rcnst ancestors state)
                           (mv step-limit nil term ttree)))
                         (t
                          (with-accumulated-persistence
                           rune
                           ((the #.*fixnum-type* step-limit) flg term ttree)
                           flg
                           (sl-let
                            (relieve-hyps-ans failure-reason unify-subst ttree)
                            (rewrite-entry
                             (relieve-hyps
                              rune
                              term
                              (access rewrite-rule lemma :hyps)
                              (access rewrite-rule lemma
                                      :backchain-limit-lst)
                              unify-subst
                              (not (oncep (access rewrite-constant
                                                  rcnst
                                                  :oncep-override)
                                          (access rewrite-rule
                                                  lemma
                                                  :match-free)
                                          rune
                                          (access rewrite-rule
                                                  lemma
                                                  :nume))))
                             :obj nil         ; ignored
                             :geneqv nil      ; ignored
                             :pequiv-info nil ; ignored
                             )
                            (cond
                             (relieve-hyps-ans
                              (sl-let
                               (rewritten-rhs ttree)
                               (with-accumulated-persistence
                                rune
                                ((the #.*fixnum-type* step-limit)
                                 rewritten-rhs ttree)

; This rewrite of the body is considered a success unless the parent with-acc-p
; fails.

                                t
                                (rewrite-entry
                                 (rewrite
                                  (access rewrite-rule lemma :rhs)
                                  unify-subst
                                  'rhs))
                                :conc
                                (access rewrite-rule lemma :hyps))
                               (prog2$
                                (brkpt2 t nil unify-subst gstack rewritten-rhs
                                        ttree rcnst ancestors state)
                                (mv step-limit t rewritten-rhs
                                    (push-lemma
                                     (geneqv-refinementp
                                      (access rewrite-rule lemma
                                              :equiv)
                                      geneqv
                                      wrld)
                                     (push-lemma+ rune ttree rcnst ancestors
                                                  (access rewrite-rule lemma
                                                          :rhs)
                                                  rewritten-rhs))))))
                             (t (prog2$
                                 (brkpt2 nil failure-reason
                                         unify-subst gstack nil nil
                                         rcnst ancestors state)
                                 (mv step-limit nil term ttree)))))))))
                       (t (progn$
                           (near-miss-brkpt1 lemma term type-alist geneqv
                                             ancestors ttree
                                             gstack rcnst
                                             simplify-clause-pot-lst
                                             state)
                           (brkpt2 nil 'near-miss
                                   unify-subst gstack nil nil
                                   rcnst ancestors state)
                           (mv step-limit nil term ttree)))))))
           (t (mv step-limit nil term ttree))))))

(defun rewrite-with-lemmas1 (term lemmas
                                  ;;; &extra formals
                                  rdepth step-limit
                                  type-alist obj geneqv pequiv-info wrld state
                                  fnstack ancestors
                                  backchain-limit
                                  simplify-clause-pot-lst rcnst gstack ttree)

; Try to rewrite term with the lemmas in lemmas.  Return t or nil indicating
; success, the rewritten term, and the final ttree.

; This function is a No-Change Loser modulo rw-cache: only the values of
; 'rw-cache-any-tag and 'rw-cache-nil-tag may differ between the input and
; output ttrees.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   4
   #.*fixnum-type*
   (cond ((null lemmas) (mv step-limit nil term ttree))

; When we are doing non-linear we will be rewriting linear terms
; under a different theory than the standard one.  The :active-theory
; field of the rcnst keeps track of which theory we are using.

         ((if (eq (access rewrite-constant rcnst :active-theory)
                  :standard)
              (not (enabled-numep
                    (access rewrite-rule (car lemmas) :nume)
                    (access rewrite-constant rcnst
                            :current-enabled-structure)))
            (not (enabled-arith-numep
                  (access rewrite-rule (car lemmas) :nume)
                  (global-val 'global-arithmetic-enabled-structure wrld))))
          (rewrite-entry (rewrite-with-lemmas1 term (cdr lemmas))))
         (t (sl-let
             (rewrittenp rewritten-term ttree)
             (rewrite-entry (rewrite-with-lemma term (car lemmas)))
             (cond (rewrittenp
                    (mv step-limit t rewritten-term ttree))
                   (t (rewrite-entry
                       (rewrite-with-lemmas1 term (cdr lemmas))))))))))

(defun rewrite-fncall (rule term ; &extra formals
                       rdepth step-limit
                       type-alist obj geneqv pequiv-info wrld state fnstack
                       ancestors backchain-limit
                       simplify-clause-pot-lst rcnst gstack ttree)

; Rule is a :REWRITE rule of subclass DEFINITION or else it is nil.  Rule is
; nil iff term is a lambda application.  The three values returned by this
; function are the new step-limit, the (possibly) rewritten term, and the new
; ttree.  We assume rule is enabled.

; Term is of the form (fn . args).

; Nqthm Discrepancy: In Nqthm, the caller of rewrite-fncall,
; rewrite-with-lemmas, would ask whether the result was different from term and
; whether it contained rewritable calls.  If so, it called the rewriter on the
; result.  We have changed that here so that rewrite-fncall, in the case that
; it is returning the expanded body, asks about rewritable calls and possibly
; calls rewrite again.  In the implementation below we ask about rewritable
; calls only for recursively defined fns.  The old code asked the question on
; all expansions.  It is possible the old code sometimes found a rewritable
; call of a non-recursive fn in the expansion of that fn's body because of uses
; of that fn in the arguments.  So this is a possible difference between ACL2
; and Nqthm, although we have no reason to believe it is significant and we do
; it only for recursive fns simply because the non-recursive case seems
; unlikely.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (let* ((fn (ffn-symb term))
          (args (fargs term))
          (body (if (null rule)
                    (or (lambda-body fn)
                        (er hard 'rewrite-fncall
                            "We had thought that a lambda function symbol ~
                             always has a non-nil lambda-body, but the ~
                             following lambda does not: ~x0"
                            fn))
                  (or (access rewrite-rule rule :rhs)
                      "We had thought that a rewrite-rule always has a non-nil ~
                      :rhs, but the following rewrite rule does not: ~x0")))
          (recursivep (and rule ; it's a don't-care if (flambdap fn)
                           (car (access rewrite-rule rule :heuristic-info)))))
     (cond ((and (not (flambdap fn))
                 (or (being-openedp fn fnstack recursivep
                                    (eq (access rewrite-constant rcnst
                                                :rewriter-state)
                                        'settled-down))
                     (fnstack-term-member term fnstack)
                     (and recursivep
                          (member-eq :rewrite-lambda-object fnstack))))
            (prepend-step-limit
             2
             (rewrite-solidify term type-alist obj geneqv
                               (access rewrite-constant rcnst
                                       :current-enabled-structure)
                               wrld ttree
                               simplify-clause-pot-lst
                               (access rewrite-constant rcnst :pt))))
           ((null rule) ; i.e., (flambdap fn)
            (cond
             ((and (not (recursive-fn-on-fnstackp fnstack))
                   (too-many-ifs-pre-rewrite args
                                             (var-counts (lambda-formals fn)
                                                         body)))
              (prepend-step-limit
               2
               (rewrite-solidify term type-alist obj geneqv
                                 (access rewrite-constant rcnst
                                         :current-enabled-structure)
                                 wrld ttree
                                 simplify-clause-pot-lst
                                 (access rewrite-constant rcnst :pt))))
             (t
              (sl-let
               (rewritten-body ttree1)
               (rewrite-entry (rewrite body
                                       (pairlis$ (lambda-formals fn) args)
                                       'lambda-body)
                              :fnstack fnstack)

; Observe that we do not put the lambda-expression onto the fnstack.
; We act just as though we were rewriting a term under a substitution.
; But we do decide on heuristic grounds whether to keep the expansion.
; See the handling of non-recursive functions below for some comments
; relating to the too-many-ifs code.

; Note: If the handling of lambda-applications is altered, consider
; their handling in both rewrite-fncallp (where we take advantage of
; the knowledge that lambda-expressions will not occur in rewritten
; bodies unless the user has explicitly prevented us from opening
; them) and contains-rewritable-callp.

               (cond
                ((and (not (recursive-fn-on-fnstackp fnstack))
                      (too-many-ifs-post-rewrite args rewritten-body))
                 (prepend-step-limit
                  2
                  (rewrite-solidify term type-alist obj geneqv
                                    (access rewrite-constant rcnst
                                            :current-enabled-structure)
                                    wrld
                                    (accumulate-rw-cache t ttree1 ttree)
                                    simplify-clause-pot-lst
                                    (access rewrite-constant rcnst :pt))))
                (t (mv step-limit rewritten-body ttree1)))))))
           (t
            (let* ((new-fnstack (cons (or recursivep fn) fnstack))
                   (rune (access rewrite-rule rule :rune)))
              (mv-let
               (unify-ans unify-subst)
               (one-way-unify-restrictions
                (access rewrite-rule rule :lhs)
                term
                (cdr (assoc-equal
                      rune
                      (access rewrite-constant rcnst
                              :restrictions-alist))))
               (cond
                ((and unify-ans
                      (null (brkpt1 rule term unify-subst type-alist geneqv
                                    ancestors ttree gstack rcnst
                                    simplify-clause-pot-lst state)))
                 (with-accumulated-persistence
                  (access rewrite-rule rule :rune)
                  ((the #.*fixnum-type* step-limit) term-out ttree)

; The following mis-guarded use of eq instead of equal implies that we could be
; over-counting successes at the expense of failures.

                  (not (eq term term-out))
                  (cond
                   ((and (null recursivep)
                         (not (recursive-fn-on-fnstackp fnstack))
                         (too-many-ifs-pre-rewrite args
                                                   (access rewrite-rule rule
                                                           :var-info)))

; We are dealing with a nonrecursive fn.  If we are at the top-level of the
; clause but the expanded body has too many IFs in it compared to the number
; in the args, we do not use the expanded body.  We know the IFs in
; the args will be clausified out soon and then this will be permitted to
; open.

                    (prog2$

; As of this writing (shortly after the Version_8.6 release) the brr-result,
; :rewritten-rhs-avoided, supplied below, is not referenced elsewhere in our
; code or documentation.  However, it may be occasionally printed as the result
; of rewriting and is intended to be self-explanatory.

                     (brkpt2 nil 'too-many-ifs-pre-rewrite unify-subst gstack
                             :rewritten-rhs-avoided ttree rcnst ancestors
                             state)
                     (prepend-step-limit
                      2
                      (rewrite-solidify term type-alist obj geneqv
                                        (access rewrite-constant rcnst
                                                :current-enabled-structure)
                                        wrld ttree
                                        simplify-clause-pot-lst
                                        (access rewrite-constant rcnst
                                                :pt)))))
                   (t
                    (sl-let
                     (relieve-hyps-ans failure-reason unify-subst ttree1)
                     (cond
                      ((and (eq fn (base-symbol rune))

; There may be alternative definitions of fn.  "The" definition is the one
; whose rune is of the form (:DEFINITION fn); its hyps is nil, at least in the
; standard case; but:

                            #+:non-standard-analysis

; In the non-standard case, we may be attempting to open up a call of a
; function defined by defun-std.  Hence, there may be one or more hypotheses.

                            (not (access rewrite-rule rule :hyps)))
                       (mv step-limit t nil unify-subst ttree))
                      (t (rewrite-entry
                          (relieve-hyps rune term
                                        (access rewrite-rule rule :hyps)
                                        nil ; backchain-limit-lst
                                        unify-subst
                                        nil ; allp=nil for definitions
                                        )
                          :obj nil :geneqv nil :pequiv-info nil ; all ignored
                          )))
                     (cond
                      (relieve-hyps-ans
                       (with-accumulated-persistence
                        rune
                        ((the #.*fixnum-type* step-limit) term-out ttree)
                        t ; considered a success unless the parent with-acc-p fails
                        (sl-let
                         (rewritten-body new-ttree1)
                         (rewrite-entry (rewrite body unify-subst 'body)
                                        :fnstack new-fnstack
                                        :ttree ttree1)

; Again, we use ttree1 to accumulate the successful rewrites and we'll
; return it in our answer if we like our answer.

                         (let ((ttree1 (restore-rw-cache-any-tag new-ttree1
                                                                 ttree1)))
                           (cond
                            ((null recursivep)

; We are dealing with a nonrecursive fn.  If we are at the top-level of the
; clause but the expanded body has too many IFs in it compared to the number
; in the args, we do not use the expanded body.  We know the IFs in
; the args will be clausified out soon and then this will be permitted to
; open.

                             (cond
                              ((and (not (recursive-fn-on-fnstackp fnstack))
                                    (too-many-ifs-post-rewrite args
                                                               rewritten-body))
                               (prog2$
                                (brkpt2 nil 'too-many-ifs-post-rewrite
                                        unify-subst gstack rewritten-body
                                        ttree1 rcnst ancestors state)
                                (prepend-step-limit
                                 2
                                 (rewrite-solidify
                                  term type-alist obj geneqv
                                  (access rewrite-constant rcnst
                                          :current-enabled-structure)
                                  wrld
                                  (accumulate-rw-cache t ttree1 ttree)
                                  simplify-clause-pot-lst
                                  (access rewrite-constant rcnst :pt)))))
                              (t (prog2$
                                  (brkpt2 t nil unify-subst gstack
                                          rewritten-body ttree1 rcnst ancestors
                                          state)
                                  (mv step-limit
                                      rewritten-body
                                      (push-lemma+ rune ttree1 rcnst ancestors
                                                   body rewritten-body))))))
                            ((rewrite-fncallp
                              term rewritten-body
                              (if (cdr recursivep) recursivep nil)
                              (access rewrite-constant rcnst
                                      :top-clause)
                              (access rewrite-constant rcnst
                                      :current-clause)
                              (cdr (access rewrite-rule rule :heuristic-info)))
                             (cond

; Once upon a time, before we were heavily involved with ACL2 proofs, we had
; the following code here.  Roughly speaking this code forced recursive
; functions to open one step at a time if they introduced any IFs.

;                           ((ffnnamep 'if rewritten-body)

; Nqthm Discrepancy: This clause is new to ACL2.  Nqthm always rewrote the
; rewritten body if it contained rewritable calls.  This allows Nqthm to open
; up (member x '(a b c d e)) to a 5-way case split in "one" apparent rewrite.
; In an experiment I have added the proviso above, which avoids rewriting the
; rewritten body if it contains an IF.  This effectively slows down the opening
; of member, forcing the whole theorem back through the simplifier on each
; opening.  Eventually it will open completely, even under this rule.  The
; thought, though, is that often the case splits introduced by such openings
; seems to be irrelevant.  Under this new rule, (length (list a b c d e)) will
; expand in one step to '5, but the member expression above will expand more
; slowly because the expansion introduces a case split.  An experiment was done
; with Nqthm-1992 in which this change was introduced and examples/basic/
; proveall.events was replayed without any trouble and with no apparent
; performance change.  There are undoubtedly example files where this change
; will slow things down.  But it was motivated by an example in which it speeds
; things up by a factor of 10 because the opening is totally irrelevant to the
; proof.  The problem -- which was illustrated in the guard proofs for the
; function ascii-code-lst in the nqthm.lisp events -- is that (member x
; *standard-chars*) opens into a 96-way case split in a situation in which it
; could as well have been disabled.  This happens more in ACL2 than in Nqthm
; because of the presence of defconsts which permit big constants to be fed
; to recursive functions.  It is not clear whether this change is an improvement
; or not.

;                            (prog2$
;                             (brkpt2 t nil unify-subst gstack rewritten-body
;                                     ttree1 rcnst ancestors state)
;                             (mv rewritten-body
;                                 (push-lemma rune ttree1))))

; With further experience, I've decided it is clear that this change is not an
; improvement!  I really like Nqthm's behavior.  The example cited above is
; still a problem.  In particular,

;    (defun ascii-code-lst (lst)
;
;   ; This function converts a standard char list into the list of their
;   ; ascii codes, terminated by a 0.
;
;      (declare (xargs :guard (standard-char-listp lst)
;                      :hints (("Goal" :in-theory (disable member)))
;                      :guard-hints (("Goal" :in-theory (disable member)))))
;      (if (null lst)
;          0
;        (cons (ascii-code (car lst))
;              (ascii-code-lst (cdr lst)))))

; takes forever unless you give the two disable hints shown above.

                              ((contains-rewritable-callp
                                fn rewritten-body
                                (if (cdr recursivep)
                                    recursivep
                                  nil)
                                (access rewrite-constant
                                        rcnst :terms-to-be-ignored-by-rewrite))

; Ok, we are prepared to rewrite the once rewritten body.  But beware!  There
; is an infinite loop lurking here.  It can be broken by using :fnstack
; new-fnstack.  While the loop can be broken by using new-fnstack, that
; approach has a bad side-effect: (member x '(a b c)) is not runout.  It opens
; to (if (equal x 'a) (member x '(b c))) and because new-fnstack mentions
; member, we don't expand the inner call.  See the comment in
; fnstack-term-member for a discussion of loop avoidance (which involved code
; that was here before Version_2.9).

                               (sl-let (rewritten-body ttree2)
                                       (rewrite-entry (rewrite rewritten-body
                                                               nil
                                                               'rewritten-body)
                                                      :fnstack

; See the reference to fnstack in the comment above.

                                                      (cons (cons :TERM term)
                                                            fnstack)
                                                      :ttree ttree1)
                                       (let ((ttree2
                                              (restore-rw-cache-any-tag
                                               (push-lemma+ rune ttree2 rcnst
                                                            ancestors body
                                                            rewritten-body)
                                               ttree1)))
                                         (prog2$
                                          (brkpt2 t nil unify-subst gstack
                                                  rewritten-body ttree2 rcnst
                                                  ancestors state)
                                          (mv step-limit
                                              rewritten-body
                                              ttree2)))))
                              (t
                               (prog2$
                                (brkpt2 t nil unify-subst gstack rewritten-body
                                        ttree1 rcnst ancestors state)
                                (mv step-limit
                                    rewritten-body
                                    (push-lemma+ rune ttree1 rcnst
                                                 ancestors
                                                 body
                                                 rewritten-body))))))
                            (t (prog2$
                                (brkpt2 nil 'rewrite-fncallp unify-subst gstack
                                        rewritten-body ttree1 rcnst ancestors
                                        state)
                                (prepend-step-limit
                                 2
                                 (rewrite-solidify
                                  term type-alist obj geneqv
                                  (access rewrite-constant rcnst
                                          :current-enabled-structure)
                                  wrld
                                  (accumulate-rw-cache t ttree1 ttree)
                                  simplify-clause-pot-lst
                                  (access rewrite-constant rcnst
                                          :pt))))))))
                        :conc
                        (access rewrite-rule rule :hyps)))
                      (t (prog2$
                          (brkpt2 nil failure-reason unify-subst gstack nil
                                  nil rcnst ancestors state)
                          (prepend-step-limit
                           2
                           (rewrite-solidify term type-alist obj geneqv
                                             (access rewrite-constant rcnst
                                                     :current-enabled-structure)
                                             wrld
                                             (accumulate-rw-cache
                                              t ttree1 ttree)
                                             simplify-clause-pot-lst
                                             (access rewrite-constant rcnst
                                                     :pt)))))))))))
                (t
                 (progn$
                  (near-miss-brkpt1 rule term type-alist geneqv
                                    ancestors ttree
                                    gstack rcnst
                                    simplify-clause-pot-lst
                                    state)
                  (brkpt2 nil 'near-miss
                          unify-subst gstack nil nil
                          rcnst ancestors state)
                  (prepend-step-limit
                   2
                   (rewrite-solidify term type-alist obj geneqv
                                     (access rewrite-constant rcnst
                                             :current-enabled-structure)
                                     wrld ttree
                                     simplify-clause-pot-lst
                                     (access rewrite-constant rcnst
                                             :pt)))))))))))))

(defun rewrite-with-lemmas (term ; &extra formals
                            rdepth step-limit
                            type-alist obj geneqv pequiv-info wrld state fnstack
                            ancestors backchain-limit
                            simplify-clause-pot-lst rcnst gstack ttree)
  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((variablep term)
     (rewrite-entry (rewrite-solidify-plus term)))
    ((fquotep term)
     (mv step-limit term ttree))
    ((member-equal (ffn-symb term)
                   (access rewrite-constant rcnst
                           :fns-to-be-ignored-by-rewrite))
     (mv step-limit term ttree))
    ((flambda-applicationp term)
     (mv-let (new-term hyp unify-subst rune rcnst)
             (expand-permission-result term rcnst geneqv wrld)
             (cond (new-term
                    (assert$ (and (null rune) (null hyp))
                             (rewrite-entry (rewrite new-term unify-subst
                                                     'expansion))))
                   (t (rewrite-entry (rewrite-fncall nil term))))))
    (t (sl-let
        (rewrittenp rewritten-term ttree)
        (rewrite-entry (rewrite-with-linear term)
                       :geneqv nil :pequiv-info nil ; both ignored
                       )
        (cond
         (rewrittenp
          (mv step-limit rewritten-term ttree))
         (t
          (sl-let
           (rewrittenp rewritten-term ttree)
           (rewrite-entry
            (rewrite-with-lemmas1 term
                                  (getpropc (ffn-symb term) 'lemmas nil wrld)))
           (cond
            (rewrittenp (mv step-limit rewritten-term ttree))
            (t (mv-let
                (new-term hyp alist rune rcnst)
                (expand-permission-result term rcnst geneqv wrld)
                (cond
                 ((and hyp new-term)

; We want to rewrite something like (if hyp new-term term).  But hyp and
; new-term are to be understood (and rewritten) in the context of the unifying
; substitution, while term is to be understood in the context of the empty
; substitution.  So we lay down code customized to this situation, adapted from
; the definition of rewrite-if.

                  (with-accumulated-persistence
                   rune
                   ((the #.*fixnum-type* step-limit) new-term ttree)
                   t
                   (sl-let
                    (rewritten-test ttree)

; We could save the original ttree to use below when we don't use
; rewritten-test.  But this way we record runes that participated even in a
; failed expansion, which could be of use for those who want to use that
; information for constructing a theory in which the proof may replay.

                    (rewrite-entry (rewrite hyp alist 'expansion)
                                   :geneqv *geneqv-iff*
                                   :pequiv-info nil
                                   :obj t
                                   :ttree (push-lemma? rune ttree))
                    (let ((ens (access rewrite-constant rcnst
                                       :current-enabled-structure)))
                      (mv-let
                        (must-be-true
                         must-be-false
                         true-type-alist false-type-alist ts-ttree)
                        (assume-true-false rewritten-test nil
                                           (ok-to-force rcnst)
                                           nil type-alist ens wrld
                                           nil nil :fta)
                        (declare (ignore false-type-alist))
                        (cond
                         (must-be-true
                          (sl-let
                           (rewritten-new-term ttree)
                           (rewrite-entry
                            (rewrite new-term alist 'expansion)
                            :type-alist true-type-alist
                            :ttree (cons-tag-trees ts-ttree ttree))
                           (mv step-limit
                               rewritten-new-term
                               (push-splitter? rune ttree rcnst ancestors
                                               new-term rewritten-new-term))))
                         (t
                          (let ((hide-reason
                                 (and rune
                                      (not (assoc-eq (car rune)
                                                     *fake-rune-alist*))
                                      (list* :expand
                                             rune
                                             (symbol-in-current-package-p
                                              (base-symbol rune) state)))))
                            (cond
                             (must-be-false
                              (mv step-limit
                                  (hide-with-comment hide-reason term wrld
                                                     state)
                                  (push-lemma (fn-rune-nume 'hide nil nil wrld)
                                              (cons-tag-trees ts-ttree ttree))))
                             (t

; We are tempted to bind ttree here to (normalize-rw-any-cache ttree), as we do
; in a similar situation in rewrite-if.  But limited experiments suggest that
; we may get better performance without doing so.

                              (sl-let
                               (rewritten-left ttree1)
                               (rewrite-entry (rewrite new-term alist 2)
                                              :type-alist true-type-alist
                                              :ttree
                                              (rw-cache-enter-context ttree))
                               (mv-let
                                 (final-term ttree)
                                 (rewrite-if11 (fcons-term* 'if
                                                            rewritten-test
                                                            rewritten-left
                                                            (hide-with-comment
                                                             hide-reason
                                                             term wrld state))
                                               type-alist geneqv wrld
                                               (push-lemma (fn-rune-nume 'hide nil
                                                                         nil wrld)
                                                           (rw-cache-exit-context
                                                            ttree ttree1)))
                                 (mv step-limit
                                     final-term

; We avoid push-lemma+ just below, because ttree already incorporates a call of
; push-lemma? on rune.

                                     (push-splitter? rune ttree rcnst ancestors
                                                     new-term
                                                     final-term))))))))))))))
                 (new-term
                  (with-accumulated-persistence
                   rune
                   ((the #.*fixnum-type* step-limit) new-term ttree)
                   t
                   (sl-let (final-term ttree)
                           (rewrite-entry (rewrite new-term alist 'expansion)
                                          :ttree (push-lemma? rune ttree))
                           (mv step-limit
                               final-term
                               (push-splitter? rune ttree rcnst ancestors
                                               new-term final-term)))))
                 (t (prepend-step-limit
                     2
                     (rewrite-solidify term type-alist obj geneqv
                                       (access rewrite-constant rcnst
                                               :current-enabled-structure)
                                       wrld ttree
                                       simplify-clause-pot-lst
                                       (access rewrite-constant rcnst
                                               :pt))))))))))))))))

(defun rewrite-linear-term (term alist ; &extra formals
                                 rdepth step-limit
                                 type-alist obj geneqv pequiv-info wrld state
                                 fnstack ancestors
                                 backchain-limit
                                 simplify-clause-pot-lst rcnst gstack ttree)

; We desire to rewrite the instantiated conclusion of :LINEAR lemmas
; before adding them to the linear pot.  (We also rewrite with this
; function the hypotheses being added while building the initial pot
; list, when the non-linear package is turned on via set-non-linearp.)
; To avoid tail biting we adopted the policy of rewriting just the
; args of the conclusion.  It is not known whether this is still
; necessary.

; Historical Plaque from Nqthm:

; However, because all of the literals of the clause being proved are on the
; TYPE-ALIST as false, it is possible -- say when proving an instance of an
; already proved :LINEAR lemma -- to rewrite the conclusion to F!  We could
; avoid this by either not putting the linear-like literals on the type alist
; in the first place, or by not rewriting the entire conclusion, just the
; args.  We took the latter approach because it was simplest.  It does suffer
; from the possibility that the whole (< lhs rhs) of the conclusion might
; rewrite to something else, possibly a better <.

; End of Plaque.

; Note that it is not the case that all of the literals of the clause are on
; type-alist!  In rewrite-clause we do not put the current literal on.  During
; the computation of the initial pot-lst in setup-simplify-clause-pot-lst, the
; type-alist is nil.

; We return two things, the rewritten term and the new ttree.

  (declare (ignore obj geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (mv-let
    (not-flg atm)
    (strip-not term)
    (cond ((and (nvariablep atm)
;               (not (fquotep atm))
                (or (eq (ffn-symb atm) '<)
                    (eq (ffn-symb atm) 'equal)))
           (let ((rcnst1 (if (access rewrite-constant rcnst :nonlinearp)
                             (change rewrite-constant rcnst
                                     :active-theory :arithmetic)
                           rcnst)))
             (sl-let (lhs ttree)
                     (rewrite-entry (rewrite (fargn atm 1) alist 1)
                                    :obj '?
                                    :geneqv nil ; geneqv equal
                                    :pequiv-info nil

; If we have enabled non-linear arithmetic, we change theories here,
; so that we can have a different normal form for polys and linear- and
; non-linear-arithmetic than when rewriting.

                                    :rcnst rcnst1)
                     (sl-let (rhs ttree)
                             (rewrite-entry (rewrite (fargn atm 2) alist 2)
                                            :obj '?
                                            :geneqv nil ; geneqv equal
                                            :pequiv-info nil

; We change theories here also.

                                            :rcnst rcnst1)
                             (cond
                              (not-flg
                               (mv step-limit
                                   (mcons-term*
                                    'not
                                    (mcons-term* (ffn-symb atm) lhs rhs))
                                   ttree))
                              (t (mv step-limit
                                     (mcons-term* (ffn-symb atm) lhs rhs)
                                     ttree)))))))
          (t (mv step-limit (sublis-var alist term) ttree))))))

(defun rewrite-linear-term-lst (term-lst ttrees ; &extra formals
                                         rdepth step-limit
                                         type-alist obj geneqv pequiv-info
                                         wrld state fnstack ancestors
                                         backchain-limit
                                         simplify-clause-pot-lst
                                         rcnst gstack ttree)

; We wish to be able to have a different normal form when doing
; linear and non-linear arithmetic than when doing normal rewriting.
; Therefore, before seeding the linear pot with a poly, we rewrite it
; under the theory prevailing in rewrite-linear-term.

; Term-lst is a list of terms as received by add-terms-and-lemmas, and
; ttrees is its corresponding list of tag-trees.  We simply call
; rewrite-linear-term (nee rewrite-linear-concl in ACL2 Version_2.6)
; on each member of term-lst and return two lists --- the rewritten
; terms and their ttrees.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (if (null term-lst)
       (mv step-limit nil nil)
     (sl-let
      (term1 ttree1)
      (rewrite-entry (rewrite-linear-term (car term-lst) nil)
                     :obj nil ; ignored
                     :geneqv nil ; ignored
                     :pequiv-info nil ; ignored
                     :type-alist (cleanse-type-alist type-alist
                                                     (collect-parents
                                                      (car ttrees)))
                     :ttree (car ttrees))
      (sl-let (term-lst ttree-lst)
              (rewrite-entry (rewrite-linear-term-lst (cdr term-lst)
                                                      (cdr ttrees))
                             :obj nil ; ignored
                             :geneqv nil ; ignored
                             :pequiv-info nil ; ignored
                             :ttree nil ; ignored
                             )
              (mv step-limit
                  (cons term1 term-lst)
                  (cons ttree1 ttree-lst)))))))

(defun add-linear-lemma (term lemma ; &extra formals
                              rdepth step-limit
                              type-alist obj geneqv pequiv-info wrld state
                              fnstack ancestors backchain-limit
                              simplify-clause-pot-lst rcnst gstack ttree)

; We investigate the application of lemma to term and the
; simplify-clause-pot-lst.  If term unifies with the max-term of lemma and we
; can relieve the hypotheses, we add the polynomial produced from lemma's
; conclusion to the pot-lst.  We return three values.  The second is the
; standard contradictionp.  The third is a possibly modified
; simplify-clause-pot-lst.

; PATCH: We use a new field in the linear pots to catch potential loops.
; Loop-stopper-value is initially 0 in all the linear pots.  Let value be the
; loop-stopper-value associated with term in simplify-clause-pot-lst.  When we
; return a new linear-pot-list, we check to see if there are any new pots.  Let
; pot be such a new pot.  If the largest var in pot is term order greater than
; term, we set the loop-stopper-value of pot to value + 1.  Otherwise, we set
; it to value.

; Now, before we actually add any polys to simplify-clause-pot-lst, we call
; no-new-and-ugly-linear-varsp on the list of polys to be added.  This function
; (among other things) checks whether the new vars would have a
; loop-stopper-value which exceeds *max-linear-pot-loop-stopper-value*.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (let ((gstack (push-gframe 'add-linear-lemma nil term lemma))
         (rdepth (adjust-rdepth rdepth)))
     (mv-let
      (unify-ans unify-subst)
      (one-way-unify (access linear-lemma lemma :max-term)
                     term)
      (cond
       ((and unify-ans
             (null (brkpt1 lemma term unify-subst
                           type-alist nil ; geneqv ignored
                           ancestors nil ; ttree
                           gstack rcnst simplify-clause-pot-lst state)))
        (let ((rune (access linear-lemma lemma :rune)))
          (with-accumulated-persistence
           rune
           ((the #.*fixnum-type* step-limit) contradictionp pot-lst)
           (or contradictionp

; The following mis-guarded use of eq instead of equal implies that we could be
; over-counting successes at the expense of failures.

               (not (eq pot-lst simplify-clause-pot-lst)))
           (sl-let
            (relieve-hyps-ans failure-reason unify-subst ttree1)
            (rewrite-entry (relieve-hyps rune
                                         term
                                         (access linear-lemma lemma :hyps)
                                         (access linear-lemma lemma
                                                 :backchain-limit-lst)
                                         unify-subst
                                         (not (oncep (access rewrite-constant
                                                             rcnst
                                                             :oncep-override)
                                                     (access linear-lemma lemma
                                                             :match-free)
                                                     rune
                                                     (access linear-lemma lemma
                                                             :nume))))
                           :obj nil :geneqv nil :pequiv-info nil ; all ignored
                           :ttree nil)
            (cond
             (relieve-hyps-ans
              (sl-let
               (rewritten-concl ttree2)
               (with-accumulated-persistence
                rune
                ((the #.*fixnum-type* step-limit) rewritten-concl ttree2)
                t ; considered a success unless the parent with-acc-p fails
                (rewrite-entry
                 (rewrite-linear-term
                  (access linear-lemma lemma :concl)
                  unify-subst)
                 :obj nil :geneqv nil :pequiv-info nil ; all ignored
                 :ttree ttree1)
                :conc
                (access linear-lemma lemma :hyps))

; Previous to Version_2.7, we just went ahead and used the result of
; (linearize rewritten-concl ...).  This had long been known to be
; problematic (see the comments in linearize1 beginning ``This is a
; strange one.'') but nothing had been done about it.  Then Eric Smith
; sent the following example to us and wanted to know what was going
; wrong.

;    (defstub bitn (x n) t)   ; extract bit n of x
;
;    (skip-proofs
;     (defthm bitn-non-negative-integer
;      (and (integerp (bitn x n))
;           (<= 0 (bitn x n)))
;      :rule-classes (:rewrite :type-prescription)))
;
;    (skip-proofs
;     (defthm bits-upper-bound-linear
;       (< (bits x i j) (expt 2 (+ i 1 (- j))))
;       :rule-classes ((:linear :trigger-terms ((bits x i j))))))
;
;    ;goes through (using the two :linear rules above)
;    (thm
;     (< (+ (BITN x 32)
;           (BITN x 58))
;        2))
;
;    ;the problem rule.
;    (skip-proofs
;     (defthm bitn-known-not-0-replace-with-1
;      (implies (not (equal (bitn x n) 0))
;               (equal (bitn x n)
;                      1))))
;
;    ;same thm; now fails --- the rule above causes linear arithmetic to fail.
;
;    (thm
;     (< (+ (BITN x 32)
;           (BITN x 58))
;        2))

; If one uses the following trace and replays the above script, one
; can see what was happening (In a nutshell, ACL2 rewrites the (BITN B
; Z) in the instantiated conclusion of bitn-upper-bound-linear, (<=
; (BITN B Z) 1), to 1 yielding (<= 1 1), which is trivially true but
; not very useful.

;    (defun show-type-alist (type-alist)
;      (cond ((endp type-alist) nil)
;            (t (cons (list (car (car type-alist))
;                           (decode-type-set (cadr (car type-alist))))
;                     (show-type-alist (cdr type-alist))))))
;    SHOW-TYPE-ALIST
;    ACL2(3): (trace (add-polys
;             :entry (list (list 'new-polys (show-poly-lst (nth 0 arglist)))
;                          (list 'pot-lst (show-pot-lst (nth 1 arglist)))
;                          (list 'type-alist (show-type-alist (nth 3 arglist))))
;             :exit (list (list 'contradictionp (nth 0 values))
;                         (list 'new-pot-lst (show-pot-lst (nth 1 values)))))
;           (add-linear-lemma
;             :entry (list (list 'term (nth 0 arglist))
;                          (list 'lemma (nth 1 arglist)))
;             :exit (list (list 'contradictionp (nth 0 values))
;                         (list 'new-pot-lst (show-pot-lst (nth 1 values)))))
;          (rewrite-linear-term
;             :entry (list (list 'term (sequential-subst-var-term (nth 1 arglist)
;                                                                 (nth 0 arglist))))
;             :exit (list (list 'rewritten-term (nth 0 values))
;                         (list 'ttree (nth 1 arglist)))))
;    (REWRITE-LINEAR-TERM ACL2_*1*_ACL2::REWRITE-LINEAR-TERM ADD-LINEAR-LEMMA
;                          ACL2_*1*_ACL2::ADD-LINEAR-LEMMA ADD-POLYS
;                          ACL2_*1*_ACL2::ADD-POLYS)

; The best solution would probably be to not rewrite the instantiated
; trigger term in rewrite-linear-term, but that has its own problems
; and is much more work to implement.  By just reverting to the
; un-rewritten concl we catch the ``obvious'' cases such as
; illustrated above.  Note that the un-rewritten concl may also
; linearize to nil, but a regression test using the community books
; actually shows a slight improvement in speed (about a
; minute and a half, out of 158 and a half minutes), so we conclude
; that this is not a problem in practice.

; We thank Robert Krug for providing this improvement.

               (let ((force-flg (ok-to-force rcnst)))
                 (mv-let
                  (contradictionp new-pot-lst failure-reason brr-result)
                  (add-linear-lemma-finish rewritten-concl force-flg rune t
                                           term type-alist wrld state
                                           simplify-clause-pot-lst rcnst ttree2)
                  (cond
                   (contradictionp
                    (prog2$ (brkpt2 t nil unify-subst gstack
                                    brr-result
                                    nil ; ttree, not used (see brkpt2)
                                    rcnst ancestors state)
                            (mv step-limit contradictionp nil)))
                   (t
                    (mv-let
                     (contradictionp new-pot-lst failure-reason brr-result)
                     (let ((unrewritten-concl-to-try
                            (and (or (eq new-pot-lst :null-lst)

; Simplify-clause arranges for the following term to be true immediately after
; the clause has settled down.  In that case, we are prepared to try any
; "desperation heuristics", such as (here) linearizing the unrewritten
; conclusion in cases when we would have stopped after linearizing the
; rewritten conclusion.  Below are two examples that motivated this change.

; Example 1.

; Consider the following theorem:
; (<= (len (cdr (cdr (nthcdr n stk))))
;      (len stk))

; A script is below that introduces two linear lemmas that one could reasonably
; expect to suffice for proving this theorem, given the following informal
; proof.

;   (len (cdr (cdr (nthcdr n stk))))
;   <=                                 ; by linear1
;   (len (cdr (nthcdr n stk)))
;   <=                                 ; by linear1
;   (len (nthcdr n stk))
;   <=                                 ; by linear2
;   (len stk)

; Here are the two linear lemmas.

;   (defthm linear1
;     (<= (len (cdr stk)) (len stk))
;     :rule-classes :linear)

;   (defthm linear2
;     (<= (len (nthcdr n stk)) (len stk))
;     :rule-classes :linear)

; The following theorem did not prove until after we added this "desperate
; heuristic" to linearize the unrewritten conclusion.

;   (thm (<= (len (cdr (cdr (nthcdr n stk))))
;            (len stk))
;        :hints (("Goal" :do-not-induct t)))

; Example 2.

; First evaluate these events:

;   (include-book "arithmetic-5/top" :dir :system)
;
;   (defthm mod-linear
;     (implies (and (natp x) (natp k)) (<= (mod x k) x))
;     :rule-classes :linear)
;
;   (encapsulate ((rd (x) t))
;                (local (defun rd (x) (nfix x)))
;                (defthm natp-rd (natp (rd x))
;                  :rule-classes :type-prescription))

; The following proves, and indeed proved (without induction) before the
; change.

;   (thm (<= (mod (rd x) 4)
;            (+ 1 (rd x))))

; But the following theorem only proved after the change.  Naively one wouldn't
; expect the hypothesis to get in the way.  (We are not using induction in this
; example.)  To make matters worse, the hypothesis is provable; the two
; theorems really are equivalent.

;   (thm (implies
;         (< (mod (rd x) 4) 5)
;         (<= (mod (rd x) 4)
;             (+ 1 (rd x)))))

                                     (eq (access rewrite-constant rcnst
                                                 :rewriter-state)
                                         'settled-down))
                                 (sublis-var unify-subst
                                             (access linear-lemma lemma
                                                     :concl)))))
                       (cond
                        ((and unrewritten-concl-to-try
                              (not (equal rewritten-concl
                                          unrewritten-concl-to-try)))
                         (add-linear-lemma-finish
                          unrewritten-concl-to-try
                          force-flg
                          rune nil
                          term type-alist wrld state
                          (if (eq new-pot-lst :null-lst)
                              simplify-clause-pot-lst
                            new-pot-lst)
                          rcnst
                          (push-lemma
                           rune
                           (accumulate-rw-cache t
                                                ttree2
                                                ttree1))))
                        (t (mv nil new-pot-lst failure-reason brr-result))))
                     (cond (contradictionp
                            (prog2$ (brkpt2 t nil unify-subst gstack
                                            brr-result
                                            nil ; ttree, not used (see brkpt2)
                                            rcnst ancestors state)
                                    (mv step-limit contradictionp nil)))
                           (failure-reason
                            (prog2$ (brkpt2 nil failure-reason unify-subst gstack
                                            brr-result
                                            nil ; ttree, not used (see brkpt2)
                                            rcnst ancestors state)
                                    (mv step-limit nil new-pot-lst)))
                           (t
                            (prog2$ (brkpt2 t nil unify-subst gstack
                                            brr-result
                                            nil ; ttree, not used (see brkpt2)
                                            rcnst ancestors state)
                                    (mv step-limit nil new-pot-lst)))))))))))
             (t (prog2$
                 (brkpt2 nil failure-reason
                         unify-subst gstack nil nil
                         rcnst ancestors state)
                 (mv step-limit nil simplify-clause-pot-lst))))))))
       (t (progn$
           (near-miss-brkpt1 lemma term type-alist nil ; geneqv ignored!
                             ancestors nil ; ttree
                             gstack rcnst
                             simplify-clause-pot-lst
                             state)
           (brkpt2 nil 'near-miss
                   unify-subst gstack nil nil
                   rcnst ancestors state)
           (mv step-limit nil simplify-clause-pot-lst))))))))

(defun add-linear-lemmas (term linear-lemmas ; &extra formals
                               rdepth step-limit
                               type-alist obj geneqv pequiv-info wrld state
                               fnstack ancestors
                               backchain-limit
                               simplify-clause-pot-lst rcnst gstack ttree)

; Linear-lemmas is a list of linear-lemmas.  We look for those lemmas
; in linear-lemmas that match term and, if their hyps can be relieved
; and the resulting polys don't contain new and ugly vars, add them to
; the simplify-clause-pot-lst.

; We return two values.  The first is the standard contradictionp.
; The second is the possibly new pot-lst.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((null linear-lemmas)
     (mv step-limit nil simplify-clause-pot-lst))
    ((not (enabled-numep (access linear-lemma (car linear-lemmas) :nume)
                         (access rewrite-constant rcnst
                                 :current-enabled-structure)))
     (rewrite-entry (add-linear-lemmas term (cdr linear-lemmas))
                    :obj nil ; ignored
                    :geneqv nil ; ignored
                    :pequiv-info nil ; ignored
                    :ttree nil ; ignored
                    ))
    (t (sl-let
        (contradictionp new-pot-lst)
        (rewrite-entry (add-linear-lemma term
                                         (car linear-lemmas))
                       :obj nil ; ignored
                       :geneqv nil ; ignored
                       :pequiv-info nil ; ignored
                       :ttree nil ; ignored
                       )
        (cond (contradictionp (mv step-limit contradictionp nil))
              (t (rewrite-entry
                  (add-linear-lemmas term (cdr linear-lemmas))
                  :obj nil ; ignored
                  :geneqv nil ; ignored
                  :pequiv-info nil ; ignored
                  :ttree nil ; ignored
                  :simplify-clause-pot-lst new-pot-lst))))))))

(defun multiply-alists2 (alist-entry1 alist-entry2 poly ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info wrld
                                      state fnstack ancestors backchain-limit
                                      simplify-clause-pot-lst
                                      rcnst gstack ttree)

; We are in the middle of multiplying two polys.  Poly is the result
; so far.  Alist-entry1 is an alist entry from the first poly, and
; alist-entry2 is an alist entry from the second poly.  See multiply-alists.

; Here, we perform the actual multiplication of the two alist entries
; and add the result to poly.  Note that each entry is of the form
; (term . coeff).

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (let* ((leaves1 (binary-*-leaves (car alist-entry1)))
          (leaves2 (binary-*-leaves (car alist-entry2)))
          (leaves (merge-arith-term-order leaves1 leaves2))
          (tree (binary-*-tree leaves))
          (coeff (* (cdr alist-entry1)
                    (cdr alist-entry2)))
          (temp-entry (mcons-term* 'BINARY-*
                                   (kwote coeff)
                                   tree)))
     (sl-let
      (new-entry new-ttree)
      (rewrite-entry (rewrite temp-entry nil 'multiply-alists2)
                     :obj '?
                     :geneqv nil
                     :pequiv-info nil

; We change theories here, so that we can have a different normal form
; for the terms in polys than when rewriting in general.

                     :rcnst (change rewrite-constant rcnst
                                    :active-theory :arithmetic)
                     :ttree nil)
      (let ((new-poly (add-linear-term new-entry 'rhs poly)))
        (mv step-limit
            (change poly new-poly
                    :ttree (cons-tag-trees-rw-cache new-ttree
                                                    (access poly new-poly
                                                            :ttree))
                    :parents (marry-parents
                              (collect-parents new-ttree)
                              (access poly new-poly :parents)))))))))

(defun multiply-alists1 (alist-entry alist2 poly ; &extra formals
                                     rdepth step-limit
                                     type-alist obj geneqv pequiv-info
                                     wrld state
                                     fnstack ancestors backchain-limit
                                     simplify-clause-pot-lst
                                     rcnst gstack ttree)

; We are in the middle of multiplying two polys.  Poly is the result
; so far.  Alist-entry is an alist entry from the first poly, and
; alist2 is the alist from the second poly.  See multiply-alists.

; Here, we cdr down alist2 multiplying alist-entry by each entry in
; alist2 and adding the result to poly.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null alist2)
     (mv step-limit poly))
    (t
     (sl-let
      (temp-poly)
      (rewrite-entry
       (multiply-alists2 alist-entry
                         (car alist2)
                         poly)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (rewrite-entry
       (multiply-alists1 alist-entry
                         (cdr alist2)
                         temp-poly)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))))))

(defun multiply-alists (alist1 alist2 poly ; &extra formals
                               rdepth step-limit
                               type-alist obj geneqv pequiv-info
                               wrld state fnstack ancestors backchain-limit
                               simplify-clause-pot-lst
                               rcnst gstack ttree)

; We are in the middle of multiplying two polys.  Poly is the result
; so far.  Initially, it has a partially filled alist and we need to
; finish filling it in.  Alist1 is the alist from the first poly,
; and alist2 is the alist from the second poly.

; If one thinks of the initial polys as

; 0 < const1 + alist1 and 0 < const2 + alist2,

; poly initially contains
; 0 < const1*const2 + const1*alist2 + const2*alist1 + ()
; and our job is to successively add things to the ().

; In particular, we wish to form alist1*alist2.  Here, we cdr down
; alist1 multiplying each entry by alist2 and adding the result to poly.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null alist1)
     (mv step-limit poly))
    (t
     (sl-let
      (temp-poly)
      (rewrite-entry
       (multiply-alists1 (car alist1)
                         alist2
                         poly)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (rewrite-entry
       (multiply-alists (cdr alist1)
                        alist2
                        temp-poly)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))))))

(defun multiply-polys1 (alist1 const1 rel1 alist2 const2 rel2
                               poly ; &extra formals
                               rdepth step-limit
                               type-alist obj geneqv pequiv-info
                               wrld state fnstack ancestors backchain-limit
                               simplify-clause-pot-lst
                               rcnst gstack ttree)

; We are in the middle of multiplying two polys.  Poly is the result so far.
; Initially, it has an empty alist which we need to fill in.  Alist1 and const1
; are the alist and constant from the first poly, and alist2 and const2 are
; from the second poly.  We assume that at least one of these two polys is
; rational-poly-p.  Here we construct the alist for poly, finishing the process.

; If one thinks of the initial polys as

; 0 < const1 + alist1 and 0 < const2 + alist2,

; poly initially contains 0 < const1*const2 + () and our job is to successively
; add things to the ().  We wish to form const1*alist2 + const2*alist1 +
; alist1*alist2.  The first two steps are performed by the successive
; multiply-alist-and-consts in the let* below, accumulating their answers
; into the growing alist.  We finish with multiply-alists.

  (declare (ignore obj geneqv pequiv-info ttree rel1 rel2)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

; Warning: It may be tempting to add the following optimization, as was done up
; through Version_3.3.  Don't do it!  The optimization is that under suitable
; hypotheses (see optimization code below): when given 0 < a1 + b1x and 0 < a2
; + b2y, first let a1' = -a1 and b1' = -b1 and then multiply a1' < b1x by a2' <
; b2 y to get a1'a2' < b1b2xy.

; Consider the following example that illustrates the problem with this
; optimization.

; (set-non-linearp t)
; (thm (implies (and (rationalp x) (< 3 x)
;                    (rationalp y) (< 4 y))
;               (< 0 (+ 12 (* -4 x) (* -3 y) (* x y)))))

; With the optimization shown below, the proof fails, because the hypotheses
; only generate the weaker inequality (< 0 (+ -12 (* x y))).  This inequality,
; which we will name In0, is weaker than the thm's conclusion above because
; under the thm's hypotheses, we have (< (* -4 x) -12) and (< (* -3 x) -12),
; and adding these inequalities to the thm's conclusion yields In0.  In0 is
; strictly weaker than the thm's conclusion: consider x=13 and y=1, which makes
; In0 true but makes the thm's conclusion false.  Of course, that example
; doesn't take into account the hypotheses on x and y above, so the following
; example may be more persuasive.  Consider abstracting (* x y) to a new
; variable z, and consider whether the weaker inequality implies the stronger
; -- if so, then we would expect linear arithmetic reasoning to be able to
; derive the stronger from the weaker when necessary.

; (implies (and (rationalp x) (< 3 x)
;               (rationalp y) (< 4 y)
;               (rationalp z) (< 12 z))
;          (< 0 (+ 12 (* -4 x) (* -3 y) z)))

; But this is not a theorem -- consider x = y = z = 100.

; Here, then, is the optimization code to avoid:

; (if (and (rationalp const1)
;          (rationalp const2)
;          (< const1 0)
;          (< const2 0))
;     (let ((temp-poly (if (and (eq (access poly poly :relation) '<=)
;                               (or (eq rel1 '<)
;                                   (eq rel2 '<)))
;                          (change poly poly
;                                  :constant
;                                  (- (access poly poly :constant))
;                                  :relation
;                                  '<)
;                        (change poly poly
;                                :constant
;                                (- (access poly poly :constant))))))
;       (rewrite-entry
;        (multiply-alists alist1 alist2
;                         temp-poly)
;        :obj nil
;        :geneqv nil
;        :pequiv-info nil
;        :ttree nil))

; The following examples from Robert Krug illustrate issues pertaining to the
; above "optimization".  First note that the following fails with the
; optimization.  We have labeled interesting hypotheses for an explanation
; below.

; (set-non-linearp t)
; (thm
;  (implies (and (rationalp i)
;                (rationalp n)
;                (rationalp r)
;                (<= 1 i)      ; [1]
;                (<= 1 n)      ; [2]
;                (< r 0)       ; [3]
;                (< (- i) r))  ; [4]
;           (<= 0 (+ r (* i n)))))

; However, if in this formula we change r to a, and/or if we comment out the
; hypothesis (<= 1 i), then we succeed with or without the optimization,
; i.e. in Version_3.3 or beyond.

; First, consider how commenting out [1] can help.  ACL2 can add hypotheses [3]
; and [4] about r to generate 0 < i.  This can be multiplied by [2] (in the
; form 0 <= -1 + n) to generate an i*n term.  This product -- performed without
; the optimization, since 0 < i has a constant of zero -- is 0 < -i + i*n.
; This adds to [4] to yield the conclusion.  BUT if [1] is around, it subsumes
; generated inequality 0 < i, and then with the optimization, hypotheses [1]
; and [2] generate 1 <= i*n, and we claim that the conclusion no longer follows
; by linear reasoning.  To verify this claim, treat i*n as a variable by
; replacing it with z, and then notice that the following evaluates to NIL:

; (let ((i 10) (n 10) (r -5) (z 1))
;   (implies (and (rationalp i)
;                 (rationalp n)
;                 (rationalp r)
;                 (rationalp z)
;                 (<= 1 i)      ; [1]
;                 (<= 1 n)      ; [2]
;                 (< r 0)       ; [3]
;                 (< (- i) r)   ; [4]
;                 (<= 1 z))     ; generated, with i*n abstracted
;            (<= 0 (+ r z))))

; Second, consider how changing r to a can help.  We have the following.

; (thm
;  (implies (and (rationalp i)
;                (rationalp n)
;                (rationalp a)
;                (<= 1 i)      ; [1]
;                (<= 1 n)      ; [2]
;                (< a 0)       ; [3]
;                (< (- i) a))  ; [4]
;           (<= 0 (+ a (* i n)))))

; This time, [4] is about i, not r.  So in order to obtain an i*n term, we can
; multiply [4] (actually 0 < i + a) by [2] (actually 0 <= -1 + n), and what's
; more, there is no "optimization" since [4] has a constant of 0.
; Multiplication gives us: 0 < -i + i*n - a + a*n.  We add this to the negated
; conclusion, 0 < -a - i*n, to obtain 0 < -i - 2*a + a*n.  We combine this with
; [4] to obtain 0 < -a + a*n.  We then generate an inequality about a*n by
; multiplying [2] and [3] (without optimization, since [3] has a constant of 0)
; to obtain 0 < a - a*n.  Adding this to the previous result yields a
; contradiction.

  (the-mv
   2
   #.*fixnum-type*
   (let* ((temp-poly1
           (if (eql const2 0)
               poly
             (multiply-alist-and-const alist1 const2 poly)))
          (temp-poly2
           (if (eql const1 0)
               temp-poly1
             (multiply-alist-and-const alist2 const1 temp-poly1))))
     (rewrite-entry
      (multiply-alists alist1 alist2 temp-poly2)
      :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
      ))))

(defun multiply-polys (poly1 poly2 ; &extra formals
                             rdepth step-limit
                             type-alist obj geneqv pequiv-info wrld state fnstack
                             ancestors backchain-limit
                             simplify-clause-pot-lst
                             rcnst gstack ttree)

; We are to multiply the two polys, poly1 and poly2.  Roughly speaking this
; function implements the lemma:

; (implies (and (rationalp terms1)
;               (< 0 terms1)
;               (< 0 terms2))
;          (< 0 (* terms1 terms2)))

; We assume that either poly1 or poly2 is rational-poly-p.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (let ((alist1 (access poly poly1 :alist))
         (ttree1 (access poly poly1 :ttree))
         (const1 (access poly poly1 :constant))
         (rel1 (access poly poly1 :relation))
         (parents1 (access poly poly1 :parents))
         (ratp1 (access poly poly1 :rational-poly-p))
         (alist2 (access poly poly2 :alist))
         (ttree2 (access poly poly2 :ttree))
         (const2 (access poly poly2 :constant))
         (rel2 (access poly poly2 :relation))
         (parents2 (access poly poly2 :parents))
         (ratp2 (access poly poly2 :rational-poly-p)))
     (let ((pre-poly (make poly
                           :alist nil
                           :ttree (cons-tag-trees-rw-cache ttree1 ttree2)
                           :parents (marry-parents parents1 parents2)
                           :constant (* const1 const2)
                           :relation (if (and (eq rel1 '<)
                                              (eq rel2 '<))
                                         '<
                                       '<=)
                           :rational-poly-p (and ratp1 ratp2))))
       (sl-let
        (poly)
        (rewrite-entry
         (multiply-polys1 alist1 const1 rel1
                          alist2 const2 rel2
                          pre-poly)
         :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
         )
        (mv step-limit (normalize-poly poly)))))))

(defun multiply-pots2 (poly big-poly-list new-poly-list ; &extra formals
                            rdepth step-limit
                            type-alist obj geneqv pequiv-info wrld state fnstack
                            ancestors backchain-limit
                            simplify-clause-pot-lst
                            rcnst gstack ttree)

; Poly is a poly and we are to multiply it by the polys in
; big-poly-list, accumulating the answer into new-poly-list.  We
; assume that poly is a rational-poly-p.  Every poly in big-poly-list
; is assumed to be a rational-poly-p.

; We return a list of polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null big-poly-list)
     (mv step-limit new-poly-list))
    ((or (access poly poly :rational-poly-p)
         (access poly (car big-poly-list) :rational-poly-p))

; If at least one of poly and (car big-poly-list) are rational, multiplication
; preserves sign.  See the comments in multiply-polys.

     (sl-let (new-poly)
             (rewrite-entry
              (multiply-polys poly (car big-poly-list))
              :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
              )
             (rewrite-entry
              (multiply-pots2 poly
                              (cdr big-poly-list)
                              (cons new-poly new-poly-list))
              :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
              )))
    (t

; Since neither poly is known to be rational, we skip this multiplication.

     (rewrite-entry
      (multiply-pots2 poly
                      (cdr big-poly-list)
                      new-poly-list)
      :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
      )))))

(defun multiply-pots1 (poly-list big-poly-list new-poly-list ; &extra formals
                                 rdepth step-limit
                                 type-alist obj geneqv pequiv-info wrld state
                                 fnstack ancestors backchain-limit
                                 simplify-clause-pot-lst
                                 rcnst gstack ttree)

; Both poly-list and big-poly-list are lists of polys.  We are to
; multiply the polys in poly-list by those in big-poly-list.
; New-poly-list is initially nil, and is where we accumulate our
; answer.  We assume every element of big-poly-lst is a
; rational-poly-p.

; We return a list of polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null poly-list)
     (mv step-limit new-poly-list))
    (t
     (sl-let
      (new-new-poly-list)
      (rewrite-entry
       (multiply-pots2 (car poly-list)
                       big-poly-list
                       new-poly-list)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (rewrite-entry
       (multiply-pots1 (cdr poly-list)
                       big-poly-list
                       new-new-poly-list)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))))))

(defun multiply-pots-super-filter (var-list pot-lst-to-look-in ; &extra formals
                                            rdepth step-limit
                                            type-alist obj geneqv pequiv-info
                                            wrld state fnstack
                                            ancestors
                                            backchain-limit
                                            simplify-clause-pot-lst
                                            rcnst gstack ttree)

; This function is similar to multiply-pots, which see, except that we
; only multiply the bounds polys of the pots labeled by the vars in var-list.

; We return a list of polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null var-list)
     (mv step-limit nil))
    ((null (cdr var-list))
     (mv step-limit
         (shortest-polys-with-var (car var-list)
                                  pot-lst-to-look-in
                                  (access rewrite-constant rcnst :pt))))
    (t
     (sl-let
      (big-poly-list)
      (rewrite-entry
       (multiply-pots-super-filter (cdr var-list)
                                   pot-lst-to-look-in)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (rewrite-entry
       (multiply-pots1 (shortest-polys-with-var (car var-list)
                                                pot-lst-to-look-in
                                                (access rewrite-constant
                                                        rcnst
                                                        :pt))
                       big-poly-list
                       nil)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))))))

(defun multiply-pots-filter (var-list pot-lst-to-look-in ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info
                                      wrld state
                                      fnstack ancestors backchain-limit
                                      simplify-clause-pot-lst
                                      rcnst gstack ttree)

; This function is similar to multiply-pots except that we assume
; var-list is of length two, and we multiply only some of the polys.
; in particular, we multiply the bounds polys of one pot by the polys
; in the other pot, and vice-versa.

; We return a list of polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (sl-let
    (poly-list1)
    (rewrite-entry
     (multiply-pots1 (bounds-polys-with-var (car var-list)
                                            pot-lst-to-look-in
                                            (access rewrite-constant
                                                    rcnst
                                                    :pt))
                     (polys-with-var (cadr var-list)
                                     pot-lst-to-look-in)
                     nil)
     :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
     )
    (rewrite-entry
     (multiply-pots1 (bounds-polys-with-var (cadr var-list)
                                            pot-lst-to-look-in
                                            (access rewrite-constant
                                                    rcnst
                                                    :pt))
                     (polys-with-var (car var-list)
                                     pot-lst-to-look-in)
                     poly-list1)
     :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
     ))))

(defun multiply-pots (var-list pot-lst-to-look-in ; &extra formals
                               rdepth step-limit
                               type-alist obj geneqv pequiv-info
                               wrld state fnstack ancestors backchain-limit
                               simplify-clause-pot-lst
                               rcnst gstack ttree)

; Var-list is a list of pot-labels in pot-lst-to-look-in.  We are
; about to multiply the polys of the labeled pots.  We recur down
; var-list and as we unwind the recursion we multiply the polys
; corresponding to the first pot-label in var-list by the result
; of multiplying the polys corresponding to the rest of the pot-labels.
; Multiply-pots1 is responsible for carrying out the actual multiplication.

; We return a list of polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   2
   #.*fixnum-type*
   (cond
    ((null var-list) ; How can we multiply 0 things?
     (mv step-limit nil))
    ((null (cdr var-list))
     (mv step-limit
         (polys-with-var (car var-list) pot-lst-to-look-in)))
    (t
     (sl-let
      (big-poly-list)
      (rewrite-entry
       (multiply-pots (cdr var-list)
                      pot-lst-to-look-in)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (rewrite-entry
       (multiply-pots1 (polys-with-var (car var-list)
                                       pot-lst-to-look-in)
                       big-poly-list
                       nil)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))))))

(defun add-multiplied-polys-filter (var-list products-already-tried
                                             pot-lst-to-look-in ; &extra formals
                                             rdepth step-limit
                                             type-alist obj geneqv pequiv-info
                                             wrld state fnstack
                                             ancestors backchain-limit
                                             simplify-clause-pot-lst
                                             rcnst gstack ttree)

; This function assumes that var-list is of length two.  It is similar to
; add-multiply-pots, which see, except that we only multiply some of the polys
; corresponding to the pots labeled by the vars in var-list.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((product-already-triedp var-list products-already-tried)
     (mv step-limit nil simplify-clause-pot-lst products-already-tried))
    (t
     (sl-let
      (poly-list1)
      (rewrite-entry
       (multiply-pots-filter var-list
                             pot-lst-to-look-in)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )

; By filtering the polys so that we avoid creating new pots, we can
; dramatically speed up proofs, for example the failure of the following.  (The
; result is reversed, but no matter.)  Robert Krug contributed this
; modification, and expresses the opinion that the extra consing done by
; polys-with-pots is quite likely less expensive in general than the effort it
; would take to see if any filtering actually occurs, especially since
; filtering probably does occur most of the time.

;    (include-book "arithmetic-3/bind-free/top" :dir :system)
;    (set-default-hints '((nonlinearp-default-hint stable-under-simplificationp
;                                                  hist pspv)))
;    (defstub f (x) t)
;    (thm
;     (implies (and (rationalp (f r))
;                   (integerp (f i))
;                   (< (f i) 0)
;                   (not (integerp (* (f r) (/ (f y)))))
;                   (< (f r) (f y))
;                   (< (/ (f r) (f y)) 1)
;                   (< 0 (f r))
;                   (< (+ (f r) (* (f i) (f y))) -1)
;                   (rationalp (f y))
;                   (<= 2 (f y)))
;              (< (+ (f r) (* (f i) (f y))) (f i))))

      (let ((poly-list2 (polys-with-pots poly-list1
                                         simplify-clause-pot-lst
                                         nil)))
        (mv-let (contradictionp new-pot-lst)
                (add-polys poly-list2
                           simplify-clause-pot-lst
                           (access rewrite-constant rcnst :pt)
                           (access rewrite-constant rcnst :nonlinearp)
                           type-alist
                           (access rewrite-constant rcnst
                                   :current-enabled-structure)
                           (ok-to-force rcnst)
                           wrld)
                (mv step-limit contradictionp new-pot-lst
                    (cons (sort-arith-term-order var-list)
                          products-already-tried)))))))))

(defun add-multiplied-polys (var-list products-already-tried
                                      pot-lst-to-look-in ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info
                                      wrld state
                                      fnstack ancestors backchain-limit
                                      simplify-clause-pot-lst
                                      rcnst gstack ttree)

; Var-list is a list of pot labels.  If we have not yet multiplied
; the polys corresponding to those labels, we do so and add them to the
; simplify-clause-pot-lst.  Products-already-tried is a list of the
; factors we have already tried, and pot-lst-to-look-in is the pot-lst
; from which we get our polys.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((null (cdr var-list))
     (mv step-limit nil simplify-clause-pot-lst products-already-tried))
    ((product-already-triedp var-list products-already-tried)
     (mv step-limit nil simplify-clause-pot-lst products-already-tried))
    ((or (too-many-polysp var-list pot-lst-to-look-in 1)
         (< 4 (length var-list)))


; If we went ahead and naively multiplied all the polys corresponding
; to the pot labels in var-list, we would get too many of them and
; be overwhelmed.  So, we will only multiply some of the polys.

     (sl-let
      (poly-list)
      (rewrite-entry
       (multiply-pots-super-filter var-list
                                   pot-lst-to-look-in)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (mv-let (contradictionp new-pot-lst)
              (add-polys poly-list
                         simplify-clause-pot-lst
                         (access rewrite-constant rcnst :pt)
                         (access rewrite-constant rcnst :nonlinearp)
                         type-alist
                         (access rewrite-constant rcnst
                                 :current-enabled-structure)
                         (ok-to-force rcnst)
                         wrld)
              (mv step-limit contradictionp new-pot-lst
                  (cons (sort-arith-term-order var-list)
                        products-already-tried)))))
    (t
     (sl-let
      (poly-list)
      (rewrite-entry
       (multiply-pots var-list
                      pot-lst-to-look-in)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       )
      (mv-let (contradictionp new-pot-lst)
              (add-polys poly-list
                         simplify-clause-pot-lst
                         (access rewrite-constant rcnst :pt)
                         (access rewrite-constant rcnst :nonlinearp)
                         type-alist
                         (access rewrite-constant rcnst
                                 :current-enabled-structure)
                         (ok-to-force rcnst)
                         wrld)
              (mv step-limit contradictionp new-pot-lst
                  (cons (sort-arith-term-order var-list)
                        products-already-tried))))))))

(defun deal-with-product1 (part-of-new-var var-list
                                           pot-lst-to-look-in
                                           pot-lst-to-step-down
                                           products-already-tried ; &extra formals
                                           rdepth step-limit
                                           type-alist obj geneqv pequiv-info
                                           wrld state fnstack
                                           ancestors backchain-limit
                                           simplify-clause-pot-lst
                                           rcnst gstack ttree)

; Pot-lst-to-look-in is the pot-lst we keep around to extract polys for
; multiplication from (see non-linear-arithmetic), and pot-lst-to-step-down
; is the pot-lst we cdr down as we recurse through this function.  They
; are initially the same.  Products-already-tried is an accumulator which
; keeps track of which pots we have already tried multiplying the polys from.

; We are here because we wish to find a set of polys to multiply together.
; Part-of-new-var is an ACL2-term and var-list is a list of pot-labels.
; If part-of-new-var is '1, we have found our set of polys, and we will
; proceed to multiply the polys corresponding to those pot-labels and add
; them to the simplify-clause-pot-lst.  Otherwise, we attempt to find
; some pot labels whose product will form part-of-new-var, adding them
; to var-list as we go.

; All the deal-with-xxx functions return four values: a new step-limit, the
; standard contradictionp, a potentially augmented pot-lst (or nil if
; contradictionp is true), and the accumulated list of products we have already
; tried.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((equal part-of-new-var *1*)
     (if (null (cdr var-list))
         (mv step-limit nil simplify-clause-pot-lst products-already-tried)
       (rewrite-entry
        (add-multiplied-polys var-list
                              products-already-tried
                              pot-lst-to-look-in)
        :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
        )))
    ((null pot-lst-to-step-down)
     (mv step-limit nil simplify-clause-pot-lst products-already-tried))
    (t

; Is the label of the pot we are standing on a factor of part-of-new-var?
; If so, we proceed in two ways --- try using the factor, and try without
; using the factor.

     (let ((new-part-of-new-var (part-of (access linear-pot
                                                 (car pot-lst-to-step-down)
                                                 :var)
                                         part-of-new-var)))
       (cond (new-part-of-new-var
              (sl-let
               (contradictionp new-pot-list products-already-tried)
               (rewrite-entry
                (deal-with-product1 new-part-of-new-var
                                    (cons (access linear-pot
                                                  (car pot-lst-to-step-down)
                                                  :var)
                                          var-list)
                                    pot-lst-to-look-in

; Once upon a time, we used (cdr pot-lst-to-step-down) below.  But
; that introduces an asymmetry in handling (* a a) v (* a a a a) when
; one is new and the other is old.  For example, if (* a a) is a new
; var and (* a a a a) is an old pot label, deal-with-factor would
; recognize that we could square the former.  But if (* a a a a) is
; the new var and (* a a) is the old one -- and we use (cdr
; pot-lst-to-step-down) below -- then deal-with-product would not find
; an opportunity to square (* a a).  In particular, it would recognize
; (* a a) as a part of (* a a a a) and generate the subgoal of finding
; polys about (* a a), but it would do so in a shorter pot list in
; which the pot containing (* a a) was now cdr'd past.

                                    pot-lst-to-look-in
                                    products-already-tried)
                :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
                )
               (cond (contradictionp (mv step-limit
                                         contradictionp
                                         nil
                                         products-already-tried))
                     (t
                      (rewrite-entry
                       (deal-with-product1 part-of-new-var
                                           var-list
                                           pot-lst-to-look-in
                                           (cdr pot-lst-to-step-down)
                                           products-already-tried)
                       :obj nil ; ignored
                       :geneqv nil ; ignored
                       :pequiv-info nil ; ignored
                       :ttree nil ; ignored
                       :simplify-clause-pot-lst new-pot-list)))))
             (t
              (rewrite-entry
               (deal-with-product1 part-of-new-var
                                   var-list
                                   pot-lst-to-look-in
                                   (cdr pot-lst-to-step-down)
                                   products-already-tried)
               :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
               ))))))))

(defun deal-with-product (new-var pot-lst-to-look-in
                                  pot-lst-to-step-down
                                  products-already-tried ; &extra formals
                                  rdepth step-limit
                                  type-alist obj geneqv pequiv-info wrld state
                                  fnstack ancestors backchain-limit
                                  simplify-clause-pot-lst
                                  rcnst gstack ttree)

; If new-var is a product, we try to find a set of pots whose labels,
; when multiplied together, form new-var.  If we are successful at
; gathering such a set of pot labels, we will multiply the polys in those
; pots and add them to the simplify-clause-pot-lst.

; All the deal-with-xxx functions return four values: a new step-limit, the
; standard contradictionp, a potentially augmented pot-lst (or nil if
; contradictionp is true), and the accumulated list of products we have already
; tried.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((eq (fn-symb new-var) 'BINARY-*)
     (rewrite-entry
      (deal-with-product1 new-var
                          nil
                          pot-lst-to-look-in
                          pot-lst-to-step-down
                          products-already-tried)
      :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
      ))
    (t
     (mv step-limit nil simplify-clause-pot-lst products-already-tried)))))

(defun deal-with-factor (new-var pot-lst-to-look-in
                                 pot-lst-to-step-down
                                 products-already-tried ; &extra formals
                                 rdepth step-limit
                                 type-alist obj geneqv pequiv-info
                                 wrld state
                                 fnstack ancestors backchain-limit
                                 simplify-clause-pot-lst
                                 rcnst gstack ttree)

; Pot-lst-to-look-in is the pot-lst we keep around to extract polys for
; multiplication from (see non-linear-arithmetic), and pot-lst-to-step-down
; is the pot-lst we cdr down as we recurse through this function.  They
; are initially the same.  Products-already-tried is an accumulator which
; keeps track of which pots we have already tried multiplying the polys from.

; In this function, we cdr down pot-lst-to-step-down to see whether
; new-var is a factor of any of its pot labels.  If so, we attempt to
; find a set of other pots (in pot-lst-to-look-in) whose labels are the
; remaining factors of the pot label found in pot-lst-to-step-down.
; If we are successful at gathering such a set of pot labels, we will
; multiply the polys in those pots and add them to the simplify-clause-pot-lst.

; All the deal-with-xxx functions return four values: a new step-limit, the
; standard contradictionp, a potentially augmented pot-lst (or nil if
; contradictionp is true), and the accumulated list of products we have already
; tried.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((null pot-lst-to-step-down)
     (mv step-limit nil simplify-clause-pot-lst products-already-tried))
    (t
     (let ((part-of-pot-var (part-of new-var
                                     (access linear-pot
                                             (car pot-lst-to-step-down)
                                             :var))))
       (cond ((and part-of-pot-var
                   (not (equal new-var
                               (access linear-pot
                                       (car pot-lst-to-step-down)
                                       :var))))
              (sl-let
               (contradictionp new-pot-list products-already-tried)
               (rewrite-entry
                (deal-with-product1 part-of-pot-var
                                    (list new-var)
                                    pot-lst-to-look-in
                                    pot-lst-to-look-in
                                    products-already-tried)
                :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
                )
               (cond (contradictionp (mv step-limit
                                         contradictionp
                                         nil
                                         products-already-tried))
                     (t
                      (rewrite-entry
                       (deal-with-factor new-var
                                         pot-lst-to-look-in
                                         (cdr pot-lst-to-step-down)
                                         products-already-tried)
                       :obj nil ; ignored
                       :geneqv nil ; ignored
                       :pequiv-info nil ; ignored
                       :ttree nil ; ignored
                       :simplify-clause-pot-lst new-pot-list)))))
             (t
              (rewrite-entry
               (deal-with-factor new-var
                                 pot-lst-to-look-in
                                 (cdr pot-lst-to-step-down)
                                 products-already-tried)
               :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
               ))))))))

(defun deal-with-division (new-var inverse-var
                                   pot-lst-to-look-in
                                   pot-lst-to-step-down
                                   products-already-tried ; &extra formals
                                   rdepth step-limit
                                   type-alist obj geneqv pequiv-info
                                   wrld state
                                   fnstack ancestors backchain-limit
                                   simplify-clause-pot-lst
                                   rcnst gstack ttree)

; Inverse-var is the multiplicative inverse of new-var,
; pot-lst-to-look-in is the pot-lst we keep around to extract polys
; for multiplication from (see non-linear-arithmetic), and
; pot-lst-to-step-down is the pot-lst we cdr down as we recurse
; through this function.  They are initially the same pot
; list.  Products-already-tried is an accumulator which keeps track of
; which pots we have already tried multiplying the polys from.

; Division can cause problems.  For a simple example, consider:
; p1: 0 < b
; p2: b < a
; and imagine we are trying to prove
; p: 1 < a/b.
; by adding its negation and looking for a contradiction.
; The presence of the /b in the pot will cause inverse-polys to give us
; p3: 0 < 1/b
; But deal-with-factors and deal-with-products will not have a poly
; ``about'' a to multiply p3 by, because a is not the heaviest term in
; any poly.  Rather, what we want to do is multiply p3 and p2 since
; b/b = 1.  (Note that before we invoke deal-with-division, we ensure
; that we have good bounds for b in the pot.  This ensures that b/b
; disappears without a case split.)

; Another example is that
; p1: 0 < a
; p2: a < b
; imply
; p: 1 < b/a.
; The last will be stored as
; p3: b/a <= 1.
; If we multiply p1 and p3 and cancel we get
; p4: 0 <= a - b
; or
; p4: b <= a
; which contradicts p2.

; So, what we do here is see if there is a pot whose label has inverse-var
; as a factor, and, if so, multiply two sets of polys and add the
; resultant polys to the pot-lst.  The two sets of polys we multiply are:
; (1) The bounds polys of new-var with the polys of the found pot, and
; (2) the polys of new-var with the bounds polys of the found pot.

; All the deal-with-xxx functions return four values: a new step-limit, the
; standard contradictionp, a potentially augmented pot-lst (or nil if
; contradictionp is true), and the accumulated list of products we have already
; tried.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond ((null pot-lst-to-step-down)
          (mv step-limit nil simplify-clause-pot-lst products-already-tried))
         (t

; The part-of expression asks the question, ``Is inverse-var a factor
; of the first pot label in pot-lst-to-step-down?''  It returns either
; nil, meaning no, or the naive result of dividing the pot label by
; inverse-var.

          (let ((part-of (part-of inverse-var (access linear-pot
                                                      (car pot-lst-to-step-down)
                                                      :var))))
            (cond (part-of
                   (sl-let
                    (contradictionp new-pot-lst products-already-tried)
                    (rewrite-entry
                     (add-multiplied-polys-filter
                      (list new-var
                            (access linear-pot
                                    (car pot-lst-to-step-down)
                                    :var))
                      products-already-tried
                      pot-lst-to-look-in)
                     :obj nil ; ignored
                     :geneqv nil ; ignored
                     :pequiv-info nil ; ignored
                     :ttree nil ; ignored
                     )
                    (cond (contradictionp
                           (mv step-limit contradictionp nil nil))
                          (t
                           (rewrite-entry
                            (deal-with-division new-var inverse-var
                                                pot-lst-to-look-in
                                                (cdr pot-lst-to-step-down)
                                                products-already-tried)
                            :obj nil ; ignored
                            :geneqv nil ; ignored
                            :pequiv-info nil ; ignored
                            :ttree nil ; ignored
                            :simplify-clause-pot-lst new-pot-lst)))))
                  (t
                   (rewrite-entry
                    (deal-with-division new-var inverse-var
                                        pot-lst-to-look-in
                                        (cdr pot-lst-to-step-down)
                                        products-already-tried)
                    :obj nil ; ignored
                    :geneqv nil ; ignored
                    :pequiv-info nil ; ignored
                    :ttree nil ; ignored
                    ))))))))

(defun non-linear-arithmetic1 (new-vars pot-lst ;;; to look-in/step-down
                                        products-already-tried ; &extra formals
                                        rdepth step-limit type-alist obj
                                        geneqv pequiv-info
                                        wrld state
                                        fnstack ancestors backchain-limit
                                        simplify-clause-pot-lst
                                        rcnst gstack ttree)

; This is the recursive version of function non-linear-arithmetic.  See the
; comments and documentation there.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((null new-vars)
     (mv step-limit nil simplify-clause-pot-lst))
    (t
     (let ((inverted-var (invert-var (car new-vars))))
       (sl-let
        (contradictionp new-pot-lst1 products-already-tried)

; Inverse-var is the multiplicative inverse of var.  Within deal-with-division
; we are going multiply var and inverse-var in order to cancel them with
; each other.  There are two cases in which this cancellation can occur:
; (1) We know that var and inverse-var are non-zero so their product is
; one.  (2) We know that var and inverse var are zero so their product is
; zero.  Good-bounds-in-pot determines this for us and allows us to avoid
; case-splits.

        (if (good-bounds-in-pot inverted-var
                                pot-lst
                                (access rewrite-constant rcnst :pt))
            (rewrite-entry
             (deal-with-division (car new-vars)
                                 inverted-var
                                 pot-lst ; to-look-in
                                 pot-lst ; to-step-down
                                 products-already-tried)
             :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
             )
          (mv step-limit nil simplify-clause-pot-lst products-already-tried))
        (cond (contradictionp (mv step-limit contradictionp nil))
              (t
               (sl-let (contradictionp new-pot-lst2 products-already-tried)
                       (rewrite-entry
                        (deal-with-product (car new-vars)
                                           pot-lst ; to-look-in
                                           pot-lst ; to-step-down
                                           products-already-tried)
                        :obj nil ; ignored
                        :geneqv nil ; ignored
                        :pequiv-info nil ; ignored
                        :ttree nil ; ignored
                        :simplify-clause-pot-lst new-pot-lst1)
                       (cond
                        (contradictionp (mv step-limit contradictionp nil))
                        (t
                         (sl-let
                          (contradictionp new-pot-lst3 products-already-tried)
                          (rewrite-entry
                           (deal-with-factor (car new-vars)
                                             pot-lst ; to-look-in
                                             pot-lst ; to-step-down
                                             products-already-tried)
                           :obj nil ; ignored
                           :geneqv nil ; ignored
                           :pequiv-info nil ; ignored
                           :ttree nil ; ignored
                           :simplify-clause-pot-lst new-pot-lst2)
                          (cond
                           (contradictionp (mv step-limit contradictionp nil))
                           (t
                            (rewrite-entry
                             (non-linear-arithmetic1
                              (cdr new-vars)
                              pot-lst ; to look-in/step-down
                              products-already-tried)
                             :obj nil ; ignored
                             :geneqv nil ; ignored
                             :pequiv-info nil ; ignored
                             :ttree nil ; ignored
                             :simplify-clause-pot-lst
                             new-pot-lst3)))))))))))))))

(defun non-linear-arithmetic (new-vars pot-lst ;;; to look-in/step-down
                                       products-already-tried ; &extra formals
                                       rdepth step-limit
                                       type-alist obj geneqv pequiv-info
                                       wrld state
                                       fnstack ancestors backchain-limit
                                       simplify-clause-pot-lst
                                       rcnst gstack ttree)

; New-vars is a list of pot labels or factors thereof.  We think of it
; as the labels of newly added pots, analogous to new-vars in
; add-polys-and-lemmas1.

; We cdr down the list of new-vars, calling the deal-with-xxx functions
; on the way.  The basic idea is that if a new var is a product and we have
; polys about both factors, then we can multiply those polys together to
; form polys about the new var.  We are thus using the lemma

; 0 < a & 0 < b -> 0 < a*b  (for rational a and b)

; We ``deal with'' new vars of the form a*b, a/b.  Analogously, if we
; have a new var of the form a we look to see whether we have an old
; pot about a*b and if so, look for a pot about b, etc.  That is, we try
; not to be sensitive to the order in which the pots a, b, and a*b are
; added.

; We do not handle terms like (* a (* a (* a a))) very well.  We
; anticipate that such terms will be normalized into expt expressions
; anyway.  So handling them here may not be too helpful.

; Unfortunately, we do not handle (expt a i) very well either.  We do
; know that (expt a -2) is the inverse of (expt a 2).  But we do not
; know that (expt a 2) is a*a or any of the analogous higher-order
; facts.  This is an obvious subject for future work.

; Note that we keep around the original pot-lst.  We have found this
; heuristic useful to prevent excessive effort on the part of
; non-linear arithmetic.  After running a large number of tests, we
; have found that the polys which we wished to multiply were almost
; always present in the original pot-lst and that much time can be
; saved this way.  Perhaps in a few more years when computers are even
; faster than they are now (2002) this should be revisited.

; Products-already-tried is an accumulator which keeps track of which pots
; we have already tried multiplying the polys from.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((null new-vars)
     (mv step-limit nil simplify-clause-pot-lst))
    (t
     (let ((gstack (push-gframe 'non-linear-arithmetic nil new-vars))
           (rdepth (adjust-rdepth rdepth)))
       (declare (type #.*fixnat-type* rdepth))
       (rewrite-entry
        (non-linear-arithmetic1 new-vars pot-lst products-already-tried)
        :obj    nil      ; ignored
        :geneqv nil      ; ignored
        :pequiv-info nil ; ignored
        :ttree  nil      ; ignored
        ))))))

(defun add-polys-and-lemmas2-nl (new-vars old-pot-lst ; &extra formals
                                          rdepth step-limit
                                          type-alist obj geneqv pequiv-info
                                          wrld state
                                          fnstack ancestors backchain-limit
                                          simplify-clause-pot-lst
                                          rcnst gstack ttree)

; In add-polys-and-lemmas1, it is said that:

; To the simplify-clause-pot-lst, we add lemmas for every var
; in new-vars, generating a new pot-lst.  Then if that new pot-lst has
; new vars in it (relative to old-pot-lst) we repeat for those vars.
; We return the standard contradictionp and a new pot-lst.

; This is analogous to add-polys-and-lemmas1, but we also add
; polys gleaned from other sources than add-linear-lemmas, namely
; from the type-alist and ``inverse'' polys (which picks up facts about
; division).

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((null new-vars)
     (let ((new-vars (expanded-new-vars-in-pot-lst simplify-clause-pot-lst
                                                   old-pot-lst)))
       (cond ((null new-vars)
              (mv step-limit nil simplify-clause-pot-lst))
             (t (rewrite-entry
                 (add-polys-and-lemmas2-nl new-vars
                                           simplify-clause-pot-lst)
                 :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
                 )))))
    (t
     (mv-let
      (contradictionp new-pot-lst)
      (add-polys-from-type-set (car new-vars)
                               simplify-clause-pot-lst
                               type-alist
                               (access rewrite-constant rcnst :pt)
                               (ok-to-force rcnst)
                               (access rewrite-constant rcnst
                                       :current-enabled-structure)
                               wrld)
      (cond
       (contradictionp (mv step-limit contradictionp nil))
       (t
        (sl-let
         (contradictionp new-pot-lst)
         (if (and (nvariablep (car new-vars))
                  (not (flambda-applicationp (car new-vars)))
                  (access rewrite-constant rcnst :heavy-linearp))
             (rewrite-entry
              (add-linear-lemmas (car new-vars)
                                 (getpropc (ffn-symb (car new-vars))
                                          'linear-lemmas nil wrld))
              :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
              :simplify-clause-pot-lst new-pot-lst)
           (mv step-limit nil new-pot-lst))
         (cond
          (contradictionp (mv step-limit contradictionp nil))
          (t
           (mv-let (contradictionp new-pot-lst)
                   (add-inverse-polys (car new-vars)
                                      type-alist wrld new-pot-lst
                                      (ok-to-force rcnst)
                                      (access rewrite-constant rcnst
                                              :current-enabled-structure)
                                      (access rewrite-constant rcnst :pt))
                   (cond (contradictionp (mv step-limit contradictionp nil))
                         (t (rewrite-entry
                             (add-polys-and-lemmas2-nl (cdr new-vars)
                                                       old-pot-lst)
                             :obj nil ; ignored
                             :geneqv nil ; ignored
                             :pequiv-info nil ; ignored
                             :ttree nil ; ignored
                             :simplify-clause-pot-lst new-pot-lst))))))))))))))

(defun add-polys-and-lemmas1-nl (old-pot-lst cnt ; &extra formals
                                             rdepth step-limit
                                             type-alist obj geneqv pequiv-info
                                             wrld state
                                             fnstack ancestors
                                             backchain-limit
                                             simplify-clause-pot-lst
                                             rcnst gstack ttree)

; When doing non-linear arithmetic, we use this function rather than
; the add-polys-and-lemmas1.  It is a wrapper for add-polys-and-lemmas2-nl
; which is similar in function to add-polys-and-lemmas1.

; We start by calling add-polys-and-lemmas2-nl with an expanded list of pot
; vars which are new to the simplify-clause-pot-lst (relative to old-pot-lst).
; Add-polys-and-lemmas2-nl augments simplify-clause-pot-lst, creating
; new-pot-lst1.

; We next call non-linear-arithmetic with a list of all the pot vars which are
; new to new-pot-lst1 (relative, again, to old-pot-lst).  Non-linear-arithmetic
; augments new-pot-lst1, creating new-pot-lst2.

; Finally, we recursively call ourselves, replacing the
; simplify-clause-pot-lst with new-pot-lst2 and old-pot-lst with new-pot-lst1.
; We thereby avoid calling add-polys-and-lemmas1 with any of the vars which
; it has already seen.

; When we recursively call ourselves we also increment the value of the
; variable cnt, and then check its value upon entry.  If it is greater than
; or equal to *non-linear-rounds-value*, we return rather than proceeding.
; This heuristic has proved an easy way to prevent excessive effort in
; non-linear arithmetic.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((<= *non-linear-rounds-value* cnt)
     (mv step-limit nil simplify-clause-pot-lst))
    (t

; Since we are doing non-linear arithmetic, we want to gather information not
; only on the new-vars, but also on the factors of any new-vars which are
; products.  Expanded-new-vars-in-pot-lst does this for us.  Note that the list
; of new-vars returned by expanded-new-vars-in-pot-lst may include variable
; symbols, unlike the list returned by new-vars-in-pot-lst with
; include-variableps = nil.

     (let ((new-vars (expanded-new-vars-in-pot-lst simplify-clause-pot-lst
                                                   old-pot-lst)))
       (sl-let
        (contradictionp new-pot-lst1)
        (cond
         ((null new-vars)
          (mv step-limit nil simplify-clause-pot-lst))

; We used to test for (null new-vars) in the outer cond, and simply return if
; it was true.  See also the comment following the call to new-vars-in-pot-lst
; below.

         (t

; This call to add-polys-and-lemmas2-nl is stronger than a corresponding call
; to add-polys-and-lemmas1, in the sense that it may add additional facts to
; simplify-clause-pot-lst.

          (rewrite-entry
           (add-polys-and-lemmas2-nl new-vars old-pot-lst)
           :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
           )))
        (cond
         (contradictionp (mv step-limit contradictionp nil))
         (t
          (let ((new-vars (new-vars-in-pot-lst new-pot-lst1 old-pot-lst t)))

; By using include-variableps = t in our call of new-vars-in-pot-lst, and
; moving the test above for (null new-vars) to its present location, we pick up
; theorems such as the following.

;    (include-book "arithmetic-3/bind-free/top" :dir :system)
;    (set-default-hints '((nonlinearp-default-hint stable-under-simplificationp
;                                                  hist pspv)))
;    (thm
;     (implies (and (rationalp a)
;                   (rationalp b)
;                   (rationalp c)
;                   (< 0 a)
;                   (< b 0)
;                   (< 0 (* a c))
;                   (< 0 (* b c)))
;              (equal c 0))
;     :hints (("Goal" :in-theory (disable |(< 0 (* x y))|))))

            (cond
             ((null new-vars)
              (mv step-limit nil new-pot-lst1))
             (t
              (sl-let (contradictionp new-pot-lst2)
                      (rewrite-entry
                       (non-linear-arithmetic new-vars new-pot-lst1 nil)
                       :obj nil ; ignored
                       :geneqv nil ; ignored
                       :pequiv-info nil ; ignored
                       :ttree nil ; ignored
                       :simplify-clause-pot-lst new-pot-lst1)
                      (cond
                       (contradictionp (mv step-limit contradictionp nil))
                       (t
                        (rewrite-entry
                         (add-polys-and-lemmas1-nl new-pot-lst1 (1+ cnt))
                         :obj nil ; ignored
                         :geneqv nil ; ignored
                         :pequiv-info nil ; ignored
                         :ttree nil ; ignored
                         :simplify-clause-pot-lst new-pot-lst2)))))))))))))))

(defun add-polys-and-lemmas1 (new-vars old-pot-lst ; &extra formals
                                       rdepth step-limit
                                       type-alist obj geneqv pequiv-info
                                       wrld state fnstack ancestors
                                       backchain-limit
                                       simplify-clause-pot-lst
                                       rcnst gstack ttree)

; To the simplify-clause-pot-lst, we add lemmas for every var
; in new-vars, generating a new pot-lst.  Then if that new pot-lst has
; new vars in it (relative to old-pot-lst) we repeat for those vars.
; We return the standard contradictionp and a new pot-lst.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (cond
    ((null new-vars)
     (let ((new-vars (new-vars-in-pot-lst simplify-clause-pot-lst
                                          old-pot-lst
                                          nil)))
       (cond ((null new-vars)
              (mv step-limit nil simplify-clause-pot-lst))
             (t (rewrite-entry
                 (add-polys-and-lemmas1 new-vars
                                        simplify-clause-pot-lst)
                 :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
                 )))))
    (t (sl-let
        (contradictionp new-pot-lst)
        (cond
         ((or (flambda-applicationp
               (car new-vars))
              (not (access rewrite-constant rcnst :heavy-linearp)))
          (mv step-limit nil simplify-clause-pot-lst))
         (t
          (rewrite-entry
           (add-linear-lemmas (car new-vars)
                              (getpropc
                               (ffn-symb (car new-vars))
                               'linear-lemmas nil wrld))
           :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
           )))
        (cond
         (contradictionp (mv step-limit contradictionp nil))
         (t (rewrite-entry
             (add-polys-and-lemmas1 (cdr new-vars)
                                    old-pot-lst)
             :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
             :simplify-clause-pot-lst new-pot-lst))))))))

(defun add-polys-and-lemmas (lst disjunctsp ; &extra formals
                                 rdepth step-limit
                                 type-alist obj geneqv pequiv-info wrld state
                                 fnstack ancestors
                                 backchain-limit
                                 simplify-clause-pot-lst rcnst gstack ttree)

; We add all the polys in lst to the simplify-clause-pot-lst
; and then add the lemmas triggered by all the new variables.

; We return two results: the standard contradictionp and a new pot-lst.

; Important Observation about Applicative Programming: In Nqthm, this
; function was called add-equations-to-pot-lst.  Isn't this a better
; name?  The advantage to rewriting a megabyte of code applicatively
; is that you get to think of better names for everything!

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (mv-let
    (contradictionp new-pot-lst)
    (add-polys lst simplify-clause-pot-lst
               (access rewrite-constant rcnst :pt)
               (access rewrite-constant rcnst :nonlinearp)
               type-alist
               (access rewrite-constant rcnst
                       :current-enabled-structure)
               (ok-to-force rcnst)
               wrld)
    (cond
     (contradictionp (mv step-limit contradictionp nil))

; The defthm below used to fail.  This failure was caused by our use of the
; test (and (access rewrite-constant rcnst :nonlinearp) (not disjunctsp)) to
; determine when to use nonlinear arithmetic.  This prevented the use of
; nonlinear arithmetic whenever there were disjunctive polys, but this was too
; restrictive.  We now use nonlinear arithmetic on disjunct polys that are
; derived from the goal, but not those that arise while backchaining.  Some
; type of limitation is needed as we have seen much thrashing in the arithmetic
; procedures when we were too liberal.  (Thanks to Robert Krug for providing
; this modification.)

;    ; This example was supplied by Julien Schmaltz.
;
;    (include-book "arithmetic-3/bind-free/top" :dir :system)
;    (include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
;    (set-non-linearp t)
;    (defthm foo
;      (implies (and (integerp a) (integerp b)
;                    (< 0 a) (< 0 b)
;                    (equal (len l) (* a b)))
;               (equal (floor (len l) a)
;                      b))
;      :hints (("GOAL"
;               :do-not '(eliminate-destructors generalize fertilize)
;               :do-not-induct t))
;      :rule-classes nil)

; We can get here by two routes.  We could have been called by
; add-terms-and-lemmas or add-disjunct-polys-and-lemmas.  In the
; latter case we are "speculatively" trying to get a contradiction
; from one disjunct so we can simplify things to the other disjunct.
; But non-linear is very expensive.  We choose not to try it in this
; "speculative" case during backchaining even if non-linear is
; otherwise enabled.

     ((and (access rewrite-constant rcnst :nonlinearp)
           (or (not disjunctsp)
               (null ancestors)))
      (rewrite-entry
       (add-polys-and-lemmas1-nl simplify-clause-pot-lst 0)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       :simplify-clause-pot-lst new-pot-lst))
     (t
      (rewrite-entry
       (add-polys-and-lemmas1 (new-vars-in-pot-lst new-pot-lst
                                                   simplify-clause-pot-lst
                                                   nil)
                              new-pot-lst)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       :simplify-clause-pot-lst new-pot-lst))))))

(defun add-disjunct-polys-and-lemmas (lst1 lst2 ; &extra formals
                                           rdepth step-limit
                                           type-alist obj geneqv pequiv-info
                                           wrld state
                                           fnstack ancestors
                                           backchain-limit
                                           simplify-clause-pot-lst
                                           rcnst gstack ttree)

; We try to construct a pot-lst from the simplify-clause-pot-lst
; by assuming the disjunction of the polys in lst1 and lst2.  But since
; pot lists can only represent conjunctions, we are forced to take a weak
; approach:  we can assume lst1 if the assumption of lst2 produces a
; contradiction and vice versa.  If both are contradictory, we return
; the standard contradiction result.  Otherwise we return a (possibly) new
; pot-lst.

; The hard part of this procedure is keeping track of dependencies.
; If lst1 is contradictory, we must infect lst2 with the ttree of the
; contradiction, since the assumption of lst2 is dependent upon the
; proof that lst1 is contradictory.  We must do the symmetric thing if
; lst2 proves to be contradictory.  But here we are in an efficiency
; bind.  We have already created the assumption of
; simplify-clause-pot-lst and lst1 and do not want to re-create it
; after infecting lst1 with the ttree from the refutation of lst2.  So
; we visit the modified pot-lst after the fact, if lst2 is contradictory,
; and add the appropriate ttree.

; Historical Note: In Nqthm we handled this problem by infecting the
; polys of lst1 with a special mark (a fresh cons) in the lemmas field
; of the poly before we added them to the pot-lst.  If lst2 gave a
; contradiction, we scanned the pot-lst produced by lst1 looking for
; all polys containing that (eq) cons.  During the initial attempts to
; code linear applicatively we tried to mimic this by using a 'mark
; tag in the tag-tree and inventing a "new" mark, such as an integer
; that was associated with the simplify-clause-pot-lst and was
; increased here when we obtained the mark.  We could not find a
; convincing way to generate a new mark.  The problem is due to the
; recursive rewriting done to add :LINEAR lemmas.  How do we know a
; mark generated now will still be new when it needs to be?  How do we
; know that a term rewritten in an extension of this pot-lst under us,
; doesn't have some marks in its tag-tree that will come back to haunt
; us?  These questions may have cut and dried answers that make marks
; viable.  But we decided not to pursue them and just identify the new
; polys as done here.  This exercise does point to the convenience of
; being able to use cons to generate a unique object.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (sl-let
    (contradictionp new-pot-lst1)
    (rewrite-entry
     (add-polys-and-lemmas lst1 t)
     :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
     )
    (cond
     (contradictionp

; So the first disjunct, lst1, has led to a contradiction.  We will
; infect the polys in lst2 with the ttree of that contradiction and
; and add them to the original pot list.

      (rewrite-entry
       (add-polys-and-lemmas (infect-polys lst2
                                           (access poly contradictionp
                                                   :ttree)
                                           (collect-parents
                                            (access poly contradictionp
                                                    :ttree)))
                             t)
       :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
       ))
     (t

; The first disjunct did not lead to a contradiction.  Perhaps the
; second one will...

      (sl-let
       (contradictionp new-pot-lst2)
       (rewrite-entry
        (add-polys-and-lemmas lst2 t)
        :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
        )
       (declare (ignore new-pot-lst2))
       (cond (contradictionp

; So the second disjunct, lst2, has led to a contradiction and we may
; use new-pot-lst1, the result of assuming lst1, as the result of
; assuming their disjunction.  But we must infect, with the ttree from
; the contradiction, all the polys in new-pot-lst1 derived from lst1.
; That set is just all the polys in new-pot-lst1 that are not in
; simplify-clause-pot-lst.

              (mv step-limit
                  nil
                  (infect-new-polys
                   new-pot-lst1
                   simplify-clause-pot-lst
                   (access poly contradictionp :ttree))))
             (t (mv step-limit nil simplify-clause-pot-lst)))))))))

(defun add-disjuncts-polys-and-lemmas (split-lst to-do-later
                                                 pot-lst0 ; &extra formals
                                                 rdepth step-limit
                                                 type-alist obj
                                                 geneqv pequiv-info wrld state
                                                 fnstack ancestors
                                                 backchain-limit
                                                 simplify-clause-pot-lst
                                                 rcnst gstack ttree)

; Each element of split-lst is a doublet, (lst1 lst2).  Logically, we wish to
; conjoin to the simplify-clause-pot-lst the conjunction across split-lst of
; the disjunctions of each lst1 and lst2.  I.e., we wish to assume (and ... (or
; lst1 lst2) ...) and we wish to express this assumption as a pot-lst.  No way
; Jose.  Pot-lsts represent conjunctions of assumptions.  So instead we'll
; conjoin lst1 into the pot list and lst2 into the pot list and hope one or the
; other gives a contradiction.  If not, we'll just discard that doublet and try
; the others.  But if one gives a contradiction, then we can go with the
; assumption of the other as the assumption of their disjunction.  There is a
; subtlety here however: the assumption of lst2 in place of (or lst1 lst2)
; depends upon the refutation of lst1 and hence we must infect the polys from
; lst2 with the ttree arising from the refutation of lst1.  And vice versa.
; See add-disjunct-polys-and-lemma.

; We return (mv sl contradictionp pot-lst changedp), where sl is the new
; step-limit, and contradictionp and pot-lst are the standard contradictionp
; and a new pot-lst.  When contradictionp is nil then, normally, changedp is t
; if and only if the input and output pot-lst differ; however, we do not insist
; on this, as changedp is to be used only heuristically.

; The to-do-later list was first present in Version 1.6, and represents an
; attempt to make the order of the split-lst irrelevant.  The idea is that if a
; doublet in the split-lst must be "discarded" as noted above, then we actually
; save that doublet on to-do-later and try it again after processing the
; others.  Here is a long message that explains the problem; the message was
; sent to Bishop Brock, who first reported the problem, on March 31, 1994,

; I have fixed the "bug" that prevented us from proving

; (thm
;  (IMPLIES
;   (AND (INTEGERP N)
;        (NOT (< N 0))
;        (NOT (< 4 N))
;        (NOT (EQUAL N 2))
;        (NOT (EQUAL N 0))
;        (NOT (EQUAL N 1))
;        (NOT (EQUAL N 3)))
;   (EQUAL N 4)))

; To understand what I did, consider a proof that works, e.g.,
;  (IMPLIES (AND (INTEGERP N)
;              (NOT (< N 0))
;              (NOT (< 4 N))
;              (NOT (EQUAL N 0))
;              (NOT (EQUAL N 1))
;              (NOT (EQUAL N 2))
;              (NOT (EQUAL N 3)))
;         (EQUAL N 4))

; The arithmetic hyps are stored in the linear inequalities database by the
; linear arithmetic package.  That database represents a conjunction of
; inequalities.  The first two inequalities give us

;  0 <= N <= 4

; Now we come to the hard part.  In general, we cannot represent (NOT (EQUAL x
; y)) as a conjunction of inequalities.  It turns into a DISjunction, namely,
; either x < y or y < x.  Thus, if we are asked to add (NOT (EQUAL x y)) to the
; linear database we try adding x < y.  If that gives us a contradiction, then
; we know y < x and we add that.  Alternatively, if x < y doesn't give us a
; contradiction, but y < x does, we can assume x < y.  If neither gives us a
; contradiction, we simply can't represent (NOT (EQUAL x y)) in the linear
; database.  Note that to get any linear information out of (NOT (EQUAL x y))
; we must get a contradiction from one of the two disjuncts.

; When you process the hypotheses in the "wrong" order, you don't always get a
; contradiction and so we effectively drop one or more of the inequalities and
; lose.

; Consider one of the many "right" orders first, in particular the proof that
; works above.  The first NOT EQUAL we process is (NOT (EQUAL N 0)).  Because N
; is an integer, this is equivalent to either N <= -1 or 1 <= N.  The linear
; database we have initially is

;  0 <= N <= 4.

; When we add N <= -1 we get a contradiction, by clashing 0 <= N with N <= -1
; and deriving 0 <= -1.  Since we got a contradiction on one disjunct we can
; assume the other.  Adding 1 <= N to the above database gives us

;  1 <= N <= 4.

; Note that we are now in a position to successfully process (NOT (EQUAL N 1)),
; because it becomes either N <= 0 (contradiction) or 2 <= N, and thus we get

;  2 <= N <= 4.

; As you can see, we can keep narrowing the known interval as long as the hyp
; we process is beyond the current known endpoints.  We can work at either
; endpoint and so there are many "right" orders.  (In the case of the 5-way
; case split on N=0,1,2,3,4, there are 90 right orders and 30 wrong ones out of
; the 120 permutations.)

; Now consider one of the "wrong" orders.  If we know

;  0 <= N <= 4

; and we first process (NOT (EQUAL N 1)) then we must get a contradiction from
; either N <= 0 or from 2 <f= N.  But neither of these is contradictory yet.
; So in Version 1.5 (and Nqthm!) we just ignore that NOT EQUAL hyp (as far as
; linear arithmetic is concerned).  Once we've ignored any one hyp, the game is
; lost.

; In Version 1.6 the success of linear is independent of the order in which the
; inequalities are presented.  I do this by keeping a list of the ones I had
; tried to add but couldn't, i.e., the ones that Version 1.5 decided to ignore.
; Call that list the "to-do-later list".  I process all the hyps and get a
; database and a to-do-later list.  Then I reprocess the to-do-later list and
; see if any can be added now.  I iterate until either I've added them all or
; no changes happen.

; In the case of inequalities about variable symbols this is very very fast.
; In the case of inequalities about arbitrary terms, e.g., (NOT (EQUAL (FOO
; (BAR X Y)) 2)), it can be slow because every time we add an inequality we go
; look in the :LINEAR lemmas database for more facts about that term.  But I
; think this problem doesn't arise too often and I think we'll find Version 1.6
; better than Version 1.5 and seldom any slower.

; Thank you very much Bishop for noticing this problem.  It is amazing to me
; that it survived all those years in Nqthm without coming to our attention.

  (declare (ignore obj geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((null split-lst)
     (let ((eqp (equal pot-lst0 simplify-clause-pot-lst)))
       (cond
        ((or eqp
             (null to-do-later))
         (mv step-limit nil simplify-clause-pot-lst (not eqp)))
        (t (sl-let
            (contradictionp pot-lst changedp)
            (rewrite-entry
             (add-disjuncts-polys-and-lemmas to-do-later nil
                                             simplify-clause-pot-lst)
             :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored)
             )
            (declare (ignore changedp))
            (mv step-limit contradictionp pot-lst t))))))
    (t (sl-let (contradictionp new-pot-lst)
               (rewrite-entry
                (add-disjunct-polys-and-lemmas (car (car split-lst))
                                               (cadr (car split-lst)))
                :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
                )
               (cond (contradictionp (mv step-limit contradictionp nil nil))
                     (t (rewrite-entry
                         (add-disjuncts-polys-and-lemmas
                          (cdr split-lst)
                          (if (equal new-pot-lst simplify-clause-pot-lst)
                              (cons (car split-lst) to-do-later)
                            to-do-later)
                          pot-lst0)
                         :obj nil          ; ignored
                         :geneqv nil       ; ignored
                         :pequiv-info nil  ; ignored
                         :ttree nil        ; ignored
                         :simplify-clause-pot-lst new-pot-lst))))))))

(defun add-terms-and-lemmas (term-lst ttrees positivep
                                      ; &extra formals
                                      rdepth step-limit
                                      type-alist obj geneqv pequiv-info
                                      wrld state
                                      fnstack ancestors
                                      backchain-limit
                                      simplify-clause-pot-lst
                                      rcnst gstack ttree)

; Term-lst is a list of terms to be assumed true (if positivep) or false (if
; not positivep).  We linearize each term in term-lst and add the resulting
; polys and all lemmas we can to simplify-clause-pot-lst.  When we linearize a
; term we use the weakly corresponding element of ttrees as its tag-tree (if
; that element is non-nil).

; Only variables introduced by the addition of the new polys are considered
; new.

; This function returns 3 values.  The first is the new step-limit.  The second
; indicates that a linear contradiction arises from the assumption of term-lst
; as above.  When non-nil the second result is the impossible-poly generated.
; Its tag-tree contains all the necessary information.  In particular, if a
; contradiction is indicated then there is a proof of NIL from type-alist, the
; assumption of the terms in term-lst (as per positivep), the assumptions in
; the final tag-tree and some subset of the polys in the
; simplify-clause-pot-lst.

; If no contradiction is indicated then the third value is the new
; simplify-clause-pot-lst.  For each poly p in the new pot list there is a
; proof of p from type-alist, the assumption of the terms in term-lst (as per
; positivep) and the polys in the original pot list.

; Note that obj has an special use in this function.  Values t and nil for obj
; indicate, as usual, that we are in the process of trying to prove or falsify
; (respectively) the given terms; however, this function does not use obj for
; that purpose. (That said, obj is used in reports issued by cw-gframe and
; dmr-interp.)  The value '?, however, is a special mark that is used when
; setting up the pot-lst for a clause.  The desperation heuristic noted below,
; of making a second attempt to use linear lemmas after successfully using at
; least one disjunctive inequality, is invoked only when setting up the pot-lst
; (obj = '?).  We found it much too expensive in some cases without this
; restriction, as discussed in a comment in (deflabel note-8-4 ...) in the
; source documentation (see books/system/doc/acl2-doc.lisp).

  (declare (ignore geneqv pequiv-info ttree)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   3
   #.*fixnum-type*
   (let ((gstack (push-gframe 'add-terms-and-lemmas nil term-lst obj))
         (rdepth (adjust-rdepth rdepth)))
     (declare (type #.*fixnat-type* rdepth))
     (sl-let
      (term-lst ttree-lst)
      (if (and (access rewrite-constant rcnst :nonlinearp)
               (access rewrite-constant rcnst :heavy-linearp))

; This call to rewrite-linear-term-lst is new to Version_2.7.
; We wish to be able to have a different normal form when doing
; linear and non-linear arithmetic than when doing normal rewriting.
; The terms in term-lst eventually get passed on to rewrite-linear-term
; where they are rewritten under a possibly changed current-enabled-structure.
; See the comments in cleanse-type-alist for a couple of oddities
; associated with this.

          (rewrite-entry
           (rewrite-linear-term-lst term-lst ttrees)
           :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
           )
        (mv step-limit term-lst ttrees))

; Back to the original show.

      (mv-let (poly-lst split-lst)
        (linearize-lst term-lst ttree-lst positivep
                       type-alist
                       (access rewrite-constant rcnst
                               :current-enabled-structure)
                       (ok-to-force rcnst)
                       wrld
                       state)
        (sl-let
         (contradictionp basic-pot-lst)
         (rewrite-entry
          (add-polys-and-lemmas poly-lst nil)
          :obj nil                ; ignored
          :geneqv nil             ; ignored
          :pequiv-info nil        ; ignored
          :ttree nil              ; ignored
          )
         (cond
          (contradictionp (mv step-limit contradictionp nil))
          (t
           (sl-let
            (contradictionp new-pot-lst changedp)
            (rewrite-entry
             (add-disjuncts-polys-and-lemmas
              split-lst
              nil
              basic-pot-lst)
             :obj nil                         ; ignored
             :geneqv nil                      ; ignored
             :pequiv-info nil                 ; ignored
             :ttree nil                       ; ignored
             :simplify-clause-pot-lst
             basic-pot-lst)
            (cond
             (contradictionp
              (mv step-limit contradictionp nil))
             ((and changedp
                   (eq obj '?) ; special mark for setting up the pot-lst

; The following test is what we use to enable so-called "desperation
; heuristics".

                   (eq (access rewrite-constant rcnst :rewriter-state)
                       'settled-down))
              (rewrite-entry

; We have seen an example where a proof fails unless we make one more pass at
; using linear lemmas after improving the pot-lst with
; add-disjuncts-polys-and-lemmas.  That same example fails when, instead of
; adding this call of add-polys-and-lemmas1 at the end, we add a call of
; add-disjuncts-polys-and-lemmas before the earlier call of
; add-polys-and-lemmas.

               (add-polys-and-lemmas1
                (new-vars-in-pot-lst new-pot-lst nil nil)
                new-pot-lst)
               :obj nil :geneqv nil :pequiv-info nil :ttree nil ; all ignored
               :simplify-clause-pot-lst new-pot-lst))
             (t (mv step-limit nil new-pot-lst))))))))))))

(defun rewrite-with-linear (term ; &extra formals
                            rdepth step-limit
                            type-alist obj geneqv pequiv-info wrld state
                            fnstack ancestors backchain-limit
                            simplify-clause-pot-lst rcnst gstack ttree)

; If term is an (in)equality, and obj is either 'T or 'NIL, we try
; to rewrite term using the arithmetic package.  If obj is 'T, we
; add the negation of term and hope for a contradictionp;
; otherwise we add term.  We thus pass (eq obj nil) for the
; positivep flag to add-terms-and-lemmas and thence linearize.

; We return 3 values, whether we rewrote term, the (possibly) new term,
; and the (possibly) new ttree.  If we rewrote term using the linear
; package we add the *fake-rune-for-linear* to the ttree.

; Historical Plaque from Nqthm:

;    We tried rewriting with linear under the objective ?, and it cost
;    us 4 million conses over a proveall, so we stopped rewriting with
;    linear under the objective ?.  We found that too restrictive, and
;    experimented with the idea of only rewriting with linear under ?
;    when ANCESTORS is nonNIL, i.e., when we are working on a term
;    that may appear as part of the simplification of the theorem as
;    opposed to a term that appears while rewriting the hypothesis of
;    a :REWRITE rule.  That cost us 5 times more conses on the theorem
;    it was designed to prove!  So we have abandoned linear under ?
;    altogether, again.  Here, however is the most recent experimental
;    code:

;    (COND ((AND (NULL ANCESTORS)
;                (EQ (ADD-TERM-TO-POT-LST TERM
;                                         SIMPLIFY-CLAUSE-POT-LST NIL NIL)
;                    (QUOTE CONTRADICTION)))
;           (SETQ ANS TRUE)
;           (GO WIN)))

;    (COND ((AND (NULL ANCESTORS)
;                (EQ (ADD-TERM-TO-POT-LST TERM SIMPLIFY-CLAUSE-POT-LST T NIL)
;                    (QUOTE CONTRADICTION)))
;           (SETQ ANS FALSE)
;           (GO WIN)))

; On a somewhat related note, we have briefly considered the possibility of
; supporting some weak kind of forward chaining when we enter the true and
; false branches of an IF, generalizing what we support with compound
; recognizer rules.

; (implies (unsigned-byte-p 4 x)
;          (< x 16))

; We have come up with at least the following reasons not to provide such
; support.

; - To take full advantage of such a rule we'd need assume-true-false to extend
;   the linear pot, which would likely be expensive, as discussed above.

; - IF calls generally work their way up to top-level case splits anyhow, with
;   two exceptions: backchaining and the tentative opening of recursive
;   functions.  Such a rule would only provide marginal help for these cases.
;   Note that recursive function calls can be forced open anyhow, using :expand
;   hints.

  (declare (ignore geneqv pequiv-info)
           (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))

; Convention: It is our convention to pass nils into ignored &extra formals.
; Do not change the (ignore ...) declaration above without looking at the
; callers.  That is, if you change this function so that it uses the formals
; declared ignored above, you are making a mistake because all callers of this
; function pass nils into them.

  (the-mv
   4
   #.*fixnum-type*
   (let ((positivep (eq obj nil)))
     (cond
      ((and (not (eq obj '?))
            (mv-let (not-flg atm)
                    (strip-not term)
                    (declare (ignore not-flg))
                    (or (equalityp atm)
                        (inequalityp atm))))
       (sl-let (contradictionp irrelevant-pot-lst)
               (rewrite-entry (add-terms-and-lemmas (list term)
                                                    nil ; pts
                                                    positivep)
                              :geneqv nil ; ignored
                              :pequiv-info nil ; ignored
                              :ttree nil ; ignored
                              )
               (declare (ignore irrelevant-pot-lst))
               (cond (contradictionp
                      (mv step-limit
                          t
                          (if positivep
                              *nil*
                            *t*)
                          (push-lemma
                           *fake-rune-for-linear*
                           (cons-tag-trees-rw-cache
                            (access poly contradictionp :ttree)
                            ttree))))
                     (t (mv step-limit nil term ttree)))))
      (t
       (mv step-limit nil term ttree))))))

(defun rewrite-quoted-constant-with-lemma
  (term lemma ; &extra formals
        rdepth step-limit
        type-alist obj geneqv pequiv-info wrld state
        fnstack ancestors
        backchain-limit
        simplify-clause-pot-lst rcnst gstack
        ttree)

; The structure of this function and its immediate,
; rewrite-quoted-constant-with-lemmas, is based on rewrite-with-lemma and
; rewrite-with-lemmas.  Term is a quoted evg, i.e., 'evg, and lemma is an
; enabled :rewrite-quoted-constant rule whose :heuristic-info field contains (n
; . loop-stopper), where n is the form number as per the Essay on Rewriting
; Quoted Constants:

; [1] (IMPLIES hyps (equiv 'lhs-evg 'rhs-evg))
; [2] (IMPLIES hyps (equiv (fn x) x)), where x is a variable.
; [3] (IMPLIES hyps (equiv lhs-term rhs-term))

; In all cases below, we check that equiv is a refinement of geneqv.  Roughly
; speaking, if n is 1 and evg is lhs-evg, we backchain to establish the hyps
; and if successful replace term by 'rhs-evg.  If n is 2 and backchaining
; succeeds and (fn 'evg) returns a non-erroneous result, we replace term with
; the quoted result.  If n is 3, we unify lhs-term with 'evg and if successful
; backchain and rewrite as with an ordinary rewrite rule.

; The four values returned by this function are: a new step-limit, t or nil
; indicating whether lemma was used to rewrite term, the rewritten version of
; term, and the final version of ttree.

; This function is a No-Change Loser modulo rw-cache: only the values of
; 'rw-cache-any-tag and 'rw-cache-nil-tag may differ between the input and
; output ttrees.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   4
   #.*fixnum-type*
   (let* ((gstack (push-gframe 'rewrite-quoted-constant-with-lemma nil term lemma
                               geneqv))
          (rdepth (adjust-rdepth rdepth))
          (temp (access rewrite-rule lemma :heuristic-info))
          (n (car temp))
          (loop-stopper (cdr temp)))
     (declare (type #.*fixnat-type* rdepth)
              (type integer n))
     (cond ((zero-depthp rdepth)
            (rdepth-error
             (mv step-limit nil term ttree)))
           ((not (geneqv-refinementp (access rewrite-rule lemma :equiv)
                                     geneqv
                                     wrld))
            (mv step-limit nil term ttree))
           (t
; Note below we swap the lhs and rhs of form [2] rules!  The rule is written
; and stored as (equiv (fn var) var), but actually used as though it were
; (equiv var (fn var)), so in this code we actually let lhs be the var and rhs
; be the normalizer expression.

            (let ((lhs (if (eql n 2)
                           (access rewrite-rule lemma :rhs)
                           (access rewrite-rule lemma :lhs)))
                  (rhs (if (eql n 2)
                           (access rewrite-rule lemma :lhs)
                           (access rewrite-rule lemma :rhs)))
                  (rune (access rewrite-rule lemma :rune)))
              (mv-let (unify-ans unify-subst)
                (cond
                 ((eql n 1)
                  (mv (equal term lhs) nil))
                 ((eql n 2)
                  (mv t (list (cons lhs term))))
                 ((eql n 3)
                  (one-way-unify-restrictions
                   lhs
                   term
                   (cdr (assoc-equal
                         rune
                         (access rewrite-constant rcnst
                                 :restrictions-alist)))))
                 (t (mv nil
                        (er hard 'rewrite-quoted-constant-with-lemma
                            "We've encountered a :rewrite-quoted-constant ~
                             rule, namely ~x0, with an unrecognized form ~
                             number, ~x1."
                            rune
                            n))))
                (cond
                 ((and unify-ans
                       (null (brkpt1 lemma term unify-subst
                                     type-alist geneqv ancestors
                                     ttree
                                     gstack rcnst simplify-clause-pot-lst
                                     state)))
                  (cond
                   ((null (loop-stopperp loop-stopper unify-subst wrld))
                    (prog2$
                     (brkpt2 nil 'loop-stopper
                             unify-subst gstack nil nil
                             rcnst ancestors state)
                     (mv step-limit nil term ttree)))
                   (t
                    (with-accumulated-persistence
                     rune
                     ((the #.*fixnum-type* step-limit) flg term ttree)
                     flg
                     (sl-let
                      (relieve-hyps-ans failure-reason unify-subst ttree)
                      (rewrite-entry
                       (relieve-hyps
                        rune
                        term
                        (access rewrite-rule lemma :hyps)
                        (access rewrite-rule lemma
                                :backchain-limit-lst)
                        unify-subst
                        (not (oncep (access rewrite-constant
                                            rcnst
                                            :oncep-override)
                                    (access rewrite-rule
                                            lemma
                                            :match-free)
                                    rune
                                    (access rewrite-rule
                                            lemma
                                            :nume))))
                       :obj nil         ; ignored
                       :geneqv nil      ; ignored
                       :pequiv-info nil ; ignored
                       )
                      (cond
                       (relieve-hyps-ans
                        (sl-let
                         (rewritten-rhs ttree)
                         (with-accumulated-persistence
                          rune
                          ((the #.*fixnum-type* step-limit)
                           rewritten-rhs ttree)

; This rewrite of the body is considered a success unless the parent with-acc-p
; fails.

                          t
                          (rewrite-entry
                           (rewrite
                            rhs
                            unify-subst
                            'rhs))
                          :conc
                          (access rewrite-rule lemma :hyps))
                         (cond
                          ((or (eql n 1)
                               (and (eql n 2)
                                    (quotep rewritten-rhs)
                                    (not (equal term rewritten-rhs)))
                               (eql n 3))
                           (prog2$
                            (brkpt2 t nil unify-subst gstack rewritten-rhs
                                    ttree rcnst ancestors state)
                            (mv step-limit
                                t
                                rewritten-rhs
                                (push-lemma
                                 (geneqv-refinementp
                                  (access rewrite-rule lemma
                                          :equiv)
                                  geneqv
                                  wrld)
                                 (push-lemma+ rune ttree rcnst ancestors
                                              rhs
                                              rewritten-rhs)))))
                          (t (prog2$
; We can only get here if n is 2 but either rewritten-rhs is not a quote or
; it is equal to term.
                              (brkpt2 nil
                                      (list
                                       (if (quotep rewritten-rhs)
                                           'normalizer-returned-same-constant
                                           'normalizer-failed-to-evaluate)
                                       (sublis-var unify-subst rhs)
                                       rewritten-rhs)
                                      unify-subst gstack nil nil
                                      rcnst ancestors state)
                              (mv step-limit nil term ttree))))))
                       (t (prog2$
                           (brkpt2 nil failure-reason
                                   unify-subst gstack nil nil
                                   rcnst ancestors state)
                           (mv step-limit nil term ttree)))))))))
                 (t (mv step-limit nil term ttree))))))))))

(defun rewrite-quoted-constant-with-lemmas
  (term lemmas ; &extra formals
        rdepth step-limit
        type-alist obj geneqv pequiv-info wrld state
        fnstack ancestors backchain-limit
        simplify-clause-pot-lst rcnst gstack ttree)
; Term is a quoted evg.
  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit))
  (the-mv
   4
   #.*fixnum-type*
   (cond
    ((null lemmas) (mv step-limit nil term ttree))
    ((not (enabled-numep
           (access rewrite-rule (car lemmas) :nume)
           (access rewrite-constant rcnst
                   :current-enabled-structure)))
     (rewrite-entry
      (rewrite-quoted-constant-with-lemmas term (cdr lemmas))))
    (t (sl-let
        (rewrittenp rewritten-term ttree)
        (rewrite-entry (rewrite-quoted-constant-with-lemma term (car lemmas)))
        (cond
         (rewrittenp
          (mv step-limit t rewritten-term ttree))
         (t (rewrite-entry
             (rewrite-quoted-constant-with-lemmas term (cdr lemmas))))))))))

(defun rewrite-quoted-constant (term ; &extra formals
                                rdepth step-limit
                                type-alist obj geneqv pequiv-info wrld state
                                fnstack ancestors backchain-limit
                                simplify-clause-pot-lst rcnst gstack ttree)

  (sl-let (rewrittenp rewritten-term ttree1)
          (rewrite-entry
           (rewrite-quoted-constant-with-lemmas
            term
            (global-val 'rewrite-quoted-constant-rules wrld)))
          (cond
           (rewrittenp
            (mv step-limit rewritten-term ttree1))
           ((fn-slot-from-geneqvp geneqv)
            (sl-let
             (evg1 ttree1)
             (rewrite-entry
              (rewrite-lambda-object (unquote term)))

; Rewrite-lambda-object is insensitive to the incoming ttree.  So ttree1
; does not include that tree and if we use evg1 above we have to cons
; ttree1 onto the existing ttree.

             (cond ((equal evg1 (unquote term))
                    (mv step-limit term ttree))
                   (t (mv step-limit
                          (kwote evg1)
                          (cons-tag-trees ttree1 ttree))))))
           (t (mv step-limit term ttree)))))

(defun rewrite-lambda-object (evg ; &extra formals
                              rdepth step-limit
                              type-alist obj geneqv pequiv-info wrld state
                              fnstack ancestors backchain-limit
                              simplify-clause-pot-lst rcnst gstack ttree)

; Evg is some evg and rewrite has been called on 'evg.  Furthermore, we know
; from geneqv that 'evg is in a :FN slot.  If evg is in fact a well-formed
; lambda object and all the user defined functions in it have had warrants
; issued (whether they're in the type-alist or not) we attempt to ``rewrite''
; its body, in a context-free way, carrying in no external assumptions other
; than warrants and expanding no recursive functions in it.

; Actually, we carry in all 0-ary entries in the type-alist.

; Actually, the user can select three different senses of ``rewrite'' behavior
; by appropriately specifying the enabled status of two runes,
; (:executable-counterpart rewrite-lambda-modep) and (:definition
; rewrite-lambda-modep), which we abbreviate below as runes e and d
; respectively.

; ``Rewrite'' Action Desired                      Rune Status

; full-blown rewriting                        e and d both enabled
; just syntactic cleaning up                  e enabled and d disabled
; hands off (i.e., modifying lambda objects)  e disabled

; Both full-blown rewriting and syntactic cleaning effectively force
; needed warrants.  (Actually, cleaning forces the warrants of all user fns
; in the body that aren't assumed true in type-alist.  And if some such warrant
; is assumed false, no cleaning is done.)

; The restriction that we expand no recursive functions is accomplished by
; pushing :rewrite-lambda-object on the fnstack, which signals rewrite-fncall
; not to open any recursive function.  See the explanation of a simplify loop
; below.)

; If the rewritten body is different, contains no free variables and is tame,
; we return a new lambda object with the rewritten body and appropriately
; forced warrants.  Coincidentally, we drop the optional DECLARE form permitted
; in lambda objects; we take no special action to eliminate RETURN-LAST because
; there is an abbreviation-style rewrite rule that will do that.  We nilify the
; last two arguments of DO$ with a special clause inside the rewriter itself.
; But if evg is not well-formed or its rewritten body is equal to the original
; body (and there is no DECLARE form) or it contains free variables, or it is
; not tame, we return evg unchanged.  In the case that a well-formed lambda
; object is rewritten but the rewritten body is rejected on any grounds, we
; print a "rewrite-lambda-object" warning, which can be inhibited if it gets
; annoying.  To inhibit the warning but leave all other warnings on, do
; (set-inhibit-warnings "rewrite-lambda-object").

; Explanation of an infinite simplify loop:

; Prior to using the :rewrite-lambda-object fnstack marker to shut off the
; expansion of recursive functions in rewrite-lambda-object we rewrote the body
; using the pre-existing fnstack.  This caused an infinite loop in the presence
; of loop$-recursive functions, at least in those whose only recursions were
; within loop$ although we didn't look for other infinite loops.  The simplest
; example involves the nonsensical defun and non-theorem below:

; (defun foo (x)
;   (declare (xargs :loop$-recursion t :measure (acl2-count x)))
;   (loop$ for e in x collect (foo e)))

; (thm (foo x))

; Goal (foo x) simplifies to Goal' (collect$ (lambda$ (iv)(foo iv)) x). But
; then the lambda object is rewritten with fnstack nil (because we're in a
; top-level goal) to produce Goal'' (collect$ (lambda$ (iv) (collect$ (lambda$
; (iv) (foo iv)) iv)) x), etc.

; To solve this we adopted the most radical solution: never open a recursive
; function while rewriting a lambda object.  This is accomplished in
; rewrite-fncall, by checking to see whether :rewrite-lambda-object is an
; element of the fnstack.  Less radical would be the idea of rewriting the call
; and deciding whether to keep it.  But since lambda bodies are simplified
; without any of the external context in which the lambda object occurs, the
; context of the call never changes.  So one has to ask why didn't the user
; just write what the recursive function would simplify to?  We may eventually
; see why a more sophisticated solution is needed.  But as a first cut we just
; don't open recursive functions in lambda bodies.

  (declare (type #.*fixnat-type* rdepth)
           (type #.*fixnum-type* step-limit)
           (ignore obj geneqv pequiv-info
                   ancestors simplify-clause-pot-lst))

  (the-mv
   3
   #.*fixnum-type*
   (cond ((or (symbolp evg)

; We don't mess with evg if it is a symbol.  If we did, it would fail the first
; test below and report that the symbol was an ill-formed lambda object.  If
; the user wants to rewrite a quoted symbol occurring in a :FN position that is
; possible but he or she should prove a :rewrite-quoted-constant rule.

              (not (enabled-numep *rewrite-lambda-modep-xnume*
                                  (access rewrite-constant
                                          rcnst
                                          :current-enabled-structure))))
          (mv step-limit evg ttree))
         ((well-formed-lambda-objectp evg wrld)
          (let* ((formals (lambda-object-formals evg))
                 (dcl (lambda-object-dcl evg))
                 (body (lambda-object-body evg))
                 (type-alist1 (collect-0-ary-hyps type-alist))
                 (fns (all-fnnames body))
                 (progs (collect-programs fns wrld)))
            (mv-let (pre-have-warrants pre-have-no-warrants)
              (partition-userfns-by-warrantp fns wrld nil nil)

; Note that (:executable-counterpart rewrite-lambda-modep) is enabled.  Fns is
; the list of fns in body.  It does not include fns buried in quoted objects;
; they are handled by recursion.  Progs is the list of :program mode functions
; in fns, pre-have-warrants are the symbols in fns that have warrants (whether
; they're assumed in the current context or not), and pre-have-no-warrants are
; the symbols in fns for which no warrants exist but which would require a
; warrant to be apply$d.  (Primitives and apply$ primitives don't have warrants
; but don't need them.)

              (cond
               ((and (null progs)
                     (null pre-have-no-warrants))

; So body is in :logic mode and every function symbol occurring in it has a
; warrant or doesn't need one.

; Since (:executable-counterpart rewrite-lambda-modep), aka ``e'', is enabled
; and body is a well-formed tame term and all the functions in it are in :logic
; mode and have had warrants issued (whether or not they are assumed true in
; type-alist1) we have permission to modify body.

; We are going to bind rewritten-body and ttree1 to the result of either (a)
; rewriting and normalizing body or (b) removing guards and cleaning up body.
; Since e is enabled, the user can select (a) or (b) by manipulating the
; enabled status of (:definition rewrite-lambda-modep), aka ``d''.  If d is
; enabled, we do (a), and if d is disabled we do (b).  The use of
; clean-up-dirty-lambda-object-body below is intended to perform the same
; transformation on the body of this lambda as add-rewrite-rule, for example,
; would if the body were the lhs of a :rewrite rule.

; Note: Since we normalize the result of rewriting it was natural to normalize
; the result of just cleaning up.  That's easy enough to do here but impossible
; in add-rewrite-rule because there we don't have a stable ens, which is used
; in type-set and assume-true-false to normalize.  (The global ens not won't be
; the same as it was when rules were added.)  Given that we use the enabled
; status of e and d to select our action here, and that we offer 3 options now,
; we could easily offer a fourth: normalize wrt the ens available here after
; cleaning.  But we see no need, yet.

                (sl-let
                 (rewritten-body ttree1)
                 (if (enabled-numep *rewrite-lambda-modep-def-nume*
                                    (access rewrite-constant
                                            rcnst
                                            :current-enabled-structure))
                     (sl-let
                      (temp-rewritten-body temp-ttree1)
                      (rewrite-entry (rewrite body
                                              nil
                                              'lambda-object-body)
                                     :fnstack (cons :rewrite-lambda-object fnstack)
                                     :type-alist type-alist1
                                     :obj '?
                                     :geneqv nil ; maintain EQUAL
                                     :pequiv-info nil
                                     :ancestors nil
                                     :simplify-clause-pot-lst nil
                                     :ttree nil)
                      (mv-let (temp-rewritten-body temp-ttree1)
                        (normalize temp-rewritten-body
                                   nil ; iff-flg
                                   nil ; type-alist
                                   (access rewrite-constant
                                           rcnst
                                           :current-enabled-structure)
                                   wrld
                                   temp-ttree1
                                   (backchain-limit wrld :ts))
                        (mv step-limit temp-rewritten-body temp-ttree1)))
                     (mv step-limit
                         (clean-up-dirty-lambda-object-body
                          :all
                          body
                          wrld
                          (remove-guard-holders-lamp))
                         ttree))
                 (cond
                  ((equal rewritten-body body) ; no change
                   (cond
                    ((null dcl)
                     (mv step-limit evg ttree))
                    (t (mv step-limit
                           `(lambda ,formals ,body) ; Just drop the dcl
                           ttree))))
                  ((or (not (subsetp-eq (all-vars rewritten-body) formals))
                       (not (executable-tamep rewritten-body wrld)))

; If the rewritten body contains free variables or is not tame, we reject this
; whole rewrite, after possibly printing a warning.

                   (prog2$ (rewrite-lambda-object-post-warning
                            evg rewritten-body nil ttree1 wrld)
                           (mv step-limit evg ttree)))
                  (t

; The replacement of body by rewritten-body inside a quoted lambda object
; depends on the equivalence of the ev$ of the quotations of those two terms.
; We know that body is equal to rewritten-body, by the correctness of rewrite,
; normalize, etc.  So the equivalence of the ev$s of their quotations is just
; analogous to the theorem justifying meta rules, except we need to know that
; (ev$ '(fn a1 ... an) env) = (fn (ev$ 'a1 env) ... (ev$ 'an env)), for every
; function in either term.  (Note: here ``ev$'' is used where a suitable
; evaluator is used in metafunction correctness theorems.)  But we have that
; theorem for every apply$ primitive and for every apply$ boot function
; (provided the two terms are both tame), but we warrants for every userfn in
; either term.  (The tameness hypotheses required in the warrants are already
; assured by the tameness checks here, so we know we have badges, but not
; necessarily warrants.  We know all fns in rewritten-body1 are in :logic mode
; because it was produced by rewriting a :logic mode term and the rewriter
; never introduces a :program mode fn.)  Furthermore, we don't just need the
; userfns to be warranted, we need to have each warrant hypothesis.  We ensure
; that by collecting all the warranted userfns functions occurring in either
; term and then calling push-warrants.

                   (mv-let (post-have-warrants post-have-no-warrants)
                     (partition-userfns-by-warrantp
                      (all-fnnames rewritten-body)
                      wrld nil nil)
                     (cond
                      (post-have-no-warrants
                       (prog2$
                        (rewrite-lambda-object-post-warning
                         evg rewritten-body post-have-no-warrants ttree1
                         wrld)
                        (mv step-limit evg ttree)))
                      (t
                       (mv-let (erp ttree2)
                         (push-warrants (union-eq pre-have-warrants
                                                  post-have-warrants)
                                        body
                                        type-alist1
                                        (access rewrite-constant rcnst
                                                :current-enabled-structure)
                                        wrld
                                        (ok-to-force rcnst)
                                        ttree1 ttree)

; Body, above, is passed in as the ``target'' for push-warrants.  The target is
; only used in commentary about the forcing.  The :target of a forced rewrite
; rule is generally the term to which the rule was applied, but here we're
; talking about function symbols that must (probably) be apply$'d during the
; rewriting of :target.
                         (cond
                          (erp

; A warrant is assumed false, the apply$ rule for a fn is disabled, or forcing
; is not allowed.

                           (prog2$
                            (rewrite-lambda-object-post-warning
                             evg rewritten-body nil ttree1 wrld)
                            (mv step-limit
                                evg
                                ttree)))
                          (t (let ((ttree3
                                    (push-lemma
                                     *rewrite-lambda-modep-xrune*
                                     (cons-tag-trees ttree2 ttree))))
                               (mv step-limit
                                   `(lambda ,formals ,rewritten-body)
                                   (if (enabled-numep *rewrite-lambda-modep-def-nume*
                                                      (access rewrite-constant
                                                              rcnst
                                                              :current-enabled-structure))
                                       (push-lemma
                                        *rewrite-lambda-modep-def-rune*
                                        ttree3)
                                       ttree3)))))))))))))
               (t (prog2$
                   (rewrite-lambda-object-pre-warning
                    evg nil progs pre-have-no-warrants wrld)
                   (mv step-limit evg ttree)))))))
         (t (prog2$
             (and (consp evg)
                  (eq (car evg) 'lambda) ; else skip warning
                  (rewrite-lambda-object-pre-warning evg t nil nil wrld))
             (mv step-limit evg ttree))))))
)