File: basis.lisp

package info (click to toggle)
acl2 3.1-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 36,712 kB
  • ctags: 38,396
  • sloc: lisp: 464,023; makefile: 5,470; sh: 86; csh: 47; cpp: 25; ansic: 22
file content (11850 lines) | stat: -rw-r--r-- 486,526 bytes parent folder | download
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
; ACL2 Version 3.1 -- A Computational Logic for Applicative Common Lisp
; Copyright (C) 2006  University of Texas at Austin

; 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 GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; (at your option) any later version.

; 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
; GNU General Public License for more details.

; You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

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

; When we are ready to verify termination in this and later files, we should
; consider changing null to endp in a number of functions.

(in-package "ACL2")

(defun enforce-redundancy-er-args (event-form-var wrld-var)
  (list "Enforce-redundancy is active; see :DOC set-enforce-redundancy and ~
         see :DOC redundant-events.  However, the following event ~@0:~|~%~x1"
        `(if (and (symbolp (cadr ,event-form-var))
                  (decode-logical-name (cadr ,event-form-var) ,wrld-var))
             "conflicts with an existing event of the same name"
           "is not redundant")
        event-form-var))

(defmacro enforce-redundancy (event-form ctx wrld form)
  (let ((var 'redun-check-var))
    `(let ((,var (and (not (eq (ld-skip-proofsp state)
                               'include-book))
                      (cdr (assoc-eq :enforce-redundancy
                                     (table-alist 'acl2-defaults-table
                                                  ,wrld))))))
       (cond ((eq ,var t)
              (check-vars-not-free
               (,var)
               (er soft ,ctx
                   ,@(enforce-redundancy-er-args
                      event-form wrld))))
             (t (pprogn (cond (,var (check-vars-not-free
                                     (,var)
                                     (warning$ ,ctx "Enforce-redundancy"
                                               ,@(enforce-redundancy-er-args
                                                  event-form wrld))))
                              (t state))
                        (check-vars-not-free
                         (,var)
                         ,form)))))))

; System calls

#-acl2-loop-only
(defvar *last-sys-call-status* 0)

(defun sys-call (command-string args)

  ":Doc-Section ACL2::Programming

  make a system call to the host operating system~/
  ~bv[]
  Example Forms:
  (sys-call \"cp\" '(\"foo.lisp\" \"foo-copied.lisp\"))
  (prog2$ (sys-call \"cp\" '(\"foo.lisp\" \"foo-copied.lisp\"))
          (sys-call-status state))
  ~ev[]
  The first argument of ~c[sys-call] is a command for the host operating
  system, and the second argument is a list of strings that are the
  arguments for that command.  In GCL and perhaps other lisps, you can put the
  arguments with the command; but this is not the case, for example, in Allegro
  CL running on Linux.

  The use of ~ilc[prog2$] above is optional, but illustrates a typical sort
  of use when one wishes to get the return status.  ~l[sys-call-status].~/
  ~bv[]
  General Form:
  (sys-call cmd args)
  ~ev[]
  This function logically returns ~c[nil].  However, it makes the
  indicated call to the host operating system, as described above,
  using a function supplied ``under the hood'' by the underlying Lisp
  system.  On occasions where one wishes to obtain the numeric status
  returned by the host operating system (or more precisely, by the
  Lisp function under the hood that passes the system call to the host
  operating system), one may do so;  ~pl[sys-call-status].  The
  status value is the value returned by that Lisp function, which may
  well be the same numeric value returned by the host operating system
  for the underlying system call.

  Note that ~c[sys-call] does not touch the ACL2 ~ilc[state]; however,
  ~ilc[sys-call-status] updates the ~c[file-clock] field of the ~c[state].  One may
  view that update as modifying the ~c[file~clock] to be at least as
  recent as the time of the most recent ~c[sys-call].

  Be careful if you use ~c[sys-call]!  It can be used for example to overwrite
  files, or worse!  The following example from Bob Boyer shows how to use
  ~c[sys-call] to execute, in effect, arbitrary Lisp forms.  ACL2 provides a
  ``trust tag'' mechanism that requires execution of a ~ilc[defttag] form
  before you can use ~c[sys-call]; ~pl[defttag].  (Note: The setting of the raw
  Lisp variable ~c[*features*] below is just to illustrate that any such
  mischief is possible.  Normally ~c[*features*] is a list with more than a few
  elements.)
  ~bv[]
  % cat foo
  print *0x85d2064=0x838E920
  detach
  q
  % acl2
  ... boilerplate deleted
  ACL2 !>(sys-call \"gdb -p $PPID -w < foo >& /dev/null \" nil)
  NIL
  ACL2 !>:q

  Exiting the ACL2 read-eval-print loop.  To re-enter, execute (LP).
  ACL2>*features*

  (:AKCL-SET-MV)

  ACL2>
  ~ev[]

  Finally, we make a comment about output redirection, which also applies to
  other related features that one may expect of a shell.  ~c[Sys-call] does not
  directly support output redirection.  If you want to run a program, ~c[P],
  and redirect its output, we suggest that you create a wrapper script, ~c[W]
  to call instead.  Thus ~c[W] might be a shell script containing the line:
  ~bv[]
  P $* >& foo.out
  ~ev[]
  If this sort of solution proves inadequate, please contact the ACL2
  implementors and perhaps we can come up with a solution."

  #+acl2-loop-only
  (declare (ignore command-string args))
  #-acl2-loop-only 
  (let ((rslt (system-call command-string args)))
    (progn (setq *last-sys-call-status* rslt)
           nil))
  #+acl2-loop-only
  nil
  )

(encapsulate
 (((sys-call-status-sequence *) => *))
 (local (defun sys-call-status-sequence (n)
          (declare (ignore n)) 0)))

(defun sys-call-status (state-state)

; This function needs to stay in :program mode!  It isn't even a function!
; Well, except there seems to be no way for anything to go terribly wrong even
; if we verify-termination and verify-guards.

  ":Doc-Section ACL2::Programming

  exit status from the preceding system call~/

  This function returns two values, ~c[(mv status state)].  The first is
  the status returned by the most recent invocation of function
  ~c[sys-call]; ~pl[sys-call].  The second is the ACL2 ~ilc[state] object,
  which is also the input to this function.~/

  The function ~ilc[sys-call] makes a system call to the host operating
  system using a function supplied ``under the hood'' by the
  underlying Lisp system.  The status value is the value returned by
  that Lisp function, which may well be the same numeric value
  returned by the host operating system for the underlying system
  call.  For more information, ~pl[sys-call].~/"

; There is a signature problem here:
; (declare (xargs :guard (state-p state-state)))

  #-(or acl2-loop-only no-hack)
  (when (live-state-p state-state)
    (return-from sys-call-status
                 (progn (setq *file-clock* (1+ *file-clock*))
                        (mv *last-sys-call-status* state-state))))
  (let* ((new-clock (1+ (file-clock state-state)))
         (status
          (sys-call-status-sequence new-clock))
         (state-state (update-file-clock new-clock state-state)))
    (mv status state-state)))

; End of system calls

; For some reason, MCL didn't like it when there was a single definition of
; gc$-fn with acl2-loop-only directives in the body.  So we define the two
; versions separately.

#-acl2-loop-only
(defun-one-output gc$-fn (args)

; We will add some checks on the arguments as a courtesy, but really, it is up
; to the user to pass in the right arguments.

  #+allegro (apply `excl:gc args)
  #+gcl
  (if (eql (length args) 1)
      (apply 'si::gbc args)
    (er hard 'gc$
        "In GCL, gc$ requires exactly one argument, typically T."))
  #+clisp (apply 'ext:gc args)
  #+cmu (apply 'system::gc args)
  #+sbcl (apply 'sb-ext:gc args)
  #+(or mcl openmcl) (apply 'ccl::gc args)
  #+lispworks (apply 'cl-user::mark-and-sweep (or args (list 3)))
  #-(or allegro gcl clisp cmu sbcl mcl openmcl lispworks)
  (illegal 'gc$ "GC$ is not supported in this Common Lisp." nil)
  nil)

#+acl2-loop-only
(defun gc$-fn (args)
  (declare (ignore args))
  nil)

(defmacro gc$ (&rest args)
  ":Doc-Section Miscellaneous

  invoke the garbage collector~/

  This function is provided so that the user can call the garbage collector of
  the underlying Lisp from inside the ACL2 loop.  Specifically, a call of
  ~c[gc$] is translated into a call of a function below on the same arguments.
  ~bv[]
  Allegro CL:            excl:gc
  GCL                    si::gbc
  CLISP                  ext:gc
  CMU Common Lisp        system::gc
  SBCL                   sb-ext:gc
  Macintosh Common Lisp  ccl::gc
  ~ev[]
  The arguments, if any, are as documented in the underlying Common Lisp.  It
  is up to the user to pass in the right arguments, although we may do some
  rudimentary checks.

  This function always returns ~c[nil].~/~/"

  `(gc$-fn ',args))

(defdoc gcl
  ":Doc-Section miscellaneous

  tips on building and using ACL2 based on Gnu Common Lisp~/

  See the installation instructions for basic information about building ACL2
  on top of GCL, including information about where to fetch GCL.  Here, we
  provide some tips that may be useful.~/

  1. You can place forms to evaluate at start-up into file ~c[init.lsp] in the
  directory where you are starting ACL2 (GCL), or into file ~c[acl2-init.lsp]
  in your home directory.  For example, in order to evaluate both of the lisp
  forms mentioned in 2 below, you could put them both into ~c[init.lsp] in the
  current directory or in ~c[~~/acl2-init.lsp] (either way, without ~c[(lp)] or
  ~c[:q]):
  ~bv[]
  (setq si::*optimize-maximum-pages* nil)
  (si::allocate 'cons 75000 t)
  ~ev[]

  2. Suppose you run out of space, for example with an error like this:
  ~bv[]
     Error: The storage for CONS is exhausted.
       Currently, 59470 pages are allocated.
       Use ALLOCATE to expand the space.
  ~ev[]
  The following suggestion from Camm Maguire will minimize the heap size, at
  the cost of more garbage collection time.
  ~bv[]
  :q   ; exit the ACL2 loop
  (setq si::*optimize-maximum-pages* nil)
  (lp) ; re-enter the ACL2 loop
  ~ev[]
  A second thing to try, suggested by several people, is to preallocate more
  pages before the run, e.g.:
  ~bv[]
  :q   ; exit the ACL2 loop
  (si::allocate 'cons 75000 t)
  (lp) ; re-enter the ACL2 loop
  ~ev[]
  Also ~pl[reset-kill-ring] for a suggestion on how to free up space.

  3. Windows users have seen this error:
  ~bv[]
  cc1.exe: unrecognized option `-fno-zero-initialized-in-bss'
  ~ev[]
  Camm Maguire suggests that a solution may be to evaluate the following in GCL
  before building ACL2.
  ~bv[]
  (in-package 'compiler)
  (let* ((x `-fno-zero-initialized-in-bss')
         (i (search x *cc*))) 
          (setq *cc* (concatenate 'string 
                                  (subseq *cc* 0 i)
                                  (subseq *cc* (+ i (length x))))))
  ~ev[]

  4. It is possible to profile using ACL2 built on GCL.  See file
  ~c[save-gprof.lsp] in the ACL2 source directory.

  5. Some versions of GCL may have garbage-collector bugs that, on rare
  occasions, cause ACL2 (when built on GCL) to break.  If you run into this,
  a solution may be to execute the following:
  ~bv[]
  :q
  (si::sgc-on nil)
  (lp)
  ~ev[]
  Alternatively, put ~c[(si::sgc-on nil)] in your ~c[~~/acl2-init.lsp] file.

  A full regression test and found that this decreased performance by about
  10%.  But even with that, GCL may be the fastest Common Lisp for ACL2 on
  Linux (performance figures may often be found by following the ``Recent
  changes'' link on the ACL2 home page).

  ~/")

(defmacro wormhole (pseudo-flg name input form
                        &key
                        (current-package 'same current-packagep)
                        (ld-skip-proofsp 'same ld-skip-proofspp)
                        (ld-redefinition-action 'save ld-redefinition-actionp)
                        (ld-prompt ''wormhole-prompt)
                        (ld-keyword-aliases 'same ld-keyword-aliasesp)
                        (ld-pre-eval-filter 'same ld-pre-eval-filterp)
                        (ld-pre-eval-print 'same ld-pre-eval-printp)
                        (ld-post-eval-print 'same ld-post-eval-printp)
                        (ld-evisc-tuple 'same ld-evisc-tuplep)
                        (ld-error-triples 'same ld-error-triplesp)
                        (ld-error-action 'same ld-error-actionp)
                        (ld-query-control-alist 'same ld-query-control-alistp)
                        (ld-verbose 'same ld-verbosep))

  ":Doc-Section Miscellaneous

  ~ilc[ld] without ~ilc[state] ~-[] a short-cut to a parallel universe~/
  ~bv[]
  Example Form:
  (wormhole t 'interactive-break nil '(value 'hi!))
                               ; Enters a recursive read-eval-print loop
                               ; on a copy of the ``current ~ilc[state]'' and
                               ; returns nil!~/

  General Form:
  (wormhole pseudo-flg name input form
    :current-package    ...  ; known package name
    :ld-skip-proofsp    ...  ; t, nil or 'include-book
    :ld-redefinition-action  ; nil or '(:a . :b)
    :ld-prompt          ...  ; nil, t, or some prompt printer fn
    :ld-keyword-aliases ...  ; an alist pairing keywords to parse info
    :ld-pre-eval-filter ...  ; :all, :query, or some new name
    :ld-pre-eval-print  ...  ; nil, t, or :never
    :ld-post-eval-print ...  ; nil, t, or :command-conventions
    :ld-evisc-tuple     ...  ; nil or '(alist level length hiding-cars)
    :ld-error-triples   ...  ; nil or t
    :ld-error-action    ...  ; :continue, :return, or :error
    :ld-query-control-alist  ; alist supplying default responses
    :ld-verbose         ...) ; nil or t
  ~ev[]
  The keyword arguments above are exactly those of ~ilc[ld] (~pl[ld])
  except that three of ~ilc[ld]'s keyword arguments are missing: the three
  that specify the channels ~ilc[standard-oi], ~ilc[standard-co] and ~ilc[proofs-co].
  Essentially ~c[wormhole] is just a call of ~ilc[ld] on the current ~ilc[state] with
  the given keyword arguments.  ~c[Wormhole] always returns ~c[nil].  The
  ~st[amazing] thing about ~c[wormhole] is that it calls ~ilc[ld] and interacts with
  the user even though ~ilc[state] is not available as an argument!

  ~c[Wormhole] does this by manufacturing a ``wormhole ~il[state],'' a copy of
  the ``current ~il[state]'' (whatever that is) modified so as to contain
  some of the wormhole arguments.  ~ilc[Ld] is called on that wormhole ~il[state]
  with the three ~ilc[ld] channels directed to ACL2's ``comment window.'' At
  the moment, the comment window is overlaid on the terminal and you
  cannot tell when output is going to ~ilc[*standard-co*] and when it is
  going to the comment window.  But we imagine that eventually a
  different window will pop up on your screen.  In any case, the
  interaction provided by this call of ~ilc[ld] does not modify the ~ilc[state]
  ``from which'' wormhole was called, it modifies the copied ~ilc[state].
  When ~ilc[ld] exits (e.g., in response to ~c[:]~ilc[q] being typed in the comment
  window) the wormhole ~il[state] evaporates and ~c[wormhole] returns ~c[nil].
  Logically and actually (from the perspective of the ongoing
  computation) nothing has happened except that a ``no-op'' function was
  called and returned ~c[nil].

  The name ~c[wormhole] is meant to suggest the idea that the function
  provides easy access to ~ilc[state] in situations where it is apparently
  impossible to get ~ilc[state].  Thus, for example, if you define the
  ~c[factorial] function, say, except that you sprinkled into its body
  appropriate calls of ~c[wormhole], then the execution of ~c[(factorial 6)]
  would cause interactive breaks in the comment window.  During those
  breaks you would apparently be able to inspect the ``current ~il[state]''
  even though ~c[factorial] does not take ~ilc[state] as an argument.  The whole
  notion of there being a ``current ~il[state]'' during the evaluation of
  ~c[(factorial 6)] is logically ill-defined.  And yet, we know from
  practical experience with the sequential computing machines upon
  which ACL2 is implemented that there is a ``current ~il[state]'' (to
  which the ~c[factorial] function is entirely insensitive) and that is
  the ~il[state] to which ~c[wormhole] ``tunnels.'' A call of ~c[wormhole] from
  within ~c[factorial] can pass ~c[factorial]-specific information that is
  embedded in the wormhole ~il[state] and made available for inspection by
  the user in an interactive setting.  But no information ever flows
  out of a wormhole ~il[state]: ~c[wormhole] always returns ~c[nil].

  There are some restrictions about what can be done inside a wormhole.  As you
  may imagine, we really do not ``copy the current state'' but rather just keep
  track of how we modified it and undo those modifications upon exit.  An error is
  signalled if you try to modify ~c[state] in an unsupported way.  For this same
  reason, wormholes do not allow updating of any user-defined single-threaded
  objects.  ~l[stobj].

  There are four arguments to ~c[wormhole] that need further explanation:
  ~c[pseudo-flg], ~c[name], ~c[input], and ~c[form].  Roughly speaking, the value of
  ~c[pseudo-flg] should be ~c[t] or ~c[nil] and indicates whether we are actually
  to enter a wormhole or just return ~c[nil] immediately.  The actual
  handling of ~c[pseudo-flg] is more sophisticated and is explained in
  detail at the end of this ~il[documentation].

  ~c[Name] and ~c[input] are used as follows.  Recall that ~c[wormhole] copies the
  ``current ~il[state]'' and then modifies it slightly to obtain the ~ilc[state]
  upon which ~ilc[ld] is called.  We now describe the modifications.  First,
  the ~ilc[state] global variable ~c['wormhole-name] is set to ~c[name], which may
  be any non-~c[nil] ACL2 object but is usually a symbol.  Then,
  ~c['wormhole-input] is set to ~c[input], which may be any ACL2 object.
  Finally, and inexplicably, ~c['wormhole-output] is set to the value of
  ~c['wormhole-output] the last time a wormhole named ~c[name] was exited (or
  ~c[nil] if this is the first time a wormhole named ~c[name] was entered).
  This last aspect of wormholes, namely the preservation of
  ~c['wormhole-output], allows all the wormholes of a given name to
  communicate with each other.

  We can now explain how ~c[form] is used.  The modified ~ilc[state] described
  above is the ~ilc[state] on which ~ilc[ld] is called.  However, ~ilc[standard-oi] ~-[]
  the input channel from which ~ilc[ld] reads ~il[command]s ~-[] is set so that the
  first ~il[command] that ~ilc[ld] reads and evaluates is ~c[form].  If ~c[form] returns
  an error triple with value ~c[:]~ilc[q], i.e., ~c[form] returns via ~c[(value :q)],
  then no further ~il[command]s are read, ~ilc[ld] exits, and the wormhole exits
  and returns ~c[nil].  But if ~c[form] returns any other value (or is not an
  error triple), then subsequent ~il[command]s are read from the comment
  window.

  As usual, the ~ilc[ld]-specials affect whether a herald is printed upon
  entry, whether ~c[form] is printed before evaluation, whether a ~il[prompt]
  is printed, how errors are handled, etc.  The ~ilc[ld]-specials can be
  specified with the corresponding arguments to ~c[wormhole].  It is
  standard practice to call ~c[wormhole] so that the entry to ~ilc[ld] and the
  evaluation of ~c[form] are totally silent.  Then, tests in ~c[form] can
  inspect the ~ilc[state] and decide whether user interaction is desired.
  If so, ~c[form] can appropriately set ~ilc[ld-prompt], ~ilc[ld-error-action], etc.,
  print a herald, and then return ~c[(value :invisible)].  Recall
  (~pl[ld]) that ~c[(value :invisible)] causes ~ilc[ld] not to print a value
  for the just executed form.  The result of this arrangement is that
  whether interaction occurs can be based on tests that are performed
  on the wormhole ~il[state] after ~c[(@ wormhole-input)] and the last
  ~c[(@ wormhole-output)] are available for inspection.  This is
  important because outside the wormhole you can access
  ~c[wormhole-input] (you are passing it into the wormhole) but you may
  not be able to access the current ~ilc[state] (because you might be in
  ~c[factorial]) and you definitely cannot access the ~c[wormhole-output] of
  the last wormhole because it is not part of the ACL2 ~ilc[state].  Thus,
  if the condition under which you wish to interact depends upon the
  ~ilc[state] or that part of it preserved from the last wormhole
  interaction, that condition can only be tested from within the
  wormhole, via ~c[form].

  It is via this mechanism that ~ilc[break-rewrite] (~pl[break-rewrite])
  is implemented.  To be more precise, the list of ~il[monitor]ed ~il[rune]s is
  maintained as part of the preserved ~c[wormhole-output] of the
  ~ilc[break-rewrite] wormhole.  Because it is not part of the normal ~ilc[state],
  it may be changed by the user during proofs.  That is what allows
  you to install new ~il[monitor]s while debugging proofs.  But that means
  that the list of ~il[monitor]ed ~il[rune]s cannot be inspected from outside
  the wormhole.  Therefore, to decide whether a break is to occur when
  a given rule is applied, the rewriter must enter the ~ilc[break-rewrite]
  wormhole, supplying a form that causes interaction if the given
  rule's break condition is satisfied.  The user perceives this as
  though the wormhole was conditionally entered ~-[] a perception that
  is happily at odds with the informed user's knowledge that the list
  of ~il[monitor]ed ~il[rune]s is not part of the ~ilc[state].  In fact, the wormhole
  was unconditionally entered and the condition was checked from
  within the wormhole, that being the only ~il[state] in which the
  condition is known.

  Another illustrative example is available in the implemention of the
  ~ilc[monitor] command.  How can we add a new ~il[rune] to the list of ~il[monitor]ed
  ~il[rune]s while in the normal ACL2 ~ilc[state] (i.e., while not in a
  wormhole)?  The answer is: by getting into a wormhole.  In
  particular, when you type ~c[(monitor rune expr)] at the top-level of
  ACL2, ~ilc[monitor] enters the ~ilc[break-rewrite] wormhole with a cleverly
  designed first ~c[form].  That form adds ~il[rune] and ~c[expr] to the list of
  ~il[monitor]ed ~il[rune]s ~-[] said list only being available in ~ilc[break-rewrite]
  wormhole ~il[state]s.  Then the first form returns ~c[(value :q)], which
  causes us to exit the wormhole.  By using ~ilc[ld]-specials that
  completely suppress all output during the process, it does not
  appear to the user that a wormhole was entered.  The moral here is
  rather subtle: the first form supplied to ~c[wormhole] may be the entire
  computation you want to perform in the wormhole; it need not just be
  a predicate that decides if interaction is to occur.  Using
  wormholes of different names you can maintain a variety of
  ``hidden'' data structures that are always accessible (whether
  passed in or not).  This appears to violate completely the
  applicative semantics of ACL2, but it does not: because these data
  structures are only accessible via ~c[wormhole]s, it is impossible for
  them to affect any ACL2 computation (except in the comment window).

  As one might imagine, there is some overhead associated with
  entering a wormhole because of the need to copy the current ~ilc[state].
  This brings us back to ~c[pseudo-flg].  Ostensibly, ~c[wormhole] is a
  function and hence all of its argument expressions are evaluated
  outside the function (and hence, outside the wormhole it creates)
  and then their values are passed into the function where an
  appropriate wormhole is created.  In fact, ~c[wormhole] is a macro that
  permits the ~c[pseudo-flg] expression to peer dimly into the wormhole
  that will be created before it is created.  In particular,
  ~c[pseudo-flg] allows the user to access the ~c[wormhole-output] that will
  be used to create the wormhole ~il[state].

  This is done by allowing the user to mention the (apparently
  unbound) variable ~c[wormhole-output] in the first argument to ~c[wormhole].
  Logically, ~c[wormhole] is a macro that wraps
  ~bv[]
  (let ((wormhole-output nil)) ...)
  ~ev[]
  around the expression supplied as its first argument.  So logically,
  ~c[wormhole-output] is always ~c[nil] when the expression is
  evaluated.  However, actually, ~c[wormhole-output] is bound to the
  value of ~c[(@ wormhole-output)] on the last exit from a wormhole of
  the given name (or ~c[nil] if this is the first entrance).  Thus, the
  ~c[pseudo-flg] expression, while having to handle the possibility
  that ~c[wormhole-output] is ~c[nil], will sometimes see non-~c[nil]
  values.  The next question is, of course, ``But how can you get away
  with saying that logically ~c[wormhole-output] is always ~c[nil] but
  actually it is not?  That doesn't appear to be sound.'' But it is
  sound because whether ~c[pseudo-flg] evaluates to ~c[nil] or
  non-~c[nil] doesn't matter, since in either case ~c[wormhole] returns
  ~c[nil].  To make that point slightly more formal, imagine that
  ~c[wormhole] did not take ~c[pseudo-flg] as an argument.  Then it
  could be implemented by writing
  ~bv[]
  (if pseudo-flg (wormhole name input form ...) nil).
  ~ev[]
  Now since wormhole always returns ~c[nil], this expression is
  equivalent to ~c[(if pseudo-flg nil nil)] and we see that the value
  of ~c[pseudo-flg] is irrelevant.  So we could in fact allow the user
  to access arbitrary information to decide which branch of this if to
  take.  We allow access to ~c[wormhole-output] because it is often all
  that is needed.  We don't allow access to ~ilc[state] (unless ~ilc[state] is
  available at the level of the wormhole call) for technical reasons
  having to do with the difficulty of overcoming ~c[translate]'s
  prohibition of the sudden appearance of the variable ~ilc[state].

  We conclude with an example of the use of ~c[pseudo-flg].  This example
  is a simplification of our implementation of ~ilc[break-rewrite].  To
  enter ~ilc[break-rewrite] at the beginning of the attempted application of
  a rule, ~c[rule], we use
  ~bv[]
  (wormhole
   (and (f-get-global 'brr-mode state)
        (member-equal (access rewrite-rule rule :rune)
                      (cdr (assoc-eq 'monitored-runes wormhole-output))))
   'break-rewrite
   ...)
  ~ev[]
  The function in which this call of ~c[wormhole] occurs has ~ilc[state] as a
  formal.  The ~c[pseudo-flg] expression can therefore refer to ~ilc[state] to
  determine whether ~c['brr-mode] is set.  But the ~c[pseudo-flg] expression
  above mentions the variable ~c[wormhole-output]; this variable is not
  bound in the context of the call of ~c[wormhole]; if ~c[wormhole] were a
  simple function symbol, this expression would be illegal because it
  mentions a free variable.

  However, it is useful to think of ~c[wormhole] as a simple function that
  evaluates all of its arguments but to also imagine that somehow
  ~c[wormhole-output] is magically bound around the first argument so that
  ~c[wormhole-output] is the output of the last ~ilc[break-rewrite] wormhole.
  If we so imagine, then the ~c[pseudo-flg] expression above evaluates
  either to ~c[nil] or non-~c[nil] and we will enter the wormhole named
  ~ilc[break-rewrite] in the latter case.

  Now what does the ~c[pseudo-flg] expression above actually test?  We
  know the format of our own ~c[wormhole-output] because we are
  responsible for maintaining it.  In particular, we know that the
  list of ~il[monitor]ed ~il[rune]s can be obtained via
  ~bv[]
  (cdr (assoc-eq 'monitored-runes wormhole-output)).
  ~ev[]
  Using that knowledge we can design a ~c[pseudo-flg] expression which
  tests whether (a) we are in ~c[brr-mode] and (b) the ~il[rune] of the
  current rule is a member of the ~il[monitor]ed ~il[rune]s.  Question (a) is
  answered by looking into the current ~ilc[state].  Question (b) is
  answered by looking into that part of the about-to-be-created
  wormhole ~il[state] that will differ from the current ~ilc[state].  To
  reiterate the reason we can make ~c[wormhole-output] available here
  even though it is not in the current ~ilc[state]: logically speaking the
  value of ~c[wormhole-output] is irrelevant because it is only used to
  choose between two identical alternatives.  This example also makes
  it clear that ~c[pseudo-flg] provides no additional functionality.
  The test made in the ~c[pseudo-flg] expression could be moved into
  the first form evaluated by the wormhole ~-[] changing the free
  variable ~c[wormhole-output] to ~c[(@ wormhole-output)] and arranging
  for the first form to return ~c[(value :q)] when the ~c[pseudo-flg]
  expression returns ~c[nil].  The only reason we provide the
  ~c[pseudo-flg] feature is because it allows the test to be carried
  out without the overhead of entering the wormhole.

  Wormholes can be used not only in ~c[:]~ilc[program] mode definitions but also
  in ~c[:]~ilc[logic] mode definitions.  Thus, it is possible (though somewhat
  cumbersome without investing in macro support) to annotate logical
  functions with output facilities that do not require ~c[state].  These
  facilities do not complicate proof obligations.  Suppose then that
  one doctored a simple function, e.g., APP, so as to do some printing
  and then proved that APP is associative.  The proof may generate
  extraneous output due to the doctoring.  Furthermore, contrary to
  the theorem proved, execution of the function appears to affect
  *standard-co*.  To see what the function ``really'' does when
  evaluated, enter raw lisp and set the global variable
  *inhibit-wormhole-activityp* to t."

  `(let ((wormhole-name ,name))
     (cond
      ((let ((wormhole-output
              #+acl2-loop-only nil
              #-acl2-loop-only (cdr (assoc-equal wormhole-name
                                                  *wormhole-outputs*))))
         (prog2$ wormhole-output
                 (check-vars-not-free (wormhole-name) ,pseudo-flg)))
       (wormhole1
        wormhole-name
        (check-vars-not-free (wormhole-name) ,input)
        (check-vars-not-free (wormhole-name) ,form)
        (check-vars-not-free (wormhole-name)
          (list
           ,@(append
              (if current-packagep
                  (list `(cons 'current-package ,current-package))
                  nil)
              (if ld-skip-proofspp
                  (list `(cons 'ld-skip-proofsp ,ld-skip-proofsp))
                  nil)
              (if ld-redefinition-actionp
                  (list `(cons 'ld-redefinition-action
                               ,ld-redefinition-action))
                  nil)
              (list `(cons 'ld-prompt ,ld-prompt))
              (if ld-keyword-aliasesp
                  (list `(cons 'ld-keyword-aliases
                               ,ld-keyword-aliases))
                  nil)
              (if ld-pre-eval-filterp
                  (list `(cons 'ld-pre-eval-filter ,ld-pre-eval-filter))
                  nil)
              (if ld-pre-eval-printp
                  (list `(cons 'ld-pre-eval-print ,ld-pre-eval-print))
                  nil)
              (if ld-post-eval-printp
                  (list `(cons 'ld-post-eval-print ,ld-post-eval-print))
                  nil)
              (if ld-evisc-tuplep
                  (list `(cons 'ld-evisc-tuple ,ld-evisc-tuple))
                  nil)
              (if ld-error-triplesp
                  (list `(cons 'ld-error-triples ,ld-error-triples))
                  nil)
              (if ld-error-actionp
                  (list `(cons 'ld-error-action ,ld-error-action))
                  nil)
              (if ld-query-control-alistp
                  (list `(cons 'ld-query-control-alist ,ld-query-control-alist))
                  nil)
              (if ld-verbosep
                  (list `(cons 'ld-verbose ,ld-verbose))
                  nil))))))
           (t nil))))

(defmacro assign-wormhole-output (pseudo-flg name input expr)

; This function is supposed to be equivalent to the wormhole call below.  The
; reason we define it specially is because it is used by push-accp and pop-accp
; and hence its efficiency is paramount.  The trouble with the logical
; definition is that entering the wormhole requires saving a lot of state,
; entering ld and translating the form supplied, and then the state saving and
; undoing code.

; One side-effect of having this function it is is now pretty efficient to
; save things into wormholes, if that is all you want to do.  For example,
; you can put

; (assign-wormhole-output t 'my-place input (foo ...))

; any place you can evaluate (foo ...) to squirrel its value away into
; (@ wormhole-output) of the wormhole called 'my-place.  The expression
; (foo ...) may mention anything that could have been used in a wormhole
; command, including (@ wormhole-input) and (@ wormhole-output), which 
; have the obvious values.

  (declare (xargs :guard (and (consp expr)
                              (eq (car expr) 'quote)
                              (consp (cdr expr)))))
  #+acl2-loop-only
  `(wormhole ,pseudo-flg ,name ,input
             `(er-progn (assign wormhole-output ,,expr)
                        (value :q))
            :ld-prompt  nil
            :ld-pre-eval-filter :all
            :ld-pre-eval-print  nil
            :ld-post-eval-print :command-conventions
            :ld-evisc-tuple nil
            :ld-error-triples  t
            :ld-error-action :error
            :ld-query-control-alist nil
            :ld-verbose nil)
  #-acl2-loop-only
  `(let* ((state *the-live-state*)
          (wormhole-name ,name)
          (wormhole-output
           (cdr (assoc-equal wormhole-name *wormhole-outputs*))))
     (cond
      ((prog2$ wormhole-output
               (check-vars-not-free (wormhole-name) ,pseudo-flg))
       (let* ((wormhole-saved-input
               (check-vars-not-free (wormhole-name wormhole-output)
                                    ,input))

; Note that we evaluate input before we have f-put-globals wormhole-name,
; etc.  That is because the input is evaluated in the environment of the
; call, not in the wormhole.  Next we collect the information necessary to
; undo the assignments we must carry out before evaluating the expr.

              (wormhole-old-name-boundp (boundp-global1 'wormhole-name state))
              (wormhole-old-name (if wormhole-old-name-boundp
                                     (f-get-global 'wormhole-name state)
                                     nil))
              (wormhole-old-input-boundp (boundp-global1 'wormhole-input state))
              (wormhole-old-input
               (if wormhole-old-input-boundp
                   (f-get-global 'wormhole-input state)
                   nil))
              (wormhole-old-output-boundp
               (boundp-global1 'wormhole-output state))
              (wormhole-old-output (if wormhole-old-output-boundp
                                       (f-get-global 'wormhole-output state)
                                       nil)))
        (f-put-global 'wormhole-name wormhole-name state)
        (f-put-global 'wormhole-input wormhole-saved-input state)
        (f-put-global 'wormhole-output wormhole-output state)
        (setq *wormhole-outputs*
              (put-assoc-equal wormhole-name
                               (check-vars-not-free
                                (wormhole-name
                                 wormhole-output
                                 wormhole-old-name-boundp wormhole-old-name
                                 wormhole-old-input-boundp wormhole-old-input
                                 wormhole-old-output-boundp wormhole-old-output)
                                ,(cadr expr))
                               *wormhole-outputs*))
        (if wormhole-old-output-boundp
            (f-put-global 'wormhole-output wormhole-old-output state)
            (makunbound-global 'wormhole-output state))
        (if wormhole-old-input-boundp
            (f-put-global 'wormhole-input wormhole-old-input state)
            (makunbound-global 'wormhole-input state))
        (if wormhole-old-name-boundp
            (f-put-global 'wormhole-name wormhole-old-name state)
            (makunbound-global 'wormhole-name state))
        nil))
     (t nil))))

(defun global-set (var val wrld)
  (declare (xargs :guard (and (symbolp var)
                              (worldp wrld))))
  (putprop var 'global-value val wrld))

(defun defabbrev1 (lst)
  (declare (xargs :guard (true-listp lst)))
  (cond ((null lst) nil)
        (t (cons (list 'list (list 'quote (car lst)) (car lst))
                 (defabbrev1 (cdr lst))))))

(defmacro er (severity context str &rest str-args)
  (declare (xargs :guard (and (true-listp str-args)
                              (member-symbol-name (symbol-name severity)
                                                  '(hard hard? hard! soft))
                              (<= (length str-args) 10))))

; Note:  We used to require (stringp str) but then we
; started writing such forms as (er soft ctx msg x y z), where
; msg was bound to the error message str (because the same string
; was used many times).

; The special form (er hard "..." &...) expands into a call of
; illegal on "..." and an alist built from &....  Since
; illegal has a guard of nil, the attempt to prove the
; correctness of a fn producing a hard error will require proving
; that the error can never occur.  At runtime, illegal causes a
; CLTL error.

; The form (er soft ctx "..." &...) expands into a call of error1 on
; ctx, "..." and an alist built from &....  At runtime error1 builds an
; error object and returns it.  Thus, soft errors are not errors at
; all in the CLTL sense and any function calling one which might
; cause an error ought to handle it.

; Just to make it easier to debug our code, we have arranged for the
; er macro to actually produce a prog2 form in which the second arg
; is as described above but the preceding one is an fmt statement
; which will actually print the error str and alist.  Thus, we can
; see when soft errors occur, whether or not the calling program
; handles them appropriately.

; We do not advertise the hard! severity, at least not yet.  The implementation
; uses it to force a hard error even in contexts where we would normally return
; nil.

  ":Doc-Section ACL2::Programming

  print an error message and ``cause an error''~/
  ~bv[]
  Example Forms:
  (er hard  'top-level \"Illegal inputs, ~~x0 and ~~x1.\" a b)
  (er hard? 'top-level \"Illegal inputs, ~~x0 and ~~x1.\" a b)
  (er soft  'top-level \"Illegal inputs, ~~x0 and ~~x1.\" a b)
  ~ev[]
  The examples above all print an error message to standard output saying that
  ~c[a] and ~c[b] are illegal inputs.  However, the first two abort evaluation
  after printing an error message, while the third returns ~c[(mv t nil state)]
  after printing an error message.  The result in the third case can be
  interpreted as an ``error'' when programming with the ACL2 ~ilc[state],
  something most ACL2 users will probably not want to do;
  ~pl[ld-error-triples] and ~pl[er-progn].

  ~c[Er] is a macro, and the above three examples expand to calls of ACL2
  functions, as shown below.  ~l[illegal], ~pl[hard-error], and ~pl[error1],
  respectively.~/
  ~bv[]
  General forms:
  (er hard  ctx fmt-string arg1 arg2 ... argk)
    ==> {macroexpands, in essence, to:}
  (ILLEGAL    CTX FMT-STRING
              (LIST (CONS #\\0 ARG1) (CONS #\\1 ARG2) ... (CONS #\\k ARGk)))

  (er hard? ctx fmt-string arg1 arg2 ... argk)
    ==> {macroexpands, in essence, to:}
  (HARD-ERROR CTX FMT-STRING
              (LIST (CONS #\\0 ARG1) (CONS #\\1 ARG2) ... (CONS #\\k ARGk)))

  (er soft  ctx fmt-string arg1 arg2 ... argk)
    ==> {macroexpands, in essence, to:}
  (ERROR1     CTX FMT-STRING
              (LIST (CONS #\\0 ARG1) (CONS #\\1 ARG2) ... (CONS #\\k ARGk)))
  ~ev[]~/"

  (let ((alist (make-fmt-bindings '(#\0 #\1 #\2 #\3 #\4
                                    #\5 #\6 #\7 #\8 #\9)
                                  str-args))
        (severity-name (symbol-name severity)))
    (cond ((equal severity-name "SOFT")
           (list 'error1 context str alist 'state))
          ((equal severity-name "HARD?")
           (list 'hard-error context str alist))
          ((equal severity-name "HARD")
           (list 'illegal context str alist))
          ((equal severity-name "HARD!")
           #+acl2-loop-only (list 'illegal context str alist)
           #-acl2-loop-only `(let ((*hard-error-returns-nilp* nil))
                              (illegal ,context ,str ,alist)))
          (t

; The final case should never happen.

           (illegal 'top-level
                    "Illegal severity, ~x0; macroexpansion of ER failed!"
                    (list (cons #\0 severity)))))))

(defun legal-variable-or-constant-namep (name)

; This function checks the syntax of variable or constant name
; symbols.  In all cases, name must be a symbol that is not in the
; keyword package or among *common-lisp-specials-and-constants*
; (except t and nil), or in the main Lisp package but outside
; *common-lisp-symbols-from-main-lisp-package*, and that does not
; start with an ampersand.  The function returns 'constant, 'variable,
; or nil.

; WARNING: T and nil are legal-variable-or-constant-nameps
; because we want to allow their use as constants.

; We now allow some variables (but still no constants) from the main Lisp
; package.  See *common-lisp-specials-and-constants*.  The following two note
; explains why we have been cautious here.

; Historical Note

; This package restriction prohibits using some very common names as
; variables or constants, e.g., MAX and REST.  Why do we do this?  The
; reason is that there are a few such symbols, such as
; LAMBDA-LIST-KEYWORDS, which if bound or set could cause real
; trouble.  Rather than attempt to identify all of the specials of
; CLTL that are prohibited as ACL2 variables, we just prohibit them
; all.  One might be reminded of Alexander cutting the Gordian Knot.
; We could spend a lot of time unravelling complex questions about
; specials in CLTL or we can get on with it.  When ACL2 prevents you
; from using REST as an argument, you should see the severed end of a
; once tangled rope.

; For example, akcl and lucid (and others perhaps) allow you to define
; (defun foo (boole-c2) boole-c2) but then (foo 3) causes an error.
; Note that boole-c2 is recognized as special (by
; system::proclaimed-special-p) in lucid, but not in akcl (by
; si::specialp); in fact it's a constant in both.  Ugh.

; End of Historical Note.

  (and (symbolp name)
       (cond
        ((or (eq name t) (eq name nil))
         'constant)
        (t (let ((p (symbol-package-name name)))
             (and (not (equal p "KEYWORD"))
                  (let ((s (symbol-name name)))
                    (cond
                     ((and (not (= (length s) 0))
                           (eql (char s 0) #\*)
                           (eql (char s (1- (length s))) #\*))
                      (if (equal p *main-lisp-package-name*)
                          nil
                        'constant))
                     ((and (not (= (length s) 0))
                           (eql (char s 0) #\&))
                      nil)
                     ((equal p *main-lisp-package-name*)
                      (and (not (member-eq
                                 name
                                 *common-lisp-specials-and-constants*))
                           (member-eq
                            name
                            *common-lisp-symbols-from-main-lisp-package*)
                           'variable))
                     (t 'variable)))))))))

(defun legal-constantp1 (name)

; This function should correctly distinguish between variables and
; constants for symbols that are known to satisfy
; legal-variable-or-constant-namep.  Thus, if name satisfies this
; predicate then it cannot be a variable.

  (declare (xargs :guard (symbolp name)))
  (or (eq name t)
      (eq name nil)
      (let ((s (symbol-name name)))
        (and (not (= (length s) 0))
             (eql (char s 0) #\*)
             (eql (char s (1- (length s))) #\*)))))

(defun tilde-@-illegal-variable-or-constant-name-phrase (name)

; Assume that legal-variable-or-constant-namep has failed on name.
; We return a phrase that when printed with ~@0 will complete the
; sentence "Variable names must ...".  Observe that the sentence
; could be "Constant names must ...".

  (cond ((not (symbolp name)) "be symbols")
        ((keywordp name) "not be in the KEYWORD package")
        ((and (legal-constantp1 name)
              (equal (symbol-package-name name) *main-lisp-package-name*))
         (cons "not be in the main Lisp package, ~x0"
               (list (cons #\0 *main-lisp-package-name*))))
        ((and (> (length (symbol-name name)) 0)
              (eql (char (symbol-name name) 0) #\&))
         "not start with ampersands")
        ((and (not (legal-constantp1 name))
              (member-eq name *common-lisp-specials-and-constants*))
         "not be among certain symbols from the main Lisp package, namely, the ~
          value of the list *common-lisp-specials-and-constants*")
        ((and (not (legal-constantp1 name))
              (equal (symbol-package-name name) *main-lisp-package-name*)
              (not (member-eq name *common-lisp-symbols-from-main-lisp-package*)))
         "either not be in the main Lisp package, or else must be among the ~
          imports into ACL2 from that package, namely, the list ~
          *common-lisp-symbols-from-main-lisp-package*")
        (t "be approved by LEGAL-VARIABLE-OR-CONSTANT-NAMEP and this ~
            one wasn't, even though it passes all the checks known to ~
            the diagnostic function ~
            TILDE-@-ILLEGAL-VARIABLE-OR-CONSTANT-NAME-PHRASE")))

(defun legal-constantp (name)

; A name may be declared as a constant if it has the syntax of a
; variable or constant (see legal-variable-or-constant-namep) and
; starts and ends with a *.

; WARNING: Do not confuse this function with defined-constant.

  (eq (legal-variable-or-constant-namep name) 'constant))

(defun defined-constant (name w)

; Name is a defined-constant if it has been declared with defconst.
; If name is a defined-constant then we can show that it satisfies
; legal-constantp, because when a name is declared as a constant we
; insist that it satisfy the syntactic check.  But there are
; legal-constantps that aren't defined-constants, e.g., any symbol
; that could be (but hasn't yet been) declared as a constant.  We
; check, below, that name is a symbolp just to guard the getprop.

; This function returns the quoted term that is the value of name, if
; name is a constant.  That result is always non-nil (it may be (quote
; nil) of course).

  (and (symbolp name)
       (getprop name 'const nil 'current-acl2-world w)))

(defun legal-variablep (name)

; Name may be used as a variable if it has the syntax of a variable
; (see legal-variable-or-constant-namep) and does not have the syntax of
; a constant, i.e., does not start and end with a *.

  (eq (legal-variable-or-constant-namep name) 'variable))

(defun lambda-keywordp (x)
  (and (symbolp x)
       (eql 1 (string<= "&" (symbol-name x)))))

(defun no-lambda-keywordsp (lst)
  (declare (xargs :guard (true-listp lst)))
  (cond ((null lst) t)
        ((lambda-keywordp (car lst))
         nil)
        (t (no-lambda-keywordsp (cdr lst)))))

(defun arglistp1 (lst)

; Every element of lst is a legal-variablep.

  (cond ((atom lst) (null lst))
        (t (and (legal-variablep (car lst))
                (arglistp1 (cdr lst))))))

(defun arglistp (lst)
  (and (arglistp1 lst)
       (no-duplicatesp lst)))

(defun find-first-bad-arg (args)

; This function is only called when args is known to be a non-arglistp
; that is a true list.  It returns the first bad argument and a string
; that completes the phrase "... violates the rules because it ...".

  (declare (xargs :guard (and (true-listp args)
                              (not (arglistp args)))))
  (cond
   ;;((null args) (mv nil nil)) -- can't happen, given the guard!
   ((not (symbolp (car args))) (mv (car args) "is not a symbol"))
   ((legal-constantp1 (car args))
    (mv (car args) "has the syntax of a constant"))
   ((lambda-keywordp (car args))
    (mv (car args) "is a lambda keyword"))
   ((keywordp (car args))
    (mv (car args) "is in the KEYWORD package"))
   ((member-eq (car args) *common-lisp-specials-and-constants*)
    (mv (car args) "belongs to the list *common-lisp-specials-and-constants* ~
                    of symbols from the main Lisp package"))
   ((member-eq (car args) (cdr args))
    (mv (car args) "occurs more than once in the list"))
   ((and (equal (symbol-package-name (car args)) *main-lisp-package-name*)
         (not (member-eq (car args) *common-lisp-symbols-from-main-lisp-package*)))
    (mv (car args) "belongs to the main Lisp package but not to the list ~
                    *common-lisp-symbols-from-main-lisp-package*"))
   (t (find-first-bad-arg (cdr args)))))

(defun process-defabbrev-declares (decls)
  (cond ((endp decls) ())

; Here we do a cheap check that the declare form is illegal.  It is tempting to
; use collect-declarations, but it take state.  Anyhow, there is no soundness
; issue; the user will just be a bit surprised when the error shows up later as
; the macro defined by the defabbrev is applied.

        ((not (and (consp (car decls))
                   (eq (caar decls) 'DECLARE)
                   (true-list-listp (cdar decls))
                   (subsetp-eq (strip-cars (cdar decls))
                               '(IGNORE TYPE))))
         (er hard 'process-defabbrev-declares
             "In a DEFABBREV form, each expression after the argument list ~
              but before the body must be of the form (DECLARE decl1 .. ~
              declk), where each dcli is of the form (IGNORE ..) or (TYPE ~
              ..).  The form ~x0 is thus illegal."
             (car decls)))
        (t
         (cons (kwote (car decls))
               (process-defabbrev-declares (cdr decls))))))

(defmacro defabbrev (fn args &rest body)
  ":Doc-Section Events
  a convenient form of macro definition for simple expansions~/
  ~bv[]
  Examples:
  (defabbrev snoc (x y) (append y (list x)))
  (defabbrev sq (x) (declare (type (signed-byte 8) x)) (* x x))

  General Form:
  (defabbrev name (v1 ... vn) doc-string decl1 ... declk body)
  ~ev[]
  where ~c[name] is a new function symbol, the ~c[vi] are distinct
  variable symbols, and ~c[body] is a term.  The ~c[decli], if supplied,
  should be legal ~c[declare] forms; ~pl[declare].  ~c[Doc-string] is
  an optional ~il[documentation] string; ~pl[doc-string].

  Roughly speaking, the ~c[defabbrev] event is akin to defining
  ~c[f] so that ~c[(f v1 ... vn) = body].  But rather than do this
  by adding a new axiom, ~c[defabbrev] defines ~c[f] to be a macro
  so that ~c[(f a1 ... an)] expands to ~c[body], with the ``formals,''
  ~c[vi], replaced by the ``actuals,'' ~c[ai].~/

  For example, if ~c[snoc] is defined as shown in the first example
  above, then ~c[(snoc (+ i j) temp)] is just an abbreviation for
  ~bv[]
  (append temp (list (+ i j))).
  ~ev[]

  In order to generate efficiently executable Lisp code,
  the macro that ~c[defabbrev] introduces uses a ~ilc[let] to
  bind the ``formals'' to the ``actuals.''  Consider the second
  example above.  Logically speaking, ~c[(sq (ack i j))] is an
  abbreviation for ~c[(* (ack i j) (ack i j))].  But in fact
  the macro for ~c[sq] introduced by ~c[defabbrev] actually
  arranges for ~c[(sq (ack i j))] to expand to:
  ~bv[]
  (let ((x (ack i j)))
    (* x x))
  ~ev[]
  which executes more efficiently than ~c[(* (ack i j) (ack i j))].

  In the theorem prover, the ~c[let] above expands to
  ~bv[]
  ((lambda (x) (* x x)) (ack i j))
  ~ev[]
  and thence to ~c[(* (ack i j) (ack i j))].

  It is important to note that the term in ~c[body] should not contain a
  call of ~c[name] ~-[] i.e., ~c[defabbrev] should not be used in place of
  ~c[defun] when the function is recursive.  ACL2 will not complain when
  the ~c[defabbrev] form is processed, but instead ACL2 will more than
  likely go into an infinite loop during macroexpansion of any form that
  has a call of ~c[name].

  It is also important to note that the parameters of any call of a
  macro defined by defabbrev will, as is the case for the parameters
  of a function call, be evaluated before the body is evaluated, since
  this is the evaluation order of ~ilc[let].  This may lead to some
  errors or unexpected inefficiencies during evaluation if the body
  contains any conditionally evaluted forms like ~c[cond], ~c[case],
  or ~c[if].  Consider the following example.
  ~bv[]
  (defabbrev foo (x y)
    (if (test x) (bar y) nil))
  ~ev[]
  Notice a typical one-step expansion of a call of ~c[foo]
  (~pl[trans1]):
  ~bv[]
  ACL2 !>:trans1 (foo expr1 expr2)
   (LET ((X EXPR1) (Y EXPR2))
        (IF (TEST X) (BAR Y) NIL))
  ACL2 !>
  ~ev[]
  Now imagine that ~c[expr2] is a complicated expression whose
  evaluation is intended only when the predicate ~c[test] holds of
  ~c[expr1].  The expansion above suggests that ~c[expr2] will always
  be evaluated by the call ~c[(foo expr1 expr2)], which may be
  inefficient (since perhaps we only need that value when ~c[test] is
  true of ~c[expr1]).  The evaluation of ~c[expr2] may even cause an
  error, for example in ~c[:]~ilc[program] mode if the expression ~c[expr2] has
  been constructed in a manner that could cause a guard violation
  unless ~c[test] holds of ~c[expr1]."

  (cond ((null body)
         (er hard (cons 'defabbrev fn)
             "The body of this DEFABBREV form is missing."))
        ((not (true-listp args))
         (er hard (cons 'defabbrev fn)
             "The formal parameter list for a DEFABBREV must be a true list.  The ~
              argument list ~x0 is thus illegal."
             args))
        ((not (arglistp args))
         (mv-let (culprit explan)
                 (find-first-bad-arg args)
                 (er hard (cons 'defabbrev fn)
                     "The formal parameter list for a DEFABBREV must be a ~
                      list of distinct variables, but ~x0 does not meet these ~
                      conditions.  The element ~x1 ~@2."
                     args culprit explan)))
        (t 
         (mv-let (doc-string-list body)
                 (if (and (stringp (car body))
                          (cdr body))
                     (mv (list (car body)) (cdr body))
                   (mv nil body))
                 (cond ((null body)
                        (er hard (cons 'defabbrev fn)
                            "This DEFABBREV form has a doc string but no ~
                             body."))
                       ((and (consp (car (last body)))
                             (eq (caar (last body)) 'declare))
                        (er hard (cons 'defabbrev fn)
                            "The body of this DEFABBREV form is a DECLARE ~
                             form, namely ~x0.  This is illegal and probably ~
                             is not what was intended."
                            (car (last body))))
                       (t
                        `(defmacro ,fn ,args
                           ,@doc-string-list
                           (list 'let (list ,@(defabbrev1 args))
                                 ,@(process-defabbrev-declares (butlast body 1))
                                 ',(car (last body))))))))))

;; RAG - I changed the primitive guard for the < function, and the
;; complex function.  Added the functions complexp, realp, and floor1.

;; RAG - I subsequently changed this to add the non-standard functions
;; standard-numberp, standard-part and i-large-integer.  I had some
;; questions as to whether these functions should appear on this list
;; or not.  After considering carefully, I decided that was the right
;; course of action.  In addition to adding them to the list below, I
;; also add them to *non-standard-primitives* which is a special list
;; of non-standard primitives.  Functions in this list are considered
;; to be constrained.  Moreover, they are given the value t for the
;; property 'unsafe-induction so that recursion and induction are
;; turned off for terms built from these functions.

(defconst *primitive-formals-and-guards*

; Keep this in sync with ev-fncall, cons-term1, and type-set-primitive, and
; with the documentation and "-completion" axioms of the primitives.  Also be
; sure to define a *1* function for each function in this list that is not a
; member of *oneify-primitives*.

  '((acl2-numberp (x) 't)
    (bad-atom<= (x y) (if (bad-atom x) (bad-atom y) 'nil))
    (binary-* (x y) (if (acl2-numberp x) (acl2-numberp y) 'nil))
    (binary-+ (x y) (if (acl2-numberp x) (acl2-numberp y) 'nil))
    (unary-- (x) (acl2-numberp x))
    (unary-/ (x) (if (acl2-numberp x) (not (equal x '0)) 'nil))
    (< (x y) 

; We avoid the temptation to use real/rationalp below, since it is a macro.

       (if #+:non-standard-analysis (realp x) 
           #-:non-standard-analysis (rationalp x)
         #+:non-standard-analysis (realp y) 
         #-:non-standard-analysis (rationalp y)
         'nil))
    (car (x) (if (consp x) 't (equal x 'nil)))
    (cdr (x) (if (consp x) 't (equal x 'nil)))
    (char-code (x) (characterp x))
    (characterp (x) 't)
    (code-char (x) (if (integerp x) (if (< x '0) 'nil (< x '256)) 'nil))
    (complex (x y)
             (if #+:non-standard-analysis (realp x) 
                 #-:non-standard-analysis (rationalp x)
               #+:non-standard-analysis (realp y) 
               #-:non-standard-analysis (rationalp y)
               'nil))
    (complex-rationalp (x) 't)
    #+:non-standard-analysis
    (complexp (x) 't)
    (coerce (x y)
            (if (equal y 'list)
                (stringp x)
                (if (equal y 'string)
                    (character-listp x)
                    'nil)))
    (cons (x y) 't)
    (consp (x) 't)
    (denominator (x) (rationalp x))
    (equal (x y) 't)
    #+:non-standard-analysis
    (floor1 (x) (realp x))
    (if (x y z) 't)
    (imagpart (x) (acl2-numberp x))
    (integerp (x) 't)
    (intern-in-package-of-symbol (str sym) (if (stringp str) (symbolp sym) 'nil))
    (numerator (x) (rationalp x))
    (pkg-witness (pkg) (and (stringp pkg) (not (equal pkg ""))))
    (rationalp (x) 't)
    #+:non-standard-analysis
    (realp (x) 't)
    (realpart (x) (acl2-numberp x))
    (stringp (x) 't)
    (symbol-name (x) (symbolp x))
    (symbol-package-name (x) (symbolp x))
    (symbolp (x) 't)
    #+:non-standard-analysis
    (standard-numberp (x) 't)
    #+:non-standard-analysis
    (standard-part (x) (acl2-numberp x))
    #+:non-standard-analysis
    (i-large-integer () 't)))

(defconst *t* (quote (quote t)))

(defconst *true-clause* (list *t*))

(defconst *nil* (quote (quote nil)))

(defconst *0* (quote (quote 0)))

(defconst *1* (quote (quote 1)))

(defconst *-1* (quote (quote -1)))

;; RAG - To keep in sync with *primitive-formals-and-guards*, I
;; changed the primitive guard for the < function, and the complex
;; function.  Added the functions complexp, realp, and floor1.

(defconst *cons-term1-alist*

; Keep this in sync with *primitive-formals-and-guards*.  In particular, every
; fn mentioned in that list must be handled here identically if it is handled
; here at all.  We handle fn = 'NOT here as well, just so that substitution
; functions never create (NOT 'T).  But with the exception of NOT, every
; function dealt with here must also appear in *primitive-formals-and-guards*.
; It is legal to omit functions here.  For example, we omit bad-atom<= and,
; even with #+:non-standard-analysis, we omit i-large-integer, because there is
; no legal ACL2 evg to which these evaluate.

  '((acl2-numberp (kwote (acl2-numberp x)))
    (binary-* (kwote (* (fix x)
                        (fix y))))
    (binary-+ (kwote (+ (fix x)
                        (fix y))))
    (unary-- (kwote (- (fix x))))
    (unary-/ (cond ((and (acl2-numberp x) (not (equal x 0)))
                    (kwote (/ x)))
                   (t *0*)))
    (< (cond ((and (real/rationalp x) (real/rationalp y))
              (kwote (< x y)))
             (t (kwote (let ((x (fix x))
                             (y (fix y)))
                         (or (< (realpart x)
                                (realpart y))
                             (and (= (realpart x)
                                     (realpart y))
                                  (< (imagpart x)
                                     (imagpart y)))))))))
    (car (cond ((consp x)
                (kwote (car x)))
               (t *nil*)))
    (cdr (cond ((consp x)
                (kwote (cdr x)))
               (t *nil*)))
    (char-code (cond ((characterp x)
                      (kwote (char-code x)))
                     (t *0*)))
    (characterp (kwote (characterp x)))
    (code-char (cond ((and (integerp x) (<= 0 x) (< x 256))
                      (kwote (code-char x)))
                     (t (kwote (code-char 0)))))
    (complex (kwote (complex (if (real/rationalp x) x 0)
                             (if (real/rationalp y) y 0))))
    (complex-rationalp (kwote (complex-rationalp x)))
    #+:non-standard-analysis
    (complexp (kwote (complexp x)))
    (coerce (cond ((equal y 'list)
                   (if (stringp x)
                       (kwote (coerce x 'list))
                     *nil*))
                  ((character-listp x)
                   (kwote (coerce x 'string)))
                  (t (kwote (coerce (make-character-list x) 'string)))))
    (cons (kwote (cons x y)))
    (consp (kwote (consp x)))
    (denominator (cond ((rationalp x)
                        (kwote (denominator x)))
                       (t *1*)))
    (equal (kwote (equal x y)))
    #+:non-standard-analysis
    (floor1 (kwote (floor x 1)))
    (if (kwote (if x y (cadr (caddr args)))))
    (imagpart (cond ((complex-rationalp x) ; could be acl2-numberp
                     (kwote (imagpart x)))
                    (t *0*)))
    (integerp (kwote (integerp x)))
    (intern-in-package-of-symbol
     (cond ((and (stringp x)
                 (symbolp y))
            (kwote (intern-in-package-of-symbol x y)))
           (t *nil*)))
    (numerator (cond ((rationalp x)
                      (kwote (numerator x)))
                     (t *0*)))

; We need to obtain (known-package-alist state) in order to evaluate
; pkg-witness, so we do not give it any special treatment.

    (rationalp (kwote (rationalp x)))
    #+:non-standard-analysis
    (realp (kwote (realp x)))
    (realpart (cond ((acl2-numberp x)
                     (kwote (realpart x)))
                    (t *0*)))
    (stringp (kwote (stringp x)))
    (symbol-name (cond ((symbolp x)
                        (kwote (symbol-name x)))
                       (t (kwote ""))))
    (symbol-package-name
     (cond ((symbolp x)
            (kwote (symbol-package-name x)))
           (t (kwote ""))))
    (symbolp (kwote (symbolp x)))
    #+:non-standard-analysis
    (standard-numberp (kwote (acl2-numberp x)))
    #+:non-standard-analysis
    (standard-part (cond ((acl2-numberp x)
                          (kwote x))
                         (t *0*)))
    (not (kwote (not x)))))

(defmacro cons-term2-body ()
  `(let ((x (cadr (car args)))
         (y (cadr (cadr args))))
     (case fn
       ,@*cons-term1-alist*
       (otherwise (cons fn args)))))

(defun cons-term2 (fn args)
  (cons-term2-body))

(defmacro cons-term1 (fn args)
  (or (and (consp fn)
           (eq (car fn) 'quote)
           (symbolp (cadr fn))
           (let ((expr (cadr (assoc-eq (cadr fn) *cons-term1-alist*))))
             (if expr
                 `(let* ((args ,args)
                         (x (cadr (car args)))
                         ,@(and (cdr (cadr (assoc-eq
                                            (cadr fn)
                                            *primitive-formals-and-guards*)))
                                '((y (cadr (cadr args))))))
                    ,expr)
               `(cons ,fn ,args))))
      `(cons-term2 ,fn ,args)))

(defun quote-listp (l)
  (declare (xargs :guard (true-listp l)))
  (cond ((null l) t)
        (t (and (quotep (car l))
                (quote-listp (cdr l))))))

(defun cons-term (fn args)
  (cond ((quote-listp args)
         (cons-term1 fn args))
        (t (cons fn args))))

(defmacro cons-term* (fn &rest args)
  `(cons-term ,fn (list ,@args)))

(defmacro mcons-term (fn args)

; The "m" in "mcons-term" is for "maybe fast".  Some calls of this macro can
; probably be replaced with fcons-term.

  `(cons-term ,fn ,args))

(defmacro mcons-term* (fn &rest args)

; The "m" in "mcons-term*" is for "maybe fast".  Some of calls of this macro
; can probably be replaced with fcons-term*.

  `(cons-term* ,fn ,@args))

(defmacro fcons-term* (&rest x)

#|
; Start experimental code mod, to check that calls of fcons-term are legitimate
; shortcuts in place of the corresponding known-correct calls of cons-term.
  #-acl2-loop-only
  `(let* ((fn-used-only-in-fcons-term* ,(car x))
          (args-used-only-in-fcons-term* (list ,@(cdr x)))
          (result (cons fn-used-only-in-fcons-term*
                        args-used-only-in-fcons-term*)))
     (assert$ (equal result (cons-term fn-used-only-in-fcons-term*
                                       args-used-only-in-fcons-term*))
              result))
  #+acl2-loop-only
; End experimental code mod.
|#

  (cons 'list x))

(defmacro fcons-term (fn args)

#|
; Start experimental code mod, to check that calls of fcons-term are legitimate
; shortcuts in place of the corresponding known-correct calls of cons-term.
  #-acl2-loop-only
  `(let* ((fn-used-only-in-fcons-term ,fn)
          (args-used-only-in-fcons-term ,args)
          (result (cons fn-used-only-in-fcons-term
                        args-used-only-in-fcons-term)))
     (assert$ (equal result (cons-term fn-used-only-in-fcons-term
                                       args-used-only-in-fcons-term))
              result))
  #+acl2-loop-only
; End experimental code mod.
|#

  (list 'cons fn args))

(defun fargn1 (x n)
  (declare (xargs :guard (and (integerp n)
                              (> n 0))))
  (cond ((eql n 1) (list 'cdr x))
        (t (list 'cdr (fargn1 x (- n 1))))))

(defmacro fargn (x n)
  (list 'car (fargn1 x n)))

(defun cdr-nest (n v)
  (cond ((equal n 0) v)
        (t (fargn1 v n))))

(defun all-but-last (l)
  (cond ((endp l) nil)
        ((endp (cdr l)) nil)
        (t (cons (car l) (all-but-last (cdr l))))))

(defun equal-x-constant (x const)

; x is an arbitrary term, const is a quoted constant, e.g., a list of
; the form (QUOTE guts).  We return a term equivalent to (equal x
; const).

  (let ((guts (cadr const)))
    (cond ((symbolp guts)
           (list 'eq x const))
          ((or (acl2-numberp guts)
               (characterp guts))
           (list 'eql x guts))
          ((stringp guts)
           (list 'equal x guts))
          (t (list 'equal x const)))))

(defun match-tests-and-bindings (x pat tests bindings)

; We return two results.  The first is a list of tests, in reverse
; order, that determine whether x matches the structure pat.  We
; describe the language of pat below.  The tests are accumulated onto
; tests, which should be nil initially.  The second result is an alist
; containing entries of the form (sym expr), suitable for use as the
; bindings in the let we generate if the tests are satisfied.  The
; bindings required by pat are accumulated onto bindings and thus are
; reverse order, although their order is actually irrelevant.

; For example, the pattern
;   ('equal ('car ('cons u v)) u)
; matches only first order instances of (EQUAL (CAR (CONS u v)) u).

; The pattern
;   ('equal (ev (simp x) a) (ev x a))
; matches only second order instances of (EQUAL (ev (simp x) a) (ev x a)),
; i.e., ev, simp, x, and a are all bound in the match.

; In general, the match requires that the cons structure of x be isomorphic
; to that of pat, down to the atoms in pat.  Symbols in the pat denote
; variables that match anything and get bound to the structure matched.
; Occurrences of a symbol after the first match only structures equal to
; the binding.  Non-symbolp atoms match themselves.

; There are some exceptions to the general scheme described above.  A
; cons structure starting with QUOTE matches only itself.  The symbols
; nil and t, and all symbols whose symbol-name starts with #\* match
; only structures equal to their values.  (These symbols cannot be
; legally bound in ACL2 anyway, so this exceptional treatment does not
; restrict us further.)  Any symbol starting with #\! matches only the
; value of the symbol whose name is obtained by dropping the #\!.
; This is a way of referring to already bound variables in the
; pattern.  Finally, the symbol & matches anything and causes no
; binding.

  (cond
   ((symbolp pat)
    (cond
     ((or (eq pat t)
          (eq pat nil))
      (mv (cons (list 'eq x pat) tests) bindings))
     ((and (> (length (symbol-name pat)) 0)
           (eql #\* (char (symbol-name pat) 0)))
      (mv (cons (list 'equal x pat) tests) bindings))
     ((and (> (length (symbol-name pat)) 0)
           (eql #\! (char (symbol-name pat) 0)))
      (mv (cons (list 'equal x
                      (intern (coerce (cdr (coerce (symbol-name pat)
                                                   'list))
                                      'string)
                              "ACL2"))
                tests)
          bindings))
     ((eq pat '&) (mv tests bindings))
     (t (let ((binding (assoc-eq pat bindings)))
          (cond ((null binding)
                 (mv tests (cons (list pat x) bindings)))
                (t (mv (cons (list 'equal x (cadr binding)) tests)
                       bindings)))))))
   ((atom pat)
    (mv (cons (equal-x-constant x (list 'quote pat)) tests)
        bindings))
   ((eq (car pat) 'quote)
    (mv (cons (equal-x-constant x pat) tests)
        bindings))
   (t (mv-let (tests1 bindings1)
        (match-tests-and-bindings (list 'car x) (car pat)
                                  (cons (list 'consp x) tests)
                                  bindings)
        (match-tests-and-bindings (list 'cdr x) (cdr pat)
                                  tests1 bindings1)))))

(defun match-clause (x pat forms)
  (mv-let (tests bindings)
    (match-tests-and-bindings x pat nil nil)
    (list (if (null tests)
              t
            (cons 'and (reverse tests)))
          (cons 'let (cons (reverse bindings) forms)))))

(defun match-clause-list (x clauses)
  (cond ((consp clauses)
         (if (eq (caar clauses) '&)
             (list (match-clause x (caar clauses) (cdar clauses)))
           (cons (match-clause x (caar clauses) (cdar clauses))
                 (match-clause-list x (cdr clauses)))))
        (t '((t nil)))))

(defmacro case-match (&rest args)
  (declare (xargs :guard (and (consp args)
                              (symbolp (car args))
                              (alistp (cdr args))
                              (null (cdr (member-equal (assoc-eq '& (cdr args))
                                                       (cdr args)))))))
  ":Doc-Section ACL2::Programming

  pattern matching or destructuring~/
  ~bv[]
  General Form:
  (case-match x
    (pat1 dcl1 body1)
    ...
    (patk dclk bodyk))
  ~ev[]
  where ~c[x] is a variable symbol, the ~c[pati] are structural patterns
  as described below, the ~c[dcli] are optional ~ilc[declare] forms and
  the ~c[bodyi] are terms.  Return the value(s) of the ~c[bodyi]
  corresponding to the first ~c[pati] matching ~c[x], or ~c[nil] if none
  matches.

  Pattern Language:~nl[]
  With the few special exceptions described below, matching requires
  that the ~ilc[cons] structure of ~c[x] be isomorphic to that of the
  pattern, down to the ~il[atom]s in the pattern.  Non-symbol ~il[atom]s in the
  pattern match only themselves.  Symbols in the pattern denote
  variables which match anything and which are bound by a successful
  match to the corresponding substructure of ~c[x].  Variables that
  occur more than once must match the same (~ilc[EQUAL]) structure in
  every occurrence.
  ~bv[]
  Exceptions:
  &               Matches anything and is not bound.  Repeated
                    occurrences of & in a pattern may match different
                    structures.
  nil, t, *sym*   These symbols cannot be bound and match only their
                    global values.
  !sym            where sym is a symbol that is already bound in the
                    context of the case-match, matches only the
                    current binding of sym.
  'obj            Matches only itself.
  ~ev[]
  Some examples are shown below.~/

  Below we show some sample patterns and examples of things they match
  and do not match.
  ~bv[]  
  pattern       matches         non-matches
  (x y y)       (ABC 3 3)       (ABC 3 4)    ; 3 is not 4
  (fn x . rst)  (P (A I) B C)   (ABC)        ; NIL is not (x . rst)
                (J (A I))                    ; rst matches nil
  ('fn (g x) 3) (FN (H 4) 3)    (GN (G X) 3) ; 'fn matches only itself
  (& t & !x)    ((A) T (B) (C))              ; provided x is '(C)
  ~ev[]                                
  Consider the two binary trees that contain three leaves.  They might
  be described as ~c[(x . (y . z))] and ~c[((x . y) . z)], where ~c[x],
  ~c[y], and ~c[z] are atomic.  Suppose we wished to recognize those
  trees.  The following ~c[case-match] would do:
  ~bv[]
  (case-match tree
    ((x . (y . z))
     (and (atom x) (atom y) (atom z)))
    (((x . y) . z)
     (and (atom x) (atom y) (atom z))))
  ~ev[]
  Suppose we wished to recognize such trees where all three tips are
  identical.  Suppose further we wish to return the tip if the tree is
  one of those recognized ones and to return the number ~c[7] otherwise.
  ~bv[]
  (case-match tree
    ((x . (x . x))
     (if (atom x) x 7))
    (((x . x) . x)
     (if (atom x) x 7))
    (& 7))
  ~ev[]
  Note that ~c[case-match] returns ~c[nil] if no ~c[pati] matches.  Thus if we
  must return ~c[7] in that case, we have to add as the final pattern the
  ~c[&], which always matches anything."
  (cons 'cond (match-clause-list (car args) (cdr args))))

; Essay on Evisceration

; We have designed the pretty printer so that it can print an
; "eviscerated" object, that is, an object that has had certain
; substructures removed.  We discuss the prettyprinter in the Essay on
; the ACL2 Prettyprinter.  The pretty printer has a flag, eviscp,
; which indicates whether the object has been eviscerated or not.  If
; not, then the full object is printed as it stands.  If so, then
; certain substructures of it are given special interpretation by the
; printer.  In particular, when the printer encounters a cons of the
; form (:evisceration-mark . x) then x is a string and the cons is
; printed by printing the characters in x (without the double
; gritches).

;     object                            pretty printed output
; (:evisceration-mark . "#")                     #
; (:evisceration-mark . "...")                   ...
; (:evisceration-mark . "<state>")               <state>
; (:evisceration-mark . ":EVISCERATION-MARK")    :EVISCERATION-MARK

; So suppose you have some object and you want to print it, implementing
; the CLTL conventions for *print-level* and *print-length*.  Then you
; must first scan it, inserting :evisceration-mark forms where
; appropriate.  But what if it contains some occurrences of
; :evisceration-mark?  Then you must use evisceration mechanism to print
; them correctly!  Once you have properly eviscerated the object, you can
; call the prettyprinter on it, telling it that the object has been
; eviscerated.  If, on the other hand, you don't want to eviscerate it,
; then you needn't sweep it to protect the native :evisceration-marks:
; just call the prettyprinter with the eviscp flag off.

(defconst *evisceration-mark* :evisceration-mark)

; Note: It is important that the evisceration-mark be a keyword.
; One reason is that (:evisceration-mark . ":EVISCERATION-MARK")
; couldn't be used to print a non-keyword because the package might
; need to be printed.  Another is that we exploit the fact that no
; event name nor any formal is *evisceration-mark*.  See
; print-ldd-full-or-sketch.  Furthermore, if the particular keyword
; chosen is changed, alter *anti-evisceration-mark* below!

(defconst *evisceration-hash-mark* (cons *evisceration-mark* "#"))
(defconst *evisceration-ellipsis-mark* (cons *evisceration-mark* "..."))
(defconst *evisceration-world-mark*
  (cons *evisceration-mark* "<world>"))
(defconst *evisceration-state-mark*
  (cons *evisceration-mark* "<state>"))
(defconst *evisceration-error-triple-marks*
  (list nil nil *evisceration-state-mark*))
(defconst *evisceration-hiding-mark*
  (cons *evisceration-mark* "<hidden>"))

(defconst *anti-evisceration-mark*
  (cons *evisceration-mark* ":EVISCERATION-MARK"))

(defmacro evisceratedp (eviscp x)
; Warning:  The value of x should be a consp.
  `(and ,eviscp (eq (car ,x) *evisceration-mark*)))

; We now define the most elementary eviscerator, the one that implements
; *print-level* and *print-length*.  In this same pass we also arrange to
; hide any object in alist, where alist pairs objects with their
; evisceration strings -- or if not a string, with the appropriate
; evisceration pair.

(mutual-recursion

(defun eviscerate1 (x v max-v max-n alist hiding-cars)
  (let ((temp (assoc-equal x alist)))
    (cond (temp
           (cond ((stringp (cdr temp))
                  (cons *evisceration-mark* (cdr temp)))
                 (t (cdr temp))))
          ((atom x)
           (cond ((eq x *evisceration-mark*) *anti-evisceration-mark*)
                 (t x)))
          ((= v max-v) *evisceration-hash-mark*)
          ((member-eq (car x) hiding-cars) *evisceration-hiding-mark*)
          (t (eviscerate1-lst x (1+ v) 0 max-v max-n alist hiding-cars)))))

(defun eviscerate1-lst (lst v n max-v max-n alist hiding-cars)
  (let ((temp (assoc-equal lst alist)))
    (cond
     (temp
      (cond ((stringp (cdr temp))
             (cons *evisceration-mark* (cdr temp)))
            (t (cdr temp))))
     ((atom lst)
      (cond ((eq lst *evisceration-mark*) *anti-evisceration-mark*)
            (t lst)))
     ((= n max-n) (list *evisceration-ellipsis-mark*))
     (t (cons (eviscerate1 (car lst) v max-v max-n alist hiding-cars)
              (eviscerate1-lst (cdr lst) v (1+ n)
                               max-v max-n alist hiding-cars))))))
)

(mutual-recursion

(defun eviscerate1p (x alist hiding-cars)

; This function returns t iff (eviscerate1 x 0 -1 -1 alist hidep)
; returns something other than x.  That is, iff the evisceration of x
; either uses alist, hiding or the *anti-evisceration-mark* (assuming
; that print-level and print-length never max out).

  (let ((temp (assoc-equal x alist)))
    (cond (temp t)
          ((atom x)
           (cond ((eq x *evisceration-mark*) t)
                 (t nil)))
          ((member-eq (car x) hiding-cars) t)
          (t (eviscerate1p-lst x alist hiding-cars)))))

(defun eviscerate1p-lst (lst alist hiding-cars)
  (let ((temp (assoc-equal lst alist)))
    (cond (temp t)
          ((atom lst)
           (cond ((eq lst *evisceration-mark*) t)
                 (t nil)))
          (t (or (eviscerate1p (car lst) alist hiding-cars)
                 (eviscerate1p-lst (cdr lst) alist hiding-cars))))))
)

(defun eviscerate (x print-level print-length alist hiding-cars)

; Print-level and print-length should either be non-negative integers
; or nil.  Alist is an alist pairing arbitrary objects to strings or
; other objects.  Hiding-cars is a list of symbols.  Any x that starts
; with one of these symbols is printed as <hidden>.  If alist pairs an
; object with a string, the string is printed in place of the object.
; If alist pairs an object with anything else, x, then x is
; substituted for the the object and is treated as eviscerated.

; This function copies the structure x and replaces certain deep
; substructures with evisceration marks.  The determination of which
; substructures to so abbreviate is based on the same algorithm used
; to define *print-level* and *print-length* in CLTL, with the
; additional identification of all occurrences of any object in alist.

; For example, if x is '(if (member x y) (+ (car x) 3) '(foo . b)) and
; print-level is 2 and print-length is 3 then the output is:

; (IF (MEMBER X Y)
;     (+ (*evisceration-mark* . "#") 3)
;     (*evisceration-mark* . "..."))

; See pg 373 of CLTL.

; Of course we are supposed to print this as:

; (IF (MEMBER X Y) (+ # 3) ...)

; We consider a couple of special cases to reduce unnecessary consing
; of eviscerated values.

  (cond ((and (null print-level)
              (null print-length))

; Warning: Observe that even if alist is nil, x might contain the
; *evisceration-mark* or hiding expressions and hence have a
; non-trivial evisceration

         (cond ((eviscerate1p x alist hiding-cars)
                (eviscerate1 x 0 -1 -1 alist hiding-cars))
               (t x)))
        (t (eviscerate1 x 0
                        (or print-level -1)
                        (or print-length -1)
                        alist
                        hiding-cars))))

(defun world-evisceration-alist (state alist)
  (cons (cons (w state) *evisceration-world-mark*)
        alist))

(defun stobj-print-name (name)
  (coerce
   (cons #\<
         (append (string-downcase1 (coerce (symbol-name name) 'list))
                 '(#\>)))
   'string))

(defun evisceration-stobj-mark (name inputp)

; NAME is a stobj name.  We return an evisceration mark that prints as
; ``<name>''.  We make a special case out of STATE.

  (cond
   (inputp name)
   ((eq name 'STATE)
    *evisceration-state-mark*)
   (t
    (cons *evisceration-mark* (stobj-print-name name)))))

(defun evisceration-stobj-marks1 (stobjs-flags inputp)

; See the comment in eviscerate-stobjs, below.

  (cond ((null stobjs-flags) nil)
        ((car stobjs-flags)
         (cons (evisceration-stobj-mark (car stobjs-flags) inputp)
               (evisceration-stobj-marks1 (cdr stobjs-flags) inputp)))
        (t
         (cons nil
               (evisceration-stobj-marks1 (cdr stobjs-flags) inputp)))))

(defun evisceration-stobj-marks (stobjs-flags inputp)
  (cond ((equal stobjs-flags '(nil nil state))
         (if inputp
             '(nil nil state)
           *evisceration-error-triple-marks*))
        ((equal stobjs-flags '(nil)) '(nil))
        (t (evisceration-stobj-marks1 stobjs-flags inputp))))

(defun eviscerate-stobjs1 (estobjs-out lst print-level print-length
                                       alist hiding-cars)
  (cond
   ((null estobjs-out) nil)
   ((car estobjs-out)
    (cons (car estobjs-out)
          (eviscerate-stobjs1 (cdr estobjs-out) (cdr lst)
                              print-level print-length
                              alist hiding-cars)))
   (t
    (cons (eviscerate (car lst) print-level print-length
                      alist hiding-cars)
          (eviscerate-stobjs1 (cdr estobjs-out) (cdr lst)
                              print-level print-length
                              alist hiding-cars)))))
                                                    
(defun eviscerate-stobjs (estobjs-out lst print-level print-length
                                      alist hiding-cars)

; Warning: Right now, we abbreviate all stobjs with the <name>
; convention.  I have toyed with the idea of allowing the user to
; specify how a stobj is to be abbreviated on output.  This is
; awkward.  See the Essay on Abbreviating Live Stobjs below.

; We wish to eviscerate lst with the given print-level, etc., but
; respecting stobjs that we may find in lst.  Estobjs-out describes
; the shape of lst as a multiple value vector: if estobjs-out is of
; length 1, then lst is the single result; otherwise, lst is a list of
; as many elements as estobjs-out is long.  The non-nil elements of
; stobjs name the stobjs in lst -- EXCEPT that unlike an ordinary
; ``stobjs-out'', the elements of estobjs-out are evisceration marks
; we are to ``print!''  For example corresponding to the stobjs-out
; setting of '(NIL $MY-STOBJ NIL STATE) is the estobjs-out

; '(NIL
;   (:EVISCERATION-MARK . "<$my-stobj>")
;   NIL
;   (:EVISCERATION-MARK . "<state>"))

; Here, we assume *evisceration-mark* is :EVISCERATION-MARK.

  (cond
   ((null estobjs-out)

; Lst is either a single non-stobj output or a list of n non-stobj
; outputs.  We eviscerate it without regard for stobjs.

    (eviscerate lst print-level print-length alist hiding-cars))

   ((null (cdr estobjs-out))

; Lst is a single output, which is either a stobj or not depending on
; whether (car stobjs-out) is non-nil.

    (cond
     ((car estobjs-out) (car estobjs-out))
     (t (eviscerate lst print-level print-length alist hiding-cars))))
   

   (t (eviscerate-stobjs1 estobjs-out lst print-level print-length
                          alist hiding-cars))))

; Essay on Abbreviating Live Stobjs

; Right now the live state is abbreviated as <state> when it is
; printed, and the user's live stobj $s is abbreviated as <$s>.  It
; would be cool if the user could specify how he or she wants a stobj
; displayed, e.g., by selecting key components for printing or by
; providing a function which maps the stobj to some non-stobj
; ``stand-in'' or eviscerated object for printing.

; I have given this matter several hours' thought and abandoned it for
; the moment.  I am not convinced it is worth the trouble.  It IS a
; lot of trouble.

; We eviscerate stobjs in two main places, a very low-level place:
; ev-fncall-msg (and its more pervasive friend, ev-fncall-guard-er)
; and in a very high level place: ld-print-results.  The low-level
; place is used to print stobjs involved in calls of functions on args
; that violate a guard.  The high-level place is the ``print'' in the
; read-eval-print loop.

; Every stobj must have some ``stand-in transformer'' function, fn.
; We will typically be holding a stobj name, e.g., $S, and a live
; value, val, e.g., (#(777) #(1 2 3 ...)), and wish to obtain some
; ACL2 object to print in place of the value.  This value is obtained
; by applying fn to val.  The two main issues I see are

; (a) where do we find fn?  The candidate places are state, world, and
; val itself.  But we do not have state available in the low-level
; code.

; (b) how do we apply fn to val?  The obvious thing is to call
; trans-eval or do an ev-fncall.  Again, we need state.  Furthermore,
; depending on how we do it, we have to fight a syntactic battle of
; ``casting'' an arbitrary object, val, to a stobj of type name, to
; apply a function which has a STOBJS-IN of (name).  A more important
; problem is the one of order-of-definition.  Which is defined first:
; how to eviscerate a stobj or how to evaluate a form?  Stobj
; evisceration calls evaluation to apply fn, but evaluation calls
; stobj evisceration to report guard errors.

; Is user-specified stobj abbreviation really worth the trouble?

; One idea that presents itself is that val ``knows how to abbreviate
; itself.''  I think this is akin to the idea of having a :program
; mode function, say stobj-standin, which syntactically takes a
; non-stobj and returns a non-stobj.  Actually, stobj-standin would be
; called on val.  It is clear that I could define this function in raw
; lisp: look in *the-live-state* to determine how to abbreviate val
; and then just do it.  But what would be the logical definition of
; it?  We could leave it undefined, or defined to be an undefined
; function.  Until we admit the whole ACL2 system :logically, we could
; even define it in the logic to be t even though it really returned
; something else, since as a :program its logical definition is
; irrelevant.  But at the moment I don't think ACL2 has a precedent
; for such a function and I don't think user-specified stobj
; abbreviation is justification enough for doing it.


; Now we lay down some macros that help with the efficiency of the FMT
; functions, by making it easy to declare various formals and function
; values to be fixnums.  To the best of our knowledge, the values of
; most-positive-fixnum in various lisps are as follows, so we feel
; safe in using (signed-byte 29) to represent fixnums.  At worst, if a
; lisp is used for which (signed-byte 29) is not a subtype of fixnum,
; a compiler may simply fail to create efficient code.

; Values of most-positive-fixnum.
; AKCL, GCL: 2147483647
; Allegro:    536870911
; Lucid:      536870911
; cmulisp:    536870911
; SBCL:       536870911
; OpenMCL:    536870911
; MCL:        268435455
; CLISP:       16777215
; Lispworks:    8388607 [4.2.0; formerly 536870911]

(defmacro mv-letc (vars form body)
  `(mv-let ,vars ,form
           (declare (type (signed-byte 29) col))
           ,body))

(defmacro fixnum-bound ()
  (1- (expt 2 28)))

(defmacro er-hard-val (val &rest args)

; Use (er-hard-val val ctx str ...) instead of (er hard ctx str ...)
; when there is an expectation on the return type, which should be the
; type of val.  Compilation with the cmulisp compiler produces many
; warnings if we do not use some such device.

  `(prog2$ (er hard ,@args)
           ,val))

(defmacro the-fixnum! (n ctx)

; See also the-half-fixnum!.

  (let ((upper-bound (fixnum-bound)))
    (declare (type (signed-byte 29) upper-bound))
    (let ((lower-bound (- (1+ upper-bound))))
      (declare (type (signed-byte 29) lower-bound))
      `(the-fixnum
        (let ((n ,n))
          (if (and (<= n ,upper-bound)
                   (>= n ,lower-bound))
              n
            (er-hard-val 0 ,ctx
                         "The object ~x0 is not a fixnum ~
                          (precisely:  not a (signed-byte 29))."
                         n)))))))

(defmacro the-half-fixnum! (n ctx)

; Same as the-fixnum!, but leaves some room.

  (let ((upper-bound (floor (fixnum-bound) 2))) ; (1- (expt 2 27))
    (declare (type (signed-byte 28) upper-bound))
    (let ((lower-bound (- (1+ upper-bound))))
      (declare (type (signed-byte 28) lower-bound))
      `(the-fixnum
        (let ((n ,n))
          (if (and (<= n ,upper-bound)
                   (>= n ,lower-bound))
              n
            (er-hard-val 0 ,ctx
                         "The object ~x0 is not a `half-fixnum' ~
                          (precisely:  not a (signed-byte 28))."
                         n)))))))

(defmacro the-string! (s ctx)
  `(if (stringp ,s)
       (the string ,s)
     (er-hard-val "" ,ctx
                  "Not a string:  ~s0."
                  ,s)))

(defun xxxjoin-fixnum (fn args root)

; This is rather like xxxjoin, but we wrap the-fixnum around all
; arguments.

  (declare (xargs :guard (true-listp args)))
  (if (cdr args)
      (list 'the-fixnum
            (list fn
                  (list 'the-fixnum (car args))
                  (xxxjoin-fixnum fn (cdr args) root)))
    (if args ; one arg
        (list 'the-fixnum (car args))
      root)))

(defmacro +f (&rest args)
  (xxxjoin-fixnum '+ args 0))

(defmacro -f (arg1 &optional arg2)
  (if arg2
      `(the-fixnum (- (the-fixnum ,arg1)
                      (the-fixnum ,arg2)))
    `(the-fixnum (- (the-fixnum ,arg1)))))

(defmacro 1-f (x)
  (list 'the-fixnum
        (list '1- (list 'the-fixnum x))))

(defmacro 1+f (x)
  (list 'the-fixnum
        (list '1+ (list 'the-fixnum x))))

(defmacro charf (s i)
  (list 'the 'character
        (list 'char s i)))

; Essay on the ACL2 Prettyprinter

; The ACL2 prettyprinter is a two pass, linear time, exact
; prettyprinter.  By "exact" we mean that if it has a page of width w
; and a big enough form, it will guarantee to use all the columns,
; i.e., the widest line will end in column w.  The algorithm dates
; from about 1971 -- virtually the same code was in the earliest
; Edinburgh Pure Lisp Theorem Prover.  This approach to prettyprinting
; was invented by Bob Boyer.  Most prettyprinters are quadratic and
; inexact.

; The secret to this method is to make two linear passes, ppr1 and
; ppr2.  The first pass builds a data structure, called a ``ppr
; tuple,'' that tells the second pass how to print.

; Some additional general principles of our prettyprinter are
; (i)    Print flat whenever possible.  
; (ii)   However, don't print flat argument lists of length over 40,
;        they're too hard to parse.
; (iii)  Atoms and eviscerated things (which print like atoms,
;        e.g., `<world>') may be printed on a single line.
; (iv)   But parenthesized expressions should not be printed on
;        a line with any other argument (unless the whole form
;        fits on the line).  Thus we may produce:
;        `(foo (bar a) b c d)'
;        and
;        `(foo a b
;              c d)'
;        But we never produce
;        `(foo (bar a) b
;              c d)'
;        preferring instead
;        `(foo (bar a)
;              b c d)'
;        It is our belief that parenthesized expressions are
;        hard to parse and after doing so the eye tends to miss
;        little atoms (like b above) hiding in their shadows.

; To play with ppr we recommend executing this form:

; (ppr2 (ppr1 x (acl2-print-base) 30 0 state t) 0 *standard-co* state t)

; This will prettyprint x on a page of width 30, assuming that
; printing starts in column 0.  To see the ppr tuple that drives the
; printer, just evaluate the inner ppr1 form,
; (ppr1 x (acl2-print-base) 30 0 state nil).

; The following test macro is handy.  A typical call of the macro
; is

#|(test 15 (foo (bar x) (mum :key1 val1 :key2 :val2)))|#

; Note that x is not evaluated.  If you want to evaluate x and ppr
; the value, use 

#|(testfn 10
          (eviscerate `(foo (bar x)
                            (mum :key1 :val1 :key2 :val2)
                            ',(w state))
                      nil nil ; print-level and print-length
                      (world-evisceration-alist state nil)
                      nil)
          state)|#

; Note that x may be eviscerated, i.e., eviscerated objects in x are
; printed in their short form, not literally.

#|(defun testfn (d x state)
    (declare (xargs :mode :program :stobjs (state)))
    (let ((tuple (ppr1 x (acl2-print-base) d 0 state t)))
      (pprogn
       (fms "~%Tuple: ~x0~%Output:~%" (list (cons #\0 tuple))
            *standard-co* state nil)
       (ppr2 tuple 0 *standard-co* state t)
       (fms "~%" nil *standard-co* state nil))))


  (defmacro test (d x)
    `(testfn ,d ',x state))|#

; Ppr tuples record enough information about the widths of various
; forms so that it can be computed without having to recompute any
; part of it and so that the second pass can print without having to
; count characters.

; A ppr tuple has the form (token n . z).  In the display below, the
; variables ti represent ppr tuples and the variables xi represent
; objects to be printed directly.  Any xi could an eviscerated object,
; a list whose car is the evisceration mark.

; (FLAT n x1 ... xk) - Print the xi, separated by spaces, all on one
;                      line. The total width of output will be n.
;                      Note that k >= 1.  Note also that such a FLAT
;                      represents k objects.  A special case is (FLAT
;                      n x1), which represents one object.  We make
;                      this observation because sometimes (in
;                      cons-ppr1) we `just know' that k=1 and the
;                      reason is: we know the FLAT we're holding
;                      represents a single object.

; (FLAT n x1... . xk)- Print the xi, separated by spaces, with xk
;                      separated by `. ', all on one line.  Here xk
;                      is at atom or an eviscerated object.  

; (FLAT n . xk)      - Here, xk is an atom (or an eviscerated object).
;                      Print a dot, a space, and xk.  The width will
;                      be n.  Note that this FLAT does not actually
;                      represent an object.  That is, no Lisp object
;                      prints as `. xk'.

; Note: All three forms of FLAT are really just (FLAT n . x) where x
; is a possibly improper list and the elements of x (and its final
; cdr) are printed, separated appropriately by spaces or dot.

; (MATCHED-KEYWORD n x1)
;                    - Exactly like (FLAT n x1), i.e., prints x1,
;                      but by virtue of being different from FLAT
;                      no other xi's are ever added.  In this tuple,
;                      x1 is always a keyword and it will appear on
;                      a line by itself.  It's associated value will
;                      appear below it in the column because we tried
;                      to put them on the same line but we did not have
;                      room.

; (DOT 1)            - Print a dot.

; (QUOTE n . t1)     - Print a single-quote followed by pretty-
;                      printing the ppr tuple t1.

; (WIDE n t1 t2 ...) - Here, t1 is a FLAT tuple of width j.  We 
;                      print an open parent, the contents of t1, a
;                      space, and then we prettyprint each of the
;                      remaining ti in a column.  When we're done, we
;                      print a close paren.  The width of the longest
;                      line we will print is n.

; (i n t1 ...)       - We print an open paren, prettyprint t1, then
;                      do a newline.  Then we prettyprint the
;                      remaining ti in the column that is i to the
;                      right of the paren.  We conclude with a close
;                      paren.  The width of the longest line we will
;                      print is n.  We call this an `indent tuple'.

; (KEYPAIR n t1 . t2)- Here, t1 is a FLAT tuple of width j.  We print
;                      t1, a space, and then prettyprint t2.  The
;                      length of the longest line we will print is n.

; The sentences "The length of the longest line we will print is n."
; bears explanation.  Consider

; (FOO (BAR X)
;      (MUMBLE Y)
;      Z)
;|<- 15 chars  ->|
; 123456789012345

; The length of the longest line, n, is 15.  That is, the length of
; the longest line counts the spaces from the start of the printing.
; In the case of a KEYPAIR tuple:

; :KEY (FOO
;       (BAR X)
;       Y)
;|<- 13      ->|

; we count the spaces from the beginning of the keyword.  That is,
; we consider the whole block of text. 

; Below we print test-term in two different widths, and display
; the ppr tuple that drives each of the two printings.

#|
(assign test-term
        '(FFF (GGG (HHH (QUOTE (A . B))))
              (III YYY ZZZ)))
      

(ppr2 (ppr1 (@ test-term) (acl2-print-base) 30 0 state nil) 0 *standard-co*
      state nil)
; =>
(FFF (GGG (HHH '(A . B)))          (WIDE 25 (FLAT 3 FFF)                    
     (III YYY ZZZ))                         (FLAT 20 (GGG (HHH '(A . B))))
                                            (FLAT 14 (III YYY ZZZ)))      
<-          25         ->|

(ppr2 (ppr1 (@ test-term) (acl2-print-base) 20 0 state nil) 0 *standard-co*
      state nil)
; =>
(FFF                               (1 20 (FLAT 3 FFF)          
 (GGG                                    (4 19 (FLAT 3 GGG)            
     (HHH '(A . B)))                           (FLAT 15 (HHH '(A . B))))
 (III YYY ZZZ))                          (FLAT 14 (III YYY ZZZ)))    

<-       20       ->|                    
|#

; The function cons-ppr1, below, is the first interesting function in
; the nest.  We want to build a tuple to print a given list form, like
; a function call.  We basically get the tuple for the car and a list
; of tuples for the cdr and then use cons-ppr1 to combine them.  The
; resulting list of tuples will be embedded in either a WIDE or an
; indent tuple.  Thus, this list of tuples we will create describes a
; column of forms.  The number of items in that column is not necessarily
; the same as the number of arguments of the function call.  For
; example, the term (f a b c) might be prettyprinted as
; (f a
;    b c)
; where b and c are printed flat on a single line.  Thus, the
; three arguments of f end up being described by a list of two
; tuples, one for a and another for b and c.

; To form lists of tuples we just use cons-ppr1 to combine the tuples
; we get for each element.

; Let x and lst be, respectively, a ppr tuple for an element and a
; list of tuples for list of elements.  Think of lst as describing a
; column of forms.  Either x can become another item that column, or
; else x can be incorporated into the first item in that column.  For
; example, suppose x will print as X and lst will print as a column
; containing y1, y2, etc.  Then we have this choice for printing x and
; lst:

; lengthened column          lengthened first row
; x                          x y1
; y1                         y2
; ...                        ...

; We get the `lengthened column' behavior if we just cons x onto lst.
; We get the `lengthened row' behavior if we merge the tuples for x
; and y1.  But we only merge if they both print flat.

; Essay on the Printing of Dotted Pairs and

; It is instructive to realize that we print a dotted pair as though
; it were a list of length 3 and the dot was just a normal argument.

; In the little table below I show, for various values of d, two
; things: the characters output by

; (ppr2 (ppr1 `(xx . yy) (acl2-print-base) d 0 state nil) 0 *standard-co* state
;       nil)

; and the ppr tuple produced by the ppr1 call.
;        
; d         output                 ppr tuple

;        |<-  9  ->|

; 9       (XX . YY)              (FLAT 9 (XX . YY))

; 8       (XX                    (3 8 (FLAT 2 XX) (FLAT 5 . YY))
;            . YY)

; 7       (XX                    (2 7 (FLAT 2 XX) (FLAT 5 . YY))
;           . YY)

; 6       (XX                    (1 6 (FLAT 2 XX) (FLAT 5 . YY))
;          . YY)

; 5       (XX                    (2 5 (FLAT 2 XX) (DOT 1) (FLAT 3 YY))
;           .
;           YY) 

; 4       (XX                    (1 4 (FLAT 2 XX) (DOT 1) (FLAT 3 YY))
;          .
;          YY)

; The fact that the dot is not necessarily connected to (on the same
; line as) the atom following it is the reason we have the (DOT 1)
; tuple.  We have to represent the dot so that its placement is first
; class.  So when we're assembling the tuple for a list, we cdr down
; the list using cons-ppr1 to put together the tuple for the car with
; the tuple for the cdr.  If we reach a non-nil cdr, atm, we call
; cons-ppr1 on the dot tuple and the tuple representing the atm.
; Depending on the width we have, this may produce (FLAT n . atm)
; which attaches the dot to the atm, or ((DOT 1) (FLAT n atm)) which
; leaves the dot on a line by itself.

; We want keywords to appear on new lines.  That means if the first
; element of lst is a keyword, don't merge (unless x is one too).

#|BUG
ACL2 p!>(let ((x '(foo bigggggggggggggggg . :littlllllllllllllle)))
         (ppr2 (ppr1 x (acl2-print-base) 40 0 state nil)
               0 *standard-co* state nil))
(x   = (DOT 1)
lst = ((FLAT 21 :LITTLLLLLLLLLLLLLLE))
val = ((FLAT 23 . :LITTLLLLLLLLLLLLLLE)))

HARD ACL2 ERROR in CONS-PPR1:  I thought I could force it!
|#

; Note: In the function below, column is NOT a number!  Often in this
; code, ``col'' is used to represent the position of the character
; column into which we are printing.  But ``column'' is a list of ppr
; tuples.

(defun keyword-param-valuep (tuple eviscp)

; We return t iff tuple represents a single object that could
; plausibly be the value of a keyword parameter.  The (or i ii iii iv)
; below checks that tuple represents a single object, either by being
; (i) a FLAT tuple listing exactly one object (ii) a QUOTE tuple,
; (iii) a WIDE tuple, or (iv) an indent tuple.  The only other kinds
; of tuples are KEYPAIR tuples, FLAT tuples representing dotted
; objects `. atm', FLAT tuples representing several objects `a b c',
; and MATCHED-KEYWORD tuples representing keywords whose associated
; values are on the next line.  These wouldn't be provided as the
; value of a keyword argument.

  (or (and (eq (car tuple) 'flat)
           (not (or (atom (cddr tuple)) ; tuple is `. atm'
                    (evisceratedp eviscp (cddr tuple))))
           (null (cdr (cddr tuple))))
      (eq (car tuple) 'quote)
      (eq (car tuple) 'wide)
      (integerp (car tuple))))
  
(defun cons-ppr1 (x column width eviscp)

; Here, x is a ppr tuple representing either a dot or a single object
; and column is a list of tuples corresponding to a list of objects
; (possibly a list of length greater than that of column).
; Intuitively, column will print as a column of objects and we want to
; add x to that column, either by extending the top row or adding a
; new row.  In the most typical case, x might be (FLAT 3 ABC) and
; column is ((FLAT 7 DEF GHI) (...)).  Thus our choices would be to
; produce

; lengthened column          lengthened first row
; ABC                        ABC DEF GHI
; DEF GHI                    (...)
; (...)

; It is also here that we deal specially with keywords.  If x is
; (FLAT 3 :ABC) and column is ((...) (...)) then we have the choice:

; lengthened column          lengthened first row
; :ABC                       :ABC (...)
; (...)                      (...)
; (...)

; The default behavior is always to lengthen the column, which is just
; to cons x onto column.

  (cond
   ((and (eq (car x) 'flat)

; Note: Since x represents a dot or an object, we know that it is not
; of the form (FLAT n . atm).  Thus, (cddr x) is a list of length 1
; containing a single (possibly eviscerated) object, x1.  If that
; object is an atom (or prints like one) we'll consider merging it
; with whatever else is on the first row. 

         (or (atom (car (cddr x)))
             (evisceratedp eviscp (car (cddr x))))
         (consp column))

    (let ((x1 (car (cddr x)))
          (row1 (car column)))

; We know x represents the atom x1 (actually, x1 may be an eviscerated
; object, but if so it prints flat like an atom, e.g., `<world>').
; Furthermore, we know column is non-empty and so has a first element,
; e.g., row1.

      (cond
       ((keywordp x1)

; So x1 is a keyword.  Are we looking at a keypair?  We are if row1
; represents a single value.  By a ``single value'' we mean a single
; object that can be taken as the value of the keyword x1.  If row1
; represents a sequence of more than one object, e.g., (FLAT 5 a b c),
; then we are not in a keypair situation because keyword argument
; lists must be keyword/value pairs all the way down and we form these
; columns bottom up, so if b were a keyword in the proper context, we
; would have paired it with c as keypair, not merged it, or we would
; have put it in a MATCHED-KEYWORD, indicating that its associated
; value is below it in the column.  If row1 does not represent a
; single value we act just like x1 had not been a keyword, i.e., we
; try to merge it with row1.  This will shut down subsequent attempts
; to create keypairs above us.

        (cond
         ((and (keyword-param-valuep row1 eviscp)
               (or (null (cdr column))
                   (eq (car (cadr column)) 'keypair)
                   (eq (car (cadr column)) 'matched-keyword)))

; So x1 is a keyword, row1 represents a keyword parameter value, and
; the rest of the column represents keyword/value pairs.  The last
; test is made by just checking the item on the column below row1.  It
; would only be a keyword/value pair if the whole column consisted of
; those.  We consider making a keypair of width n = width of key, plus
; space, plus width of widest line in row1.  Note that we don't mind
; this running over the standard 40 character max line length because
; it is so iconic.

          (let ((n (+ (cadr x) (+ 1 (cadr row1)))))
            (cond ((<= n width)
                   (cons
                    (cons 'keypair (cons n (cons x row1)))
                    (cdr column)))

; Otherwise, we put x on a newline and leave the column as it was.
; Note that we convert x from a FLAT to a MATCHED-KEYWORD, so insure
; that it stays on a line by itself and to keyword/value pairs
; encountered above us in the bottom-up processing to be paired
; with KEYPAIR.

                  (t (cons (cons 'MATCHED-KEYWORD (cdr x))
                           column)))))

; In this case, we are not in the context of a keyword/value argument
; even though x is a keyword.  So we act just like x is not a keyword
; and see whether we can merge it with row1.  We merge only if row1 is
; FLAT already and the width of the merged row is acceptable.  Even if
; row1 prints as `. atm' we will merge, giving rise to such displays
; as

; (foo a b c
;      d e f . atm)

         ((eq (car row1) 'flat)
          (let ((n (+ (cadr x) (+ 1 (cadr row1)))))
            (cond ((and (<= n 40) (<= n width))
                   (cons
                    (cons 'flat (cons n (cons x1 (cddr row1))))
                    (cdr column)))
                  (t (cons x column)))))
         (t (cons x column))))

; In this case, x1 is not a keyword.  But it is known to print in
; atom-like way, e.g., `ABC' or `<world>'.  So we try a simple merge
; following the same scheme as above.

       ((eq (car row1) 'flat)
        (let ((n (+ (cadr x) (+ 1 (cadr row1)))))
          (cond ((and (<= n 40) (<= n width))
                 (cons
                  (cons 'flat (cons n (cons x1 (cddr row1))))
                  (cdr column)))
                (t (cons x column)))))
       (t (cons x column)))))
   ((and (eq (car x) 'dot)
         (consp column))
    (let ((row1 (car column)))
      (cond ((eq (car row1) 'flat)

; In this case we know (car (cddr row1)) is an atom (or an eviscerated
; object) and it becomes the cddr of the car of the answer, which puts
; the dot on the same line as the terminal cdr.

             (let ((n (+ (cadr x) (+ 1 (cadr row1)))))
               (cond ((and (<= n 40) (<= n width))
                      (cons
                       (cons 'flat
                             (cons n (car (cddr row1))))
                       (cdr column)))
                     (t (cons x column)))))
            (t (cons x column)))))

; In this case, x1 does not print flat.  So we add a new row.

   (t (cons x column))))

(defun flsz-integer (x print-base acc)
  (declare (type (unsigned-byte 5) print-base)
           (type (signed-byte 29) acc)
           (xargs :guard (print-base-p print-base)))
  (the-fixnum
   (cond ((< x 0)
          (flsz-integer (- x) print-base (1+f acc)))
         ((< x print-base) (1+f acc))
         (t (flsz-integer (truncate x print-base) print-base (1+f acc))))))

(defun flsz-atom (x print-base acc state)
  (declare (type (unsigned-byte 5) print-base)
           (type (signed-byte 29) acc))
  (the-fixnum
   (cond ((> acc (the (signed-byte 29) 100000))

; In order to make it very simple to guarantee that flsz and flsz-atom
; return fixnums, we ensure that acc is small enough below.  We could
; certainly provide a much more generous bound, but 100,000 seems safe
; at the moment!

          100000)
         ((integerp x)
          (flsz-integer x
                        print-base
                        (cond ((int= print-base 10)
                               acc)
                              (t ; #b, #o, or #x prefix
                               (+f 2 acc)))))
         ((symbolp x)

; For symbols we add together the length of the "package part" and the
; symbol name part.  We include the colons in the package part.

          (+f (cond
               ((keywordp x) (1+f acc))
               ((or (equal (symbol-package-name x)
                           (f-get-global 'current-package state))
                    (member-eq
                     x
                     (package-entry-imports
                      (find-package-entry
                       (f-get-global 'current-package state)
                       (known-package-alist state)))))
                acc)
               (t
                (let ((p (symbol-package-name x)))
                  (cond ((may-need-slashes p)
                         (+f 4 acc (the-half-fixnum! (length p)
                                                     'flsz-atom)))
                        (t (+f 2 acc (the-half-fixnum! (length p)
                                                       'flsz-atom)))))))
              (let ((s (symbol-name x)))
                 (cond ((may-need-slashes s)
                        (+f 2 (the-half-fixnum! (length s) 'flsz-atom)))
                       (t (+f (the-half-fixnum! (length s) 'flsz-atom)))))))
         ((rationalp x)
          (flsz-integer (numerator x)
                        print-base
                        (flsz-integer (denominator x)
                                      print-base
                                      (cond ((int= print-base 10)
                                             (1+f acc))
                                            (t ; #b, #o, or #x prefix
                                             (+f 3 acc))))))
         ((complex-rationalp x)
          (flsz-atom (realpart x)
                     print-base
                     (flsz-atom (imagpart x)
                                print-base
                                (cond ((int= print-base 10)
                                       (+f 5 acc))
                                      (t
; Compensate for adding twice for #b, #o, or #x prefix.
                                       (+f 3 acc)))
                                state)
                     state))
         ((stringp x)
          (+f 2 acc (the-half-fixnum! (length x) 'flsz-atom)))
         ((characterp x)
          (+f acc
              (cond ((eql x #\Newline) 9)
                    ((eql x #\Rubout) 8)
                    ((eql x #\Space) 7)
                    ((eql x #\Page) 6)
                    ((eql x #\Tab) 5)
                    (t 3))))
         (t 0))))

(defun flsz1 (x print-base j maximum state eviscp)

; Actually, maximum should be of type (signed-byte 28).

  (declare (type (unsigned-byte 5) print-base)
           (type (signed-byte 29) j maximum))
  (the-fixnum
   (cond ((> j maximum) j)
         ((atom x) (flsz-atom x print-base j state))
         ((evisceratedp eviscp x)
          (+f j (the-half-fixnum! (length (cdr x)) 'flsz)))
         ((atom (cdr x))
          (cond ((null (cdr x))
                 (flsz1 (car x) print-base (+f 2 j) maximum state eviscp))
                (t (flsz1 (cdr x)
                          print-base
                          (flsz1 (car x) print-base (+f 5 j) maximum state
                                 eviscp)
                          maximum state eviscp))))
         ((and (eq (car x) 'quote)
               (consp (cdr x))
               (null (cddr x)))
          (flsz1 (cadr x) print-base (+f 1 j) maximum state eviscp))
         (t (flsz1 (cdr x)
                   print-base
                   (flsz1 (car x) print-base (+f 1 j) maximum state eviscp)
                   maximum state eviscp)))))

(defun output-in-infixp (state)
  (let ((infixp (f-get-global 'infixp state)))
    (or (eq infixp t) (eq infixp :out))))

#-acl2-loop-only
(defun-one-output flatsize-infix (x print-base termp j max eviscp)

; Suppose that printing x flat in infix notation causes k characters
; to come out.  Then we return j+k.  All answers greater than max are
; equivalent.

; If you think of j as the column into which you start printing flat,
; then this returns the column you'll print into after printing x.  If
; that column exceeds max, which is the right margin, then it doesn't
; matter by how far it exceeds max.

; In our $ infix notation, flat output has two extra chars in it, the
; $ and space.  But note that we use infix output only if infixp is t
; or :out.

  (declare (ignore termp))
  (+ 2 (flsz1 x print-base j max *the-live-state* eviscp)))

(defun flsz (x termp j maximum state eviscp)
  #+acl2-loop-only
  (declare (ignore termp))
  #-acl2-loop-only
  (cond ((and (live-state-p state)
              (output-in-infixp state))
         (return-from flsz (flatsize-infix x (acl2-print-base) termp j maximum
                                           eviscp))))
  (flsz1 x (acl2-print-base) j maximum state eviscp))

(defun max-width (lst maximum)
  (cond ((null lst) maximum)
        ((> (cadr (car lst)) maximum)
         (max-width (cdr lst) (cadr (car lst))))
        (t (max-width (cdr lst) maximum))))

(mutual-recursion

(defun ppr1 (x print-base width rpc state eviscp)

; We create a ppr tuple for x, i.e., a list structure that tells us
; how to prettyprint x, in a column of the given width.  Rpc stands
; for `right paren count' and is the number of right parens that will
; follow the printed version of x.  For example, in printing the x in
; (f (g (h x)) u) there will always be 2 right parens after it.  So we
; cannot let x use the entire available width, only the width-2.  Rpc
; would be 2.  Eviscp indicates whether we are to think of evisc marks
; as printing as atom-like strings or whether they're just themselves
; as data.

  (declare (type (signed-byte 29) print-base width rpc))
  (let ((sz (flsz1 x print-base rpc width state eviscp)))
    (declare (type (signed-byte 29) sz))
    (cond ((or (atom x)
               (evisceratedp eviscp x)
               (and (<= sz width)
                    (<= sz 40)))
           (cons 'flat (cons sz (list x))))
          ((and (eq (car x) 'quote)
                (consp (cdr x))
                (null (cddr x)))
           (let* ((x1 (ppr1 (cadr x) print-base (+f width -1) rpc state
                            eviscp)))
             (cons 'quote (cons (+ 1 (cadr x1)) x1))))
          (t
           (let* ((x1 (ppr1 (car x) print-base (+f width -1)
                            (the-fixnum (if (null (cdr x)) (+ rpc 1) 0))
                            state eviscp))

; If the fn is a symbol (or eviscerated, which we treat as a symbol),
; then the hd-sz is the length of the symbol.  Else, hd-sz is nil.
; Think of (null hd-sz) as meaning "fn is a lambda expession".

                  (hd-sz (cond ((or (atom (car x))
                                    (evisceratedp eviscp (car x)))
                                (cadr x1))
                               (t nil)))

; When printing the cdr of x, give each argument the full width (minus
; 1 for the minimal amount of indenting).  Note that x2 contains the
; ppr tuples for the car and the cdr.

                  (x2 (cons x1
                            (ppr1-lst (cdr x) print-base (+f width -1)
                                      (+f rpc 1) state eviscp)))

; If the fn is a symbol, then we get the maximum width of any single
; argument.  Otherwise, we get the maximum width of the fn and its
; arguments.

                  (maximum (cond (hd-sz (max-width (cdr x2) -1))
                                 (t (max-width x2 -1)))))

             (cond ((null hd-sz)

; If the fn is lambda, we indent the args by 1 and report the width of
; the whole to be one more than the maximum computed above.

                    (cons 1 (cons (+ 1 maximum) x2)))
                   ((<= (+ hd-sz (+ 2 maximum)) width)

; We can print WIDE if we have room for an open paren, the fn, a space,
; and the widest argument.

                    (cons 'wide
                          (cons (+ hd-sz (+ 2 maximum)) x2)))
                   ((< maximum width)

; If the maximum is less than the width, we can do exact indenting of
; the arguments to make the widest argument come out on the right
; margin.  This exactness property is one of the things that makes
; this algorithm produce such beautiful output: we get the largest
; possible indentation, which makes it easy to identify peer
; arguments.  How much do we indent?  width-maximum will guarantee
; that the widest argument ends on the right margin.  However, we
; believe that it is more pleasing if argument columns occur at
; regular indents.  So we limit our indenting to 5 and just give up
; the white space over on the right margin.  Note that we compute the
; width of the whole term accordingly.

                    (cons (min 5 (+ width (- maximum)))
                          (cons (+ maximum (min 5 (+ width (- maximum))))
                                x2)))

; If maximum is not less than width, we indent by 1.

                   (t (cons 1 (cons (+ 1 maximum) x2)))))))))


; The next function computes a ppr tuple for each element of lst.
; Typically these are all arguments to a function.  But of course, we
; prettyprint arbitrary constants and so have to handle the case that
; the list is not a true-list.

; If you haven't read about cons-ppr1, above, do so now.

(defun ppr1-lst (lst print-base width rpc state eviscp)

  (declare (type (signed-byte 29) print-base width rpc))
  (cond ((atom lst)

; If the list is empty and null, then nothing is printed (besides the
; parens which are being accounted for otherwise).  If the list is
; terminated by some non-nil atom, we will print a dot and the atom.
; We do that by merging a dot tuple into the flat for the atom, if
; there's room on the line, using cons-ppr1.  Where this merged flat
; will go, i.e., will it be indented under the car as happens in the
; Essay on the Printing of Dotted Pairs, is the concern of ppr1-lst,
; not the cons-ppr1.  The cons-ppr1 below just produces a merged
; flat containing the dot, if the width permits.

         (cond ((null lst) nil)
               (t (cons-ppr1 '(dot 1)
                             (list (ppr1 lst print-base width rpc state
                                         eviscp))
                             width eviscp))))

; The case for an eviscerated terminal cdr is handled the same way.

        ((evisceratedp eviscp lst)
         (cons-ppr1 '(dot 1)
                    (list (ppr1 lst print-base width rpc state eviscp))
                    width eviscp))

; If the list is a true singleton, we just use ppr1 and we pass it the
; rpc that was passed in because this last item will be followed by
; that many parens on the same line.

        ((null (cdr lst))
         (list (ppr1 (car lst) print-base width rpc state eviscp)))

; Otherwise, we know that the car is followed by more elements.  So
; its rpc is 0.

        (t (cons-ppr1 (ppr1 (car lst) print-base width 0 state eviscp)
                      (ppr1-lst (cdr lst) print-base width rpc state eviscp)
                      width eviscp))))

)

(defun newline (channel state)
  (princ$ #\Newline channel state))

(defun fmt-hard-right-margin (state)
  (the-fixnum
   (f-get-global 'fmt-hard-right-margin state)))

(defun fmt-soft-right-margin (state)
  (the-fixnum
   (f-get-global 'fmt-soft-right-margin state)))

(defun set-fmt-hard-right-margin (n state)
  (cond
   ((and (integerp n)
         (< 0 n))
    (f-put-global 'fmt-hard-right-margin
                  (the-half-fixnum! n 'set-fmt-hard-right-margin)
                  state))
   (t (let ((err (er hard 'set-fmt-hard-right-margin
                     "The fmt-hard-right-margin must be a positive ~
                      integer, but ~x0 is not."
                     n)))
        (declare (ignore err))
        state))))

(defun set-fmt-soft-right-margin (n state)
  (cond
   ((and (integerp n)
         (< 0 n))
    (f-put-global 'fmt-soft-right-margin
                  (the-half-fixnum! n 'set-fmt-soft-right-margin)
                  state))
   (t (let ((err (er hard 'set-fmt-soft-right-margin
                     "The fmt-soft-right-margin must be a positive ~
                      integer, but ~x0 is not."
                     n)))
        (declare (ignore err))
        state))))

(defun write-for-read (state)
  (and (f-boundp-global 'write-for-read state)
       (f-get-global 'write-for-read state)))

(defun spaces1 (n col hard-right-margin channel state)
  (declare (type (signed-byte 29) n col hard-right-margin))
  (cond ((<= n 0) state)
        ((> col hard-right-margin)
         (pprogn (if (write-for-read state)
                     state
                   (princ$ #\\ channel state))
                 (newline channel state)
                 (spaces1 n 0 hard-right-margin channel state)))
        (t (pprogn (princ$ #\Space channel state)
                   (spaces1 (1-f n) (1+f col) hard-right-margin channel
                            state)))))

; The use of *acl2-built-in-spaces-array* to circumvent the call to
; spaces1 under spaces has saved about 25% in GCL and a little more
; than 50% in Allegro.

(defun make-spaces-array-rec (n acc)
  (if (zp n)
      (cons (cons 0 "") acc)
    (make-spaces-array-rec
     (1- n)
     (cons
      (cons n
            (coerce (make-list n :initial-element #\Space) 'string))
      acc))))

(defun make-spaces-array (n)
  (compress1
   'acl2-built-in-spaces-array
   (cons `(:HEADER :DIMENSIONS (,(1+ n))
                   :MAXIMUM-LENGTH ,(+ 2 n)
                   :DEFAULT nil ; should be ignored
                   :NAME acl2-built-in-spaces-array)
         (make-spaces-array-rec n nil))))

(defconst *acl2-built-in-spaces-array*

; Keep the 200 below in sync with the code in spaces.

  (make-spaces-array 200))

(defun spaces (n col channel state)
  (declare (type (signed-byte 29) n col))
  (let ((hard-right-margin (fmt-hard-right-margin state))
        (result-col (+f n col)))
    (declare (type (signed-byte 29) hard-right-margin result-col))
    (if (and (<= result-col hard-right-margin)

; Keep the 200 below in sync with the code in
; *acl2-built-in-spaces-array*.

             (<= n 200))
        ;; actually (1+ hard-right-margin) would do
        (princ$ (aref1 'acl2-built-in-spaces-array
                       *acl2-built-in-spaces-array*
                       n)
                channel state)
      (spaces1 (the-fixnum! n 'spaces)
               (the-fixnum col)
               hard-right-margin
               channel state))))

(mutual-recursion

(defun flpr1 (x channel state eviscp)
  (cond ((atom x)
         (prin1$ x channel state))
        ((evisceratedp eviscp x)
         (princ$ (cdr x) channel state))
        ((and (eq (car x) 'quote)
              (consp (cdr x))
              (null (cddr x)))
         (pprogn (princ$ #\' channel state)
                 (flpr1 (cadr x) channel state eviscp)))
        (t (pprogn (princ$ #\( channel state)
                   (flpr11 x channel state eviscp)))))

(defun flpr11 (x channel state eviscp)
  (pprogn
   (flpr1 (car x) channel state eviscp)
   (cond ((null (cdr x)) (princ$ #\) channel state))
         ((or (atom (cdr x))
              (evisceratedp eviscp (cdr x)))
          (pprogn
           (princ$ " . " channel state)
           (flpr1 (cdr x) channel state eviscp)
           (princ$ #\) channel state)))
         (t (pprogn
             (princ$ #\Space channel state)
             (flpr11 (cdr x) channel state eviscp))))))

)

#-acl2-loop-only
(defun-one-output print-flat-infix (x termp file eviscp)

; Print x flat (without terpri's) in infix notation to the open output
; stream file.  Give special treatment to :evisceration-mark iff
; eviscp.  We only call this function if flatsize-infix assures us
; that x will fit on the line.  See the Essay on Evisceration in this
; file to details on that subject.

  (declare (ignore termp eviscp))
  (let ((*print-case* :downcase)
        (*print-pretty* nil))
    (princ "$ " file)
    (prin1 x file)))

(defun flpr (x termp channel state eviscp)
  #+acl2-loop-only
  (declare (ignore termp))
  #-acl2-loop-only
  (cond ((and (live-state-p state)
              (output-in-infixp state))
         (print-flat-infix x termp
                           (get-output-stream-from-channel channel)
                           eviscp)
         (return-from flpr *the-live-state*)))
  (flpr1 x channel state eviscp))

(defun ppr2-flat (x channel state eviscp)

; We print the elements of x, separated by spaces.  If
; x is a non-nil atom, we print a dot and then x.

  (cond ((null x) state)
        ((or (atom x)
             (evisceratedp eviscp x))
         (pprogn (princ$ #\. channel state)
                 (princ$ #\Space channel state)
                 (flpr1 x channel state eviscp)))
        (t (pprogn
            (flpr1 (car x) channel state eviscp)
            (cond ((cdr x)
                   (pprogn (princ$ #\Space channel state)
                           (ppr2-flat (cdr x) channel state eviscp)))
                  (t state))))))

(mutual-recursion

(defun ppr2-column (lst loc col channel state eviscp)

; We print the elements of lst in a column.  The column number is col
; and we assume the print head is currently in column loc, loc <= col.
; Thus, to indent to col we print col-loc spaces.  After every element
; of lst but the last, we print a newline.

  (cond ((null lst) state)
        (t (pprogn
            (spaces (+ col (- loc)) loc channel state)
            (ppr2 (car lst) col channel state eviscp)
            (cond ((null (cdr lst)) state)
                  (t (pprogn
                      (newline channel state)
                      (ppr2-column (cdr lst) 0 col
                                   channel state eviscp))))))))

(defun ppr2 (x col channel state eviscp)

; We interpret the ppr tuple x.

  (case
    (car x)
    (flat (ppr2-flat (cddr x) channel state eviscp))
    (matched-keyword
     (ppr2-flat (cddr x) channel state eviscp)) ; just like flat!
    (dot (princ$ #\. channel state))
    (quote (pprogn (princ$ #\' channel state)
                   (ppr2 (cddr x) (+ 1 col) channel state eviscp)))
    (keypair (pprogn
              (ppr2-flat (cddr (car (cddr x))) channel state eviscp)
              (princ$ #\Space channel state)
              (ppr2 (cdr (cddr x))
                    (+ col (+ 1 (cadr (car (cddr x)))))
                    channel state eviscp)))
    (wide (pprogn
           (princ$ #\( channel state)
           (ppr2-flat (cddr (car (cddr x))) channel state eviscp)
           (ppr2-column (cdr (cddr x))
                        (+ col (+ 1 (cadr (car (cddr x)))))
                        (+ col (+ 2 (cadr (car (cddr x)))))
                        channel state eviscp)
           (princ$ #\) channel state)))
    (otherwise (pprogn
                (princ$ #\( channel state)
                (ppr2 (car (cddr x)) (+ col (car x)) channel
                      state eviscp)
                (cond ((cdr (cddr x))
                       (pprogn
                        (newline channel state)
                        (ppr2-column (cdr (cddr x))
                                     0
                                     (+ col (car x))
                                     channel state eviscp)
                        (princ$ #\) channel state)))
                      (t (princ$ #\) channel state)))))))
)

; We used to set *fmt-ppr-indentation* below to 5, but it the
; indentation was sometimes odd because when printing a list, some
; elements could be indented and others not.  At any rate, it should
; be less than the fmt-hard-right-margin in order to preserve the
; invariant that fmt0 is called on columns that do not exceed this
; value.

(defconst *fmt-ppr-indentation* 0)

(defun ppr (x col channel state eviscp)

; If eviscp is nil, then we pretty print x as given.  Otherwise,
; x has been eviscerated and we give special importance to the
; *evisceration-mark*.  NOTE WELL:  This function does not
; eviscerate -- it assumes the evisceration has been done if
; needed.

  (declare (type (signed-byte 29) col))
  (let ((fmt-hard-right-margin (fmt-hard-right-margin state)))
    (declare (type (signed-byte 29) fmt-hard-right-margin))
    (cond
     ((< col fmt-hard-right-margin)
      (ppr2 (ppr1 x (acl2-print-base) (+f fmt-hard-right-margin (-f col)) 0
                  state eviscp)
            col channel state eviscp))
     (t (let ((er
               (er hard 'ppr
                   "The `col' argument to ppr must be less than value ~
                    of the state global variable ~
                    fmt-hard-right-margin, but ~x0 is not less than ~
                    ~x1."
                   col fmt-hard-right-margin)))
          (declare (ignore er))
          state)))))

(defun scan-past-whitespace (s i maximum)
  (declare (type (signed-byte 29) i maximum)
           (type string s))
  (the-fixnum
   (cond ((< i maximum)
          (cond ((member (charf s i) '(#\Space #\Tab #\Newline))
                 (scan-past-whitespace s (+f i 1) maximum))
                (t i)))
         (t maximum))))

(defun zero-one-or-more (x)
  (let ((n (cond ((integerp x) x)
                 (t (length x)))))
    (case n
          (0 0)
          (1 1)
          (otherwise 2))))

(defun find-alternative-skip (s i maximum)

; This function finds the first character after a list of alternatives.
; i is the value of find-alternative-stop, i.e., it points to the ~ in
; the ~/ or ~] that closed the alternative used.

; Suppose s is "~#7~[ab~/cd~/ef~]acl2".
;               01234567890123456789
; If i is 11, the answer is 17.
;

  (declare (type (signed-byte 29) i maximum)
           (type string s))
  (the-fixnum
   (cond ((< i maximum)
          (let ((char-s-i (charf s i)))
            (declare (type character char-s-i))
            (case char-s-i
              (#\~
               (let ((char-s-1+i (charf s (1+f i))))
                 (declare (type character char-s-1+i))
                 (case char-s-1+i
                   (#\] (+f 2 i))
                   (#\[ (find-alternative-skip
                         s
                         (find-alternative-skip s (+f 2 i)
                                                maximum)
                         maximum))
                   (otherwise (find-alternative-skip
                               s (+f 2 i) maximum)))))
              (otherwise
               (find-alternative-skip s (+f 1 i) maximum)))))
         (t (er-hard-val 0 'find-alternative-skip
                "Illegal Fmt Syntax -  While looking for the terminating ~
                bracket of a tilde alternative directive in the string ~
                below we ran off the end of the string.~|~%~x0"
                s)))))

(defun find-alternative-start1 (x s i maximum)
  (declare (type (signed-byte 29) x i maximum)
           (type string s))
  (the-fixnum
   (cond ((= x 0) i)
         ((< i maximum)
          (let ((char-s-i (charf s i)))
            (declare (type character char-s-i))
            (case char-s-i
              (#\~
               (let ((char-s-1+-i (charf s (1+f i))))
                 (declare (type character char-s-1+-i))
                 (case char-s-1+-i
                   (#\/ (find-alternative-start1
                         (1-f x) s (+f 2 i)
                         maximum))
                   (#\] (er-hard-val 0 'find-alternative-start1
                            "Illegal Fmt Syntax -- The tilde directive ~
                             terminating at position ~x0 of the string below ~
                             does not have enough alternative clauses.  When ~
                             the terminal bracket was reached we still needed ~
                             ~#1~[~/1 more alternative~/~x2 more ~
                             alternatives~].~|~%~x3"
                            i
                            (zero-one-or-more x)
                            x
                            s))
                   (#\[ (find-alternative-start1
                         x s
                         (find-alternative-skip s (+f 2 i) maximum)
                         maximum))
                   (otherwise
                    (find-alternative-start1
                     x s (+f 2 i) maximum)))))
              (otherwise
               (find-alternative-start1 x s (+f 1 i)
                                        maximum)))))
         (t (er-hard-val 0 'find-alternative-start1
                "Illegal Fmt Syntax -- While searching for the appropriate ~
                alternative clause of a tilde alternative directive in the ~
                string below, we ran off the end of the string.~|~%~x0"
                s)))))

(defun fmt-char (s i j maximum err-flg)
  (declare (type (signed-byte 29) i maximum)

; We only increment i by a small amount, j.

           (type (integer 0 100) j)
           (type string s))
  (cond ((< (+f i j) maximum) (charf s (+f i j)))
        (err-flg
         (er hard 'fmt-char
             "Illegal Fmt Syntax.  The tilde directive at location ~x0 ~
                in the fmt string below requires that we look at the ~
                character ~x1 further down in the string.  But the ~
                string terminates at location ~x2.~|~%~x3"
             i j maximum s))
        (t nil)))

(defun find-alternative-start (x s i maximum)

; This function returns the index of the first character in the xth
; alternative, assuming i points to the ~ that begins the alternative
; directive.  If x is not an integer, we assume it is a non-empty
; list.  If its length is 1, pick the 0th alternative.  Otherwise,
; pick the 1st.  This means we can test on a list to get a "plural" test.

; Suppose s is "~#7~[ab~/cd~/ef~]acl2".  The indices into s are
;               01234567890123456789
; This function is supposed to be called with i=0.  Suppose register
; 7 contains a 1.  That's the value of x.  This function will return
; 9, the index of the beginning of alternative x.

  (declare (type (signed-byte 29) i maximum)
           (type string s))
  (the-fixnum
   (let ((x (cond ((integerp x) (the-fixnum! x 'find-alternative-start))
                  ((and (consp x)
                        (atom (cdr x)))
                   0)
                  (t 1))))
     (declare (type (signed-byte 29) x))
     (cond ((not (and (eql (the character (fmt-char s i 3 maximum t)) #\~)
                      (eql (the character (fmt-char s i 4 maximum t)) #\[)))
            (er-hard-val 0 'find-alternative-start
                "Illegal Fmt Syntax:  The tilde directive at ~x0 in the ~
                fmt string below must be followed immediately by ~~[. ~
                ~|~%~x1"
                i s))
           (t (find-alternative-start1 x s (+f i 5) maximum))))))

(defun find-alternative-stop (s i maximum)

; This function finds the end of the alternative into which i is
; pointing.  i is usually the first character of the current alternative.
; The answer points to the ~ in the ~/ or ~] closing the alternative.

; Suppose s is "~#7~[ab~/cd~/ef~]acl2".
;               01234567890123456789
; and i is 9.  Then the answer is 11.

  (declare (type (signed-byte 29) i maximum)
           (type string s))
  (the-fixnum
   (cond ((< i maximum)
          (let ((char-s-i (charf s i)))
            (declare (type character char-s-i))
            (case char-s-i
              (#\~ (let ((char-s-1+i (charf s (1+f i))))
                     (declare (type character char-s-1+i))
                     (case char-s-1+i
                       (#\/ i)
                       (#\[ (find-alternative-stop
                             s
                             (find-alternative-skip s (+f 2 i) maximum)
                             maximum))
                       (#\] i)
                       (otherwise (find-alternative-stop
                                   s (+f 2 i) maximum)))))
              (otherwise (find-alternative-stop s (+f 1 i) maximum)))))
         (t (er-hard-val 0 'find-alternative-stop
                "Illegal Fmt Syntax -- While looking for the terminating ~
                slash of a tilde alternative directive alternative clause ~
                in the string below we ran off the end of the string. ~
                ~|~%~x0"
                s)))))

(defun punctp (c)
  (if (member c '(#\. #\, #\: #\; #\? #\! #\) #\]))
      c
    nil))

(defun fmt-symbol-name1 (s i maximum col channel state)
  (declare (type (signed-byte 29) i maximum col)
           (type string s))
  (the2s
   (signed-byte 29)
   (cond ((not (< i maximum))
          (mv col state))
         ((and (> col (fmt-hard-right-margin state))
               (not (write-for-read state)))
          (pprogn
           (princ$ #\\ channel state)
           (newline channel state)
           (fmt-symbol-name1 s i maximum 0 channel state)))
         (t
          (let ((c (charf s i))
                (fmt-soft-right-margin (fmt-soft-right-margin state)))
            (declare (type character c)
                     (type (signed-byte 29) fmt-soft-right-margin))
            (cond ((and (> col fmt-soft-right-margin)
                        (not (write-for-read state))
                        (eql c #\Space))
                   (pprogn
                    (newline channel state)
                    (fmt-symbol-name1 s
                                      (scan-past-whitespace s (+f i 1) maximum)
                                      maximum 0 channel state)))
                  ((and (> col fmt-soft-right-margin)
                        (not (write-for-read state))
                        (or (eql c #\-)
                            (eql c #\_))
                        (not (int= (1+f i) maximum)))

; If we are beyond the soft right margin and we are about to print a
; hyphen or underscore and it is not the last character in the string,
; then print it and do a terpri.  If it is the last character, as it
; is in say, the function name "1-", then we don't do the terpri and
; hope there is a better place to break soon.  The motivating example
; for this was in seeing a list of function names get printed in a way
; that produced a comma as the first character of the newline, e.g.,
; "... EQL, 1+, 1-
; , ZEROP and PLUSP."

                   (pprogn
                    (princ$ c channel state)
                    (if (eql c #\-) state (princ$ #\- channel state))
                    (newline channel state)
                    (fmt-symbol-name1 s
                                      (scan-past-whitespace s (+f i 1) maximum)
                                      maximum 0 channel state)))
                  (t
                   (pprogn
                    (princ$ c channel state)
                    (fmt-symbol-name1 s (1+f i) maximum (1+f col)
                                      channel state)))))))))

(defun fmt-var (s alist i maximum)
  (declare (type (signed-byte 29) i maximum)
           (type string s))
  (let ((x (assoc (the character (fmt-char s i 2 maximum t)) alist)))
    (cond (x (cdr x))
          (t (er hard 'fmt-var
                 "Unbound Fmt Variable.  The tilde directive at location ~x0 ~
                  in the fmt string below uses the variable ~x1.  But ~
                  this variable is not bound in the association list, ~
                  ~x2, supplied with the fmt string.~|~%~x3"
                 i (char s (+f i 2)) alist s)))))

(defun splat-atom (x print-base indent col channel state)
  (let* ((sz (flsz-atom x print-base 0 state))
         (too-bigp (> (+ col sz) (fmt-hard-right-margin state))))
    (pprogn (if too-bigp
                (pprogn (newline channel state)
                        (spaces indent 0 channel state))
                state)
            (prin1$ x channel state)
            (mv (if too-bigp (+ indent sz) (+ col sz))
                state))))

; Splat, below, prints out an arbitrary ACL2 object flat, introducing
; the single-gritch notation for quote and breaking lines between lexemes
; to avoid going over the hard right margin.  It indents all but the first
; line by indent spaces.

(mutual-recursion

(defun splat (x print-base indent col channel state)
  (cond ((atom x)
         (splat-atom x print-base indent col channel state))
        ((and (eq (car x) 'quote)
              (consp (cdr x))
              (null (cddr x)))
         (pprogn (princ$ #\' channel state)
                 (splat (cadr x) print-base indent (1+ col) channel state)))
        (t (pprogn (princ$ #\( channel state)
                   (splat1 x print-base indent (1+ col) channel state)))))

(defun splat1 (x print-base indent col channel state)
  (mv-let (col state)
          (splat (car x) print-base indent col channel state)
          (cond ((null (cdr x))
                 (pprogn (princ$ #\) channel state)
                         (mv (1+ col) state)))
                ((atom (cdr x))
                 (cond ((> (+ 3 col) (fmt-hard-right-margin state))
                        (pprogn (newline channel state)
                                (spaces indent 0 channel state)
                                (princ$ ". " channel state)
                                (mv-let (col state)
                                        (splat (cdr x)
                                               print-base
                                               indent
                                               (+ indent 2)
                                               channel state)
                                        (pprogn (princ$ #\) channel state)
                                                (mv (1+ col) state)))))
                       (t (pprogn
                           (princ$ " . " channel state)
                           (mv-let (col state)
                                   (splat (cdr x)
                                          print-base
                                          indent (+ 3 col) channel
                                          state)
                                   (pprogn (princ$ #\) channel state)
                                           (mv (1+ col) state)))))))
                (t (pprogn
                    (princ$ #\Space channel state)
                    (splat1 (cdr x) print-base indent (1+ col) channel
                            state))))))

)

(defun number-of-digits (n)

; We compute the width of the field necessary to express the integer n
; in decimal notation.  We assume minus signs are printed but plus
; signs are not.  Thus, if n is -123 we return 4, if n is 123 we
; return 3.

  (cond ((< n 0) (1+ (number-of-digits (abs n))))
        ((< n 10) 1)
        (t (1+ (number-of-digits (floor n 10))))))

(defun left-pad-with-blanks (n width col channel state)

; Print the integer n right-justified in a field of width width.
; We return the final column (assuming we started in col) and state.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (let ((d (the-half-fixnum! (number-of-digits n) 'left-pad-with-blanks)))
     (declare (type (signed-byte 29) d))
     (cond ((>= d width)
            (pprogn (prin1$ n channel state)
                    (mv (+ col d) state)))
           (t (pprogn
               (spaces (- width d) col channel state)
               (prin1$ n channel state)
               (mv (the-fixnum! (+ col width) 'left-pad-with-blanks)
                   state)))))))

(defmacro maybe-newline (body)

; This macro is used in fmt0 to force a newline only when absolutely
; necessary.  It knows the locals of fmt0, in particular, col,
; channel, and state.  We wrap this macro around code that is about to
; print a character at col.  Once upon a time we just started fmt0
; with a newline if we were past the hard right margin, but that
; produced occasional lines that ended naturally at the hard right
; margin and then had a backslash inserted in anticipation of the 0
; characters to follow.  It was impossible to tell if more characters
; follow because there may be tilde commands between where you are and
; the end of the line, and they may or may not print things.

  `(mv-letc (col state)
            (cond
             ((and (> col (fmt-hard-right-margin state))
                   (not (write-for-read state)))
              (pprogn (princ$ #\\ channel state)
                      (newline channel state)
                      (mv 0 state)))
             (t (mv col state)))
            ,body))

; To support the convention that er, fmt, and even individual fmt
; commands such as ~X can control their own evisceration parameters,
; we now introduce the idea of an evisceration tuple, or evisc-tuple.

(defun evisc-tuple (print-level print-length alist hiding-cars)

; This is really just a record constructor, but we haven't got defrec
; yet so we do it by hand.  The following functions are all of the
; ones that construct or approve of evisc-tuples:
; * evisc-tuple
; * term-evisc-tuple
; * default-evisc-tuple
; * ld-evisc-tuple -- this function does not actually construct
;   one but returns one supplied by the user and approved by:
; * standard-evisc-tuplep
; * trace-evisc-tuple (see also the constant *trace-evisc-tuple*)
; * reset-trace-evisc-tuple

; In addition, we sometimes write out constant evisc tuples!  However
; they are commented nearby with (evisc-tuple ...).

; The primitive consumers of evisc tuples all call 
; * eviscerate, or
; * eviscerate-stobjs.

;         car   cadr        caddr        cadddr

  (list alist   print-level print-length hiding-cars))

(defun standard-evisc-tuplep (x)

; This function limits what ld-evisc-tuple may be assigned.

  (or (null x)
      (and (true-listp x)
           (= (length x) 4)
           (alistp (car x))
           (or (null (cadr x))
               (integerp (cadr x)))
           (or (null (caddr x))
               (integerp (caddr x)))
           (symbol-listp (cadddr x)))))

#-acl2-loop-only
(defparameter *approved-user-default-evisc-tuple* nil)

(defun user-default-evisc-tuple (state)
  (declare (xargs :guard (and (state-p state)
                              (f-boundp-global 'user-default-evisc-tuple state))))
  (let ((val (f-get-global 'user-default-evisc-tuple state)))
    (cond
     #-acl2-loop-only
     ((eq val *approved-user-default-evisc-tuple*) ; optimization
      val)
     ((standard-evisc-tuplep val)
      #-acl2-loop-only
      (setq *approved-user-default-evisc-tuple* val) ; optimization
      val)
     (t (er hard 'user-default-evisc-tuple
            "The user-supplied value for function default-evisc-tuple, which ~
             is (f-get-global 'user-default-evisc-tuple state), is not a legal ~
             evisc-tuple.  See :DOC ld-evisc-tuple.")))))

(defun default-evisc-tuple (state)
  (cond
   ((f-boundp-global 'user-default-evisc-tuple state)
    (user-default-evisc-tuple state))
   (t (cons (world-evisceration-alist state nil)
            '(5 7 nil)))))

#-acl2-loop-only
(defparameter *approved-user-term-evisc-tuple* nil)

(defun user-term-evisc-tuple (state)
  (declare (xargs :guard (and (state-p state)
                              (f-boundp-global 'user-term-evisc-tuple state))))
  (let ((val (f-get-global 'user-term-evisc-tuple state)))
    (cond
     #-acl2-loop-only
     ((eq val *approved-user-term-evisc-tuple*) ; optimization
      val)
     ((standard-evisc-tuplep val)
      #-acl2-loop-only
      (setq *approved-user-term-evisc-tuple* val) ; optimization
      val)
     (t (er hard 'user-term-evisc-tuple
            "The user-supplied value for function term-evisc-tuple, which is ~
             (f-get-global 'user-term-evisc-tuple state), is not a legal ~
             evisc-tuple.  See :DOC ld-evisc-tuple.")))))

(defun term-evisc-tuple (flg state)

; This evisceration tuple is used when we are printing terms or lists
; of terms.  We don't hide the world or state because they aren't
; (usually) found in terms.  This saves us a little time.  If the
; global value of 'eviscerate-hide-terms is t, we print (HIDE ...) as
; <hidden>.  Otherwise not.  Flg controls whether we actually
; eviscerate on the basis of structural depth and length.  If flg is t
; we do.  The choice of the print-length 4 is motivated by the idea
; of being able to print IF as (IF # # #) rather than (IF # # ...).
; Print-level 3 lets us print a clause as ((NOT (PRIMEP #)) ...)
; rather than ((NOT #) ...).

  (cond ((and flg (f-boundp-global 'user-term-evisc-tuple state))
         (user-term-evisc-tuple state))
        ((f-get-global 'eviscerate-hide-terms state)
         (cond (flg
                ;;; (evisc-tuple 3 4 nil '(hide))
                '(nil 3 4 (hide)))

               (t
                ;;; (evisc-tuple nil nil nil '(hide))
                '(nil nil nil (hide)))))
        (flg    ;;; (evisc-tuple 3 4 nil nil)
         '(nil 3 4 nil))
        (t nil)))

(deflabel eviscerate-hide-terms
  :doc
  ":Doc-Section Miscellaneous

  to print ~c[(hide ...)] as ~c[<hidden>]~/
  ~bv[]
  Example:
  (assign eviscerate-hide-terms t)
  (assign eviscerate-hide-terms nil)
  ~ev[]~/

  ~c[Eviscerate-hide-terms] is a ~ilc[state] global variable whose value is
  either ~c[t] or ~c[nil].  The variable affects how terms are displayed.  If
  ~c[t], terms of the form ~c[(hide ...)] are printed as ~c[<hidden>].  Otherwise,
  they are printed normally.")

#-acl2-loop-only
(defun-one-output print-infix (x termp width rpc col file eviscp)

; X is an s-expression denoting a term (if termp = t) or an evg (if
; termp = nil).  File is an open output file.  Prettyprint x in infix
; notation to file.  If eviscp is t then we are to give special treatment to
; the :evisceration-mark; otherwise not.

; This hook is modeled after the ACL2 pretty-printer, which has the following
; additional features.  These features need not be implemented in the infix
; prettyprinter.  The printer is assumed to be in column col, where col=0 means
; it is on the left margin.  We are supposed to print our first character in
; that column.  We are supposed to print in a field of width width.  That is,
; the largest column into which we might print is col+width-2.  Finally, assume
; that on the last line of the output somebody is going to write rpc additional
; characters and arrange for this not to overflow the col+width-2 limit.  Rpc
; is used when, for example, we plan to print some punctuation, like a comma,
; after a form and want to ensure that we can do it without overflowing the
; right margin.  (One might think that the desired effect could be obtained by
; setting width smaller, but that is wrong because it narrows the whole field
; and we only want to guarantee space on the last line.)  Here is an example.
; Use ctrl-x = in emacs to see what columns things are in.  The semi-colons are
; in column 0.  Pretend they are all spaces, as they would be if the printing
; had been done by fmt-ppr.

; (foobar
;   (here is a long arg)
;   a)                  

; Here, col = 2, width = 23, and rpc = 19!

; Infix Hack:
; We simply print out $ followed by the expression.  We print the
; expression in lower-case.

  (declare (ignore termp width rpc col eviscp))
  (let ((*print-case* :downcase)
        (*print-pretty* t))
    (princ "$ " file)
    (prin1 x file)))

(defun fmt-ppr (x termp width rpc col channel state eviscp)
  (declare (type (signed-byte 29) col))
  #+acl2-loop-only
  (declare (ignore termp))
  #-acl2-loop-only
  (cond
   ((and (live-state-p state)
         (output-in-infixp state))
    (print-infix x termp width rpc col
                 (get-output-stream-from-channel channel)
                 eviscp)
    (return-from fmt-ppr *the-live-state*)))
  (ppr2 (ppr1 x (acl2-print-base) width rpc state eviscp)
        col channel state eviscp))

(mutual-recursion

(defun fmt0* (str0 str1 str2 str3 lst alist col channel state evisc-tuple)

; This odd function prints out the members of lst.  If the list has no
; elements, str0 is used.  If the list has 1 element, str1 is used
; with #\* bound to the element.  If the list has two elements, str2
; is used with #\* bound to the first element and then str1 is used
; with #\* bound to the second.  If the list has more than two
; elements, str3 is used with #\* bound successively to each element
; until there are only two left.  The function is used in the
; implementation of ~&, ~v, and ~*.

  (declare (type (signed-byte 29) col)
           (type string str0 str1 str2 str3))
  (the2s
   (signed-byte 29)
   (cond ((null lst)
          (fmt0 str0 alist 0 (the-fixnum! (length str0) 'fmt0*) col channel
                state evisc-tuple))
         ((null (cdr lst))
          (fmt0 str1
                (cons (cons #\* (car lst)) alist)
                0 (the-fixnum! (length str1) 'fmt0*) col channel
                state evisc-tuple))
         ((null (cddr lst))
          (mv-letc (col state)
                   (fmt0 str2
                         (cons (cons #\* (car lst)) alist)
                         0 (the-fixnum! (length str2) 'fmt0*)
                         col channel state evisc-tuple)
                   (fmt0* str0 str1 str2 str3 (cdr lst) alist col channel
                          state evisc-tuple)))
         (t (mv-letc (col state)
                     (fmt0 str3
                           (cons (cons #\* (car lst)) alist)
                           0 (the-fixnum! (length str3) 'fmt0*)
                           col channel state evisc-tuple)
                     (fmt0* str0 str1 str2 str3 (cdr lst) alist col channel
                            state evisc-tuple))))))

(defun fmt0&v (flg lst punct col channel state evisc-tuple)
  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (case flg
     (&
      (case
          punct
        (#\. (fmt0* "" "~x*." "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\, (fmt0* "" "~x*," "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\: (fmt0* "" "~x*:" "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\; (fmt0* "" "~x*;" "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\! (fmt0* "" "~x*!" "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\) (fmt0* "" "~x*)" "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\? (fmt0* "" "~x*?" "~x* and " "~x*, " lst nil col channel
                    state evisc-tuple))
        (otherwise
         (fmt0* "" "~x*" "~x* and " "~x*, " lst nil col channel
                state evisc-tuple))))
     (otherwise
      (case
          punct
        (#\. (fmt0* "" "~x*." "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\, (fmt0* "" "~x*," "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\: (fmt0* "" "~x*:" "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\; (fmt0* "" "~x*;" "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\! (fmt0* "" "~x*!" "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\) (fmt0* "" "~x*)" "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (#\? (fmt0* "" "~x*?" "~x* or " "~x*, " lst nil col channel
                    state evisc-tuple))
        (otherwise
         (fmt0* "" "~x*" "~x* or " "~x*, " lst nil col channel
                state evisc-tuple)))))))

(defun spell-number (n cap col channel state evisc-tuple)

; If n is an integerp we spell out the name of the cardinal number n
; (for a few cases) or else we just print the decimal representation
; of n.  E.g., n=4 makes us spell "four".  If n is a consp then we
; assume its car is an integer and we spell the corresponding ordinal
; number, e.g., n= '(4 . th) makes us spell "fourth".  We capitalize
; the word if cap is t.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (let ((str
          (cond ((integerp n)
                 (cond ((int= n 0) (if cap "Zero" "zero"))
                       ((int= n 1) (if cap "One" "one"))
                       ((int= n 2) (if cap "Two" "two"))
                       ((int= n 3) (if cap "Three" "three"))
                       ((int= n 4) (if cap "Four" "four"))
                       ((int= n 5) (if cap "Five" "five"))
                       ((int= n 6) (if cap "Six" "six"))
                       ((int= n 7) (if cap "Seven" "seven"))
                       ((int= n 8) (if cap "Eight" "eight"))
                       ((int= n 9) (if cap "Nine" "nine"))
                       ((int= n 10) (if cap "Ten" "ten"))
                       ((int= n 11) (if cap "Eleven" "eleven"))
                       ((int= n 12) (if cap "Twelve" "twelve"))
                       ((int= n 13) (if cap "Thirteen" "thirteen"))
                       (t "~x0")))
                ((and (consp n)
                      (<= 0 (car n))
                      (<= (car n) 13))
                 (cond ((int= (car n) 0) (if cap "Zeroth" "zeroth"))
                       ((int= (car n) 1) (if cap "First" "first"))
                       ((int= (car n) 2) (if cap "Second" "second"))
                       ((int= (car n) 3) (if cap "Third" "third"))
                       ((int= (car n) 4) (if cap "Fourth" "fourth"))
                       ((int= (car n) 5) (if cap "Fifth" "fifth"))
                       ((int= (car n) 6) (if cap "Sixth" "sixth"))
                       ((int= (car n) 7) (if cap "Seventh" "seventh"))
                       ((int= (car n) 8) (if cap "Eighth" "eighth"))
                       ((int= (car n) 9) (if cap "Ninth" "ninth"))
                       ((int= (car n) 10) (if cap "Tenth" "tenth"))
                       ((int= (car n) 11) (if cap "Eleventh" "eleventh"))
                       ((int= (car n) 12) (if cap "Twelfth" "twelfth"))
                       (t (if cap "Thirteenth" "thirteenth"))))
                (t (let ((d (mod (abs (car n)) 10)))

; We print -11th, -12th, -13th, ... -20th, -21st, -22nd, etc., though
; what business anyone has using negative ordinals I can't imagine.

                     (cond ((or (int= d 0)
                                (> d 3)
                                (int= (car n) -11)
                                (int= (car n) -12)
                                (int= (car n) -13))
                            "~x0th")
                           ((int= d 1) "~x0st")
                           ((int= d 2) "~x0nd")
                           (t "~x0rd")))))))

     (fmt0 (the-string! str 'spell-number)
           (cond ((integerp n)
                  (cond ((and (<= 0 n) (<= n 13)) nil)
                        (t (list (cons #\0 n)))))
                 (t (cond ((and (<= 0 (car n)) (<= (car n) 13)) nil)
                          (t (list (cons #\0 (car n)))))))
           0 (the-fixnum! (length str) 'spell-number)
           col channel state evisc-tuple))))

(defun fmt-symbol-name (s col channel state)

; This function is misnamed.  S ought to be an acl2-numberp, a symbol or a
; string.  We print it out, breaking on hyphens but not being fooled by fmt
; directives inside it.  We return the new col and state.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (cond
    ((acl2-numberp s)
     (pprogn (prin1$ s channel state)
             (mv (flsz-atom s (acl2-print-base state) col state) state)))
    ((stringp s)
     (fmt-symbol-name1 s 0 (the-fixnum! (length s) 'fmt-symbol-name) col
                       channel state))
    (t
     (let ((str (symbol-name s)))
       (cond
        ((keywordp s)
         (cond
          ((may-need-slashes str)
           (fmt0 ":|~s0|" (list (cons #\0 str)) 0 6 col channel state nil))
          (t (fmt0 ":~s0" (list (cons #\0 str)) 0 4 col channel state nil))))
        ((or (equal (symbol-package-name s)
                    (f-get-global 'current-package state))
             (member-eq
              s
              (package-entry-imports
               (find-package-entry
                (f-get-global 'current-package state)
                (known-package-alist state)))))
         (cond
          ((may-need-slashes str)
           (fmt0 "|~s0|" (list (cons #\0 str)) 0 5 col channel state nil))
          (t (fmt-symbol-name1 str 0
                               (the-fixnum! (length str) 'fmt-symbol-name)
                               col channel state))))
        (t
         (let ((p (symbol-package-name s)))
           (cond
            ((may-need-slashes p)
             (cond
              ((may-need-slashes str)
               (fmt0 "|~s0|::~-|~s1|"
                     (list (cons #\0 p)
                           (cons #\1 str))
                     0 14 col channel state nil))
              (t (fmt0 "|~s0|::~-~s1"
                       (list (cons #\0 p)
                             (cons #\1 str))
                       0 12 col channel state nil))))
            ((may-need-slashes str)
             (fmt0 "~s0::~-|~s1|"
                   (list (cons #\0 p)
                         (cons #\1 str))
                   0 12 col channel state nil))
            (t (fmt0 "~s0::~-~s1"
                     (list (cons #\0 p)
                           (cons #\1 str))
                     0 10 col channel state nil)))))))))))

(defun fmt0 (s alist i maximum col channel state evisc-tuple)
  (declare (type (signed-byte 29) i maximum col)
           (type string s))

; WARNING:  If you add new tilde-directives update :DOC fmt and the
; copies in :DOC fmt1 and :DOC fms.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (cond
    ((>= i maximum)
     (mv col state))
    (t
     (let ((c (charf s i)))
       (declare (type character c))
       (cond
        ((eql c #\~)
         (let ((fmc (the character (fmt-char s i 1 maximum t))))
           (declare (type character fmc))
           (case
            fmc
             ((#\p #\q #\P #\Q)

; These directives print terms.  If 'infixp is t or :out, we use infix
; printing.  Otherwise we use s-expr printing.  We assume the term has already
; been untranslated.

; The difference between the lowercase directives and the uppercase ones
; is that the uppercase ones take two fmt-vars, e.g., ~P01, and use the
; contents of the second one as the evisceration value.  Otherwise the
; uppercase directives behave as their lowercase counterparts.

; On symbols, ~p and ~q are alike and just print starting in col.  On non-
; symbols they both prettyprint.  But ~q starts printing in col while ~p
; may do a terpri and indent first.  ~p concludes with a terpri if
; it put out a terpri before printing.  ~q always concludes with a terpri
; on non-symbols, so you know where you end up.

              (maybe-newline
               (let* ((local-evisc-tuple
                       (cond ((or (eql fmc #\P)
                                  (eql fmc #\Q))
                              (fmt-var s alist (1+f i) maximum))
                             (t evisc-tuple)))

; Here is the place we unpack (evisc-tuple ...) or (default-evisc-tuple ...).

                      (x (cond
                          (local-evisc-tuple
                           (eviscerate
                            (fmt-var s alist i maximum)
                            (cadr local-evisc-tuple)          ;;; print-level
                            (caddr local-evisc-tuple)         ;;; print-length
                            (car local-evisc-tuple)           ;;; alist
                            (cadddr local-evisc-tuple)))      ;;; hiding-cars
                          (t (fmt-var s alist i maximum)))))
                 (let ((fmt-hard-right-margin
                        (fmt-hard-right-margin state)))
                   (declare (type (signed-byte 29) fmt-hard-right-margin))
                   (let ((sz (flsz x t col fmt-hard-right-margin state
                                   local-evisc-tuple)))
                     (declare (type (signed-byte 29) sz))
                     (cond
                      ((and (or (eql fmc #\p)
                                (eql fmc #\P))
                            (> col (the-fixnum *fmt-ppr-indentation*))
                            (>= sz fmt-hard-right-margin)
                            (not (>= (flsz x
                                           t
                                           (the-fixnum
                                            *fmt-ppr-indentation*)
                                           fmt-hard-right-margin
                                           state local-evisc-tuple)
                                     fmt-hard-right-margin)))
                       (pprogn
                        (newline channel state)
                        (spaces1 (the-fixnum *fmt-ppr-indentation*) 0
                                 fmt-hard-right-margin
                                 channel state)
                        (fmt0 s alist i maximum
                              (the-fixnum *fmt-ppr-indentation*)
                              channel state evisc-tuple)))
                      ((or (eql fmc #\q)
                           (eql fmc #\Q)
                           (>= sz fmt-hard-right-margin))
                       (pprogn
                        (cond ((or (eql fmc #\q)
                                   (eql fmc #\Q))
                               state)
                              ((= col 0) state)
                              (t (newline channel state)))
                        (if (or (eql fmc #\q)
                                (eql fmc #\Q))
                            state
                          (spaces1 (the-fixnum *fmt-ppr-indentation*)
                                   0 fmt-hard-right-margin channel state))
                        (let ((c (fmt-char s i
                                           (the-fixnum
                                            (if (or (eql fmc #\P)
                                                    (eql fmc #\Q))
                                                4
                                              3))
                                           maximum nil)))
                          (cond ((punctp c)
                                 (pprogn
                                  (fmt-ppr
                                   x
                                   t
                                   (+f fmt-hard-right-margin
                                       (-f (if (or (eql fmc #\q)
                                                   (eql fmc #\Q))
                                               col
                                             *fmt-ppr-indentation*)))
                                   1
                                   (the-fixnum
                                    (if (or (eql fmc #\q)
                                            (eql fmc #\Q))
                                        col
                                      *fmt-ppr-indentation*))
                                   channel state local-evisc-tuple)
                                  (princ$ c channel state)
                                  (newline channel state)
                                  (fmt0 s alist
                                        (scan-past-whitespace
                                         s
                                         (+f i
                                             (if (or (eql fmc #\P)
                                                     (eql fmc #\Q))
                                                 5
                                               4))
                                         maximum)
                                        maximum 0 channel state
                                        evisc-tuple)))
                                (t
                                 (pprogn
                                  (fmt-ppr
                                   x
                                   t
                                   (+f fmt-hard-right-margin
                                       (-f (if (or (eql fmc #\q)
                                                   (eql fmc #\Q))
                                               col
                                             *fmt-ppr-indentation*)))
                                   0
                                   (the-fixnum
                                    (if (or (eql fmc #\q)
                                            (eql fmc #\Q))
                                        col
                                      *fmt-ppr-indentation*))
                                   channel state local-evisc-tuple)
                                  (newline channel state)
                                  (fmt0 s alist
                                        (scan-past-whitespace
                                         s
                                         (+f i (if (or (eql fmc #\P)
                                                       (eql fmc #\Q))
                                                   4
                                                 3))
                                         maximum)
                                        maximum 0 channel state
                                        evisc-tuple)))))))
                      (t (pprogn
                          (flpr x t channel state local-evisc-tuple)
                          (fmt0 s alist
                                (+f i (if (or (eql fmc #\P)
                                              (eql fmc #\Q))
                                          4
                                        3))
                                maximum sz
                                channel state evisc-tuple)))))))))
             ((#\x #\y #\X #\Y)

; The difference between the lowercase directives and the uppercase ones
; is that the uppercase ones take two fmt-vars, e.g., ~X01, and use the
; contents of the second one as the evisceration value.  Otherwise the
; uppercase directives behave as their lowercase counterparts.

; On symbols, ~x and ~y are alike and just print starting in col.  On non-
; symbols they both prettyprint.  But ~y starts printing in col while ~x
; may do a terpri and indent first.  ~x concludes with a terpri if
; it put out a terpri before printing.  ~y always concludes with a terpri
; on non-symbols, so you know where you end up.

              (maybe-newline
               (let* ((local-evisc-tuple
                       (cond ((or (eql fmc #\X)
                                  (eql fmc #\Y))
                              (fmt-var s alist (1+f i) maximum))
                             (t evisc-tuple)))

; Here is the place we unpack (evisc-tuple ...) or (default-evisc-tuple ...).

                      (x (cond
                          (local-evisc-tuple
                           (eviscerate
                            (fmt-var s alist i maximum)
                            (cadr local-evisc-tuple)          ;;; print-level
                            (caddr local-evisc-tuple)         ;;; print-length
                            (car local-evisc-tuple)           ;;; alist
                            (cadddr local-evisc-tuple)))      ;;; hiding-cars
                          (t (fmt-var s alist i maximum)))))
                 (cond
                  ((or (symbolp x)
                       (acl2-numberp x))
                   (mv-letc (col state)
                            (fmt-symbol-name x col channel state)
                            (fmt0 s alist
                                  (+f i (if (or (eql fmc #\X)
                                                (eql fmc #\Y))
                                            4
                                          3))
                                  maximum col channel state evisc-tuple)))
                  (t (let ((fmt-hard-right-margin
                            (fmt-hard-right-margin state)))
                       (declare (type (signed-byte 29) fmt-hard-right-margin))
                       (let ((sz (flsz x nil col fmt-hard-right-margin state
                                       local-evisc-tuple)))
                         (declare (type (signed-byte 29) sz))
                         (cond
                          ((and (or (eql fmc #\x)
                                    (eql fmc #\X))
                                (> col (the-fixnum *fmt-ppr-indentation*))
                                (>= sz fmt-hard-right-margin)
                                (not (>= (flsz x
                                               nil
                                               (the-fixnum
                                                *fmt-ppr-indentation*)
                                               fmt-hard-right-margin
                                               state local-evisc-tuple)
                                         fmt-hard-right-margin)))
                           (pprogn
                            (newline channel state)
                            (spaces1 (the-fixnum *fmt-ppr-indentation*) 0
                                     fmt-hard-right-margin
                                     channel state)
                            (fmt0 s alist i maximum
                                  (the-fixnum *fmt-ppr-indentation*)
                                  channel state evisc-tuple)))
                          ((or (eql fmc #\y)
                               (eql fmc #\Y)
                               (>= sz fmt-hard-right-margin))
                           (pprogn
                            (cond ((or (eql fmc #\y)
                                       (eql fmc #\Y))
                                   state)
                                  ((= col 0) state)
                                  (t (newline channel state)))
                            (if (or (eql fmc #\y)
                                    (eql fmc #\Y))
                                state
                              (spaces1 (the-fixnum *fmt-ppr-indentation*)
                                       0 fmt-hard-right-margin channel state))
                            (let ((c (fmt-char s i
                                               (the-fixnum
                                                (if (or (eql fmc #\X)
                                                        (eql fmc #\Y))
                                                    4
                                                  3))
                                               maximum nil)))
                              (cond ((punctp c)
                                     (pprogn
                                      (fmt-ppr
                                       x
                                       nil
                                       (+f fmt-hard-right-margin
                                           (-f (if (or (eql fmc #\y)
                                                       (eql fmc #\Y))
                                                   col
                                                 *fmt-ppr-indentation*)))
                                       1
                                       (the-fixnum
                                        (if (or (eql fmc #\y)
                                                (eql fmc #\Y))
                                            col
                                          *fmt-ppr-indentation*))
                                       channel state local-evisc-tuple)
                                      (princ$ c channel state)
                                      (newline channel state)
                                      (fmt0 s alist
                                            (scan-past-whitespace
                                             s
                                             (+f i (if (or (eql fmc #\X)
                                                           (eql fmc #\Y))
                                                       5
                                                     4))
                                             maximum)
                                            maximum 0 channel state
                                            evisc-tuple)))
                                    (t
                                     (pprogn
                                      (fmt-ppr
                                       x
                                       nil
                                       (+f fmt-hard-right-margin
                                           (-f (if (or (eql fmc #\y)
                                                       (eql fmc #\Y))
                                                   col
                                                 *fmt-ppr-indentation*)))
                                       0
                                       (the-fixnum
                                        (if (or (eql fmc #\y)
                                                (eql fmc #\Y))
                                            col
                                          *fmt-ppr-indentation*))
                                       channel state local-evisc-tuple)
                                      (newline channel state)
                                      (fmt0 s alist
                                            (scan-past-whitespace
                                             s
                                             (+f i (if (or (eql fmc #\X)
                                                           (eql fmc #\Y))
                                                       4
                                                     3))
                                             maximum)
                                            maximum 0 channel state
                                            evisc-tuple)))))))
                          (t (pprogn
                              (flpr x nil channel state local-evisc-tuple)
                              (fmt0 s alist
                                    (+f i (if (or (eql fmc #\X)
                                                  (eql fmc #\Y))
                                              4
                                            3))
                                    maximum sz
                                    channel state evisc-tuple)))))))))))
             (#\@ (let ((s1 (fmt-var s alist i maximum)))
                    (mv-letc (col state)
                             (cond ((stringp s1)
                                    (fmt0 s1 alist 0
                                          (the-fixnum! (length s1) 'fmt0)
                                          col channel state evisc-tuple))
                                   ((consp s1)
                                    (fmt0 (car s1)
                                          (append (cdr s1) alist)
                                          0
                                          (the-fixnum! (length (car s1)) 'fmt0)
                                          col channel state evisc-tuple))
                                   (t (mv (er-hard-val 0 'fmt0
                                              "Illegal Fmt Syntax.  The ~
                                               tilde-@ directive at position ~
                                               ~x0 of the string below is ~
                                               illegal because its variable ~
                                               evaluated to ~x1, which is ~
                                               neither a string nor a ~
                                               list.~|~%~x2"
                                              i s1 s)
                                          state)))
                             (fmt0 s alist (+f i 3) maximum col
                                   channel state evisc-tuple))))
             (#\# (let ((n (find-alternative-start
                            (fmt-var s alist i maximum) s i maximum)))
                    (declare (type (signed-byte 29) n))
                    (let ((m (find-alternative-stop s n maximum)))
                      (declare (type (signed-byte 29) m))
                      (let ((o (find-alternative-skip s m maximum)))
                        (declare (type (signed-byte 29) o))
                        (mv-letc (col state) (fmt0 s alist
                                                   (the-fixnum n)
                                                   (the-fixnum m)
                                                   col channel
                                                   state evisc-tuple)
                                 (fmt0 s alist (the-fixnum o) maximum
                                       col channel state evisc-tuple))))))
             (#\* (let ((x (fmt-var s alist i maximum)))
                    (mv-letc (col state)
                             (fmt0* (car x) (cadr x) (caddr x) (cadddr x)
                                    (car (cddddr x))
                                    (append (cdr (cddddr x)) alist)
                                    col channel state evisc-tuple)
                             (fmt0 s alist (+f i 3) maximum col
                                   channel state evisc-tuple))))
             (#\& (let ((i+3 (+f i 3)))
                    (declare (type (signed-byte 29) i+3))
                    (mv-letc (col state)
                             (fmt0&v '&
                                     (fmt-var s alist i maximum)
                                     (punctp (and (< i+3 maximum)
                                                  (char s i+3)))
                                     col channel state evisc-tuple)
                             (fmt0 s alist
                                   (the-fixnum
                                    (cond
                                     ((punctp (and (< i+3 maximum)
                                                   (char s i+3)))
                                      (+f i 4))
                                     (t i+3)))
                                   maximum
                                   col channel state evisc-tuple))))
             (#\v (let ((i+3 (+f i 3)))
                    (declare (type (signed-byte 29) i+3))
                    (mv-letc (col state)
                             (fmt0&v 'v
                                     (fmt-var s alist i maximum)
                                     (punctp (and (< i+3 maximum)
                                                  (char s i+3)))
                                     col channel state evisc-tuple)
                             (fmt0 s alist
                                   (the-fixnum
                                    (cond
                                     ((punctp (and (< i+3 maximum)
                                                   (char s i+3)))
                                      (+f i 4))
                                     (t i+3)))
                                   maximum
                                   col channel state evisc-tuple))))
             (#\n (maybe-newline
                   (mv-letc (col state)
                            (spell-number (fmt-var s alist i maximum)
                                          nil col channel state evisc-tuple)
                            (fmt0 s alist (+f i 3) maximum col channel
                                  state evisc-tuple))))
             (#\N (maybe-newline
                   (mv-letc (col state)
                            (spell-number (fmt-var s alist i maximum)
                                          t col channel state evisc-tuple)
                            (fmt0 s alist (+f i 3) maximum col channel
                                  state evisc-tuple))))
             (#\t (maybe-newline
                   (let ((goal-col (fmt-var s alist i maximum))
                         (fmt-hard-right-margin (fmt-hard-right-margin state)))
                     (declare (type (signed-byte 29)
                                    goal-col fmt-hard-right-margin))
                     (pprogn
                      (cond ((> goal-col fmt-hard-right-margin)
                             (let ((er (er hard 'fmt0
                                           "It is illegal to tab past the ~
                                            value of (@ ~
                                            fmt-hard-right-margin), ~x0, and ~
                                            hence the directive ~~t~s1 to tab ~
                                            to column ~x2 is illegal.  See ~
                                            :DOC set-fmt-hard-right-margin."
                                           fmt-hard-right-margin
                                           (string (fmt-char s i 2 maximum t))
                                           goal-col)))
                               (declare (ignore er))
                               state))
                            ((>= col goal-col)
                             (pprogn (newline channel state)
                                     (spaces1 (the-fixnum goal-col) 0
                                              fmt-hard-right-margin
                                              channel state)))
                            (t (spaces1 (-f goal-col col) col
                                        fmt-hard-right-margin
                                        channel state)))
                      (fmt0 s alist (+f i 3) maximum
                            (the-fixnum goal-col)
                            channel state evisc-tuple)))))
             (#\c (maybe-newline
                   (let ((pair (fmt-var s alist i maximum)))
                     (cond ((and (consp pair)
                                 (integerp (car pair))
                                 (integerp (cdr pair))
                                 (>= (cdr pair) 0))
                            (mv-letc (col state)
                                     (left-pad-with-blanks (car pair)
                                                           (cdr pair)
                                                           col channel state)
                                     (fmt0 s alist (+f i 3) maximum col channel
                                           state evisc-tuple)))
                           (t (mv (er-hard-val 0 'fmt0
                                      "Illegal Fmt Syntax.  The tilde-c ~
                                       directive at position ~x0 of the string ~
                                       below is illegal because its variable ~
                                       evaluated to ~x1, which is not of the ~
                                       form (n . width), where n and width are ~
                                       integers and width is ~
                                       nonnegative.~|~%~x2"
                                      i pair s)
                                  state))))))
             ((#\f #\F)
              (maybe-newline
               (mv-letc (col state)
                        (splat (fmt-var s alist i maximum)
                               (acl2-print-base state)
                               (if (eql fmc #\F) (1+f col) 0)
                               col channel state)
                        (fmt0 s alist (+f i 3) maximum col channel
                              state evisc-tuple))))
             (#\s (maybe-newline
                   (mv-letc (col state)
                            (fmt-symbol-name (fmt-var s alist i maximum)
                                             col channel state)
                            (fmt0 s alist (+f i 3) maximum col channel
                                  state evisc-tuple))))
             (#\Space (let ((fmt-hard-right-margin
                             (fmt-hard-right-margin state)))
                        (declare (type (signed-byte 29) fmt-hard-right-margin))
                        (pprogn
                         (cond ((> col fmt-hard-right-margin)
                                (newline channel state))
                               (t state))
                         (princ$ #\Space channel state)
                         (fmt0 s alist (+f i 2) maximum
                               (cond ((> col fmt-hard-right-margin)
                                      1)
                                     (t (1+f col)))
                               channel state evisc-tuple))))
             (#\_ (maybe-newline
                   (let ((fmt-hard-right-margin
                          (fmt-hard-right-margin state)))
                     (declare (type (signed-byte 29) fmt-hard-right-margin))
                     (let ((n (the-half-fixnum! (fmt-var s alist i maximum)
                                                'fmt0)))
                       (declare (type (signed-byte 29) n))
                       (let ((new-col (+f col n)))
                         (declare (type (signed-byte 29) new-col))
                         (pprogn
                          (spaces n col channel state)
                          (cond
                           ((> new-col fmt-hard-right-margin)
                            (newline channel state))
                           (t state))
                          (fmt0 s alist (+f i 3) maximum
                                (the-fixnum
                                 (cond
                                  ((> new-col fmt-hard-right-margin)
                                   0)
                                  (t new-col)))
                                channel state evisc-tuple)))))))
             (#\Newline
              (fmt0 s alist (scan-past-whitespace s (+f i 2) maximum)
                    maximum col channel state evisc-tuple))
             (#\| (pprogn
                   (if (int= col 0) state (newline channel state))
                   (fmt0 s alist (+f i 2)
                         maximum 0 channel state evisc-tuple)))
             (#\% (pprogn
                   (newline channel state)
                   (fmt0 s alist (+f i 2)
                         maximum 0 channel state evisc-tuple)))
             (#\~ (maybe-newline
                   (pprogn
                    (princ$ #\~ channel state)
                    (fmt0 s alist (+f i 2) maximum (1+f col) channel
                          state evisc-tuple))))
             (#\- (cond ((> col (fmt-soft-right-margin state))
                         (pprogn
                          (princ$ #\- channel state)
                          (newline channel state)
                          (fmt0 s alist
                                (scan-past-whitespace s (+f i 2) maximum)
                                maximum 0 channel state evisc-tuple)))
                        (t (fmt0 s alist (+f i 2) maximum col channel
                                 state evisc-tuple))))
             (otherwise (let ((x
                               (er hard 'fmt0
                                   "Illegal Fmt Syntax.  The tilde ~
                                     directive at position ~x0 of the ~
                                     string below is unrecognized.~|~%~x1"
                                   i s)))
                          (declare (ignore x))
                          (mv 0 state))))))
        ((and (> col (fmt-soft-right-margin state))
              (eql c #\Space))
         (pprogn (newline channel state)
                 (fmt0 s alist
                       (scan-past-whitespace s (+f i 1) maximum)
                       maximum
                       0 channel state evisc-tuple)))
        ((and (>= col (fmt-soft-right-margin state))
              (eql c #\-))
         (pprogn (princ$ c channel state)
                 (newline channel state)
                 (fmt0 s alist
                       (scan-past-whitespace s (+f i 1) maximum)
                       maximum
                       0 channel state evisc-tuple)))
;       ((and (eql c #\Space)
; I cut out this code in response to Kaufmann's complaint 38.  The idea is
; *not* to ignore spaces after ~% directives.  I've left the code here to
; remind me of what I used to do, in case I see output that is malformed.
;            (int= col 0))
;       (fmt0 s alist (+f i 1) maximum 0 channel state evisc-tuple))
        (t (maybe-newline
            (pprogn (princ$ c channel state)
                    (fmt0 s alist (+f i 1) maximum
                          (if (eql c #\Newline) 0 (+f col 1))
                          channel state evisc-tuple))))))))))

)

(defun tilde-*-&v-strings (flg lst punct)

; This function returns an object that when bound to #\0 will cause
; ~*0 to print a conjunction (flg='&) or disjunction (flg='v) of the
; strings in lst, followed by punctuation punct, which must be #\. or
; #\,.

; WARNING:  This displayed strings are not equal to the strings in lst
; because whitespace may be inserted!

; ~& doesn't print a list of short strings very well because the first
; group is printed flat across the line, then when the line gets too
; long, the next string is indented and followed by a newline, which
; allows another bunch to be printed flat.  This function prints them
; with ~s which actually breaks the strings up internally in a way
; that does not preserve their equality.  "history-management.lisp"
; might have a newline inserted after the hyphen.

  (case
   flg
   (&
    (case
     punct
     (#\. (list "" "\"~s*\"." "\"~s*\" and " "\"~s*\", " lst))
     (#\, (list "" "\"~s*\"," "\"~s*\" and " "\"~s*\", " lst))
     (#\: (list "" "\"~s*\":" "\"~s*\" and " "\"~s*\", " lst))
     (#\; (list "" "\"~s*\";" "\"~s*\" and " "\"~s*\", " lst))
     (#\! (list "" "\"~s*\"!" "\"~s*\" and " "\"~s*\", " lst))
     (#\) (list "" "\"~s*\")" "\"~s*\" and " "\"~s*\", " lst))
     (#\? (list "" "\"~s*\"?" "\"~s*\" and " "\"~s*\", " lst))
     (otherwise
      (list "" "\"~s*\"" "\"~s*\" and " "\"~s*\", " lst))))
   (otherwise
    (case
     punct
     (#\. (list "" "\"~s*\"." "\"~s*\" or " "\"~s*\", " lst))
     (#\, (list "" "\"~s*\"," "\"~s*\" or " "\"~s*\", " lst))
     (#\: (list "" "\"~s*\":" "\"~s*\" or " "\"~s*\", " lst))
     (#\; (list "" "\"~s*\";" "\"~s*\" or " "\"~s*\", " lst))
     (#\! (list "" "\"~s*\"!" "\"~s*\" or " "\"~s*\", " lst))
     (#\) (list "" "\"~s*\")" "\"~s*\" or " "\"~s*\", " lst))
     (#\? (list "" "\"~s*\"?" "\"~s*\" or " "\"~s*\", " lst))
     (otherwise
      (list "" "\"~s*\"" "\"~s*\" or " "\"~s*\", " lst))))))

(defun fmt1 (str alist col channel state evisc-tuple)

; WARNING:  The master copy of the tilde-directives list is in :DOC fmt.

  ":Doc-Section ACL2::Programming

  ~c[:(str alist col co-channel state evisc) => (mv col state)]~/

  ~l[fmt] for further explanation, including documentation of the
  tilde-directives.~/~/"

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   #-acl2-loop-only
   (mv-let (col state)
           (fmt0 (the-string! str 'fmt1) alist 0
                 (the-fixnum! (length str) 'fmt1)
                 (the-fixnum! col 'fmt1)
                 channel state evisc-tuple)
           (declare (type (signed-byte 29) col))

; Allegro 6.0 needs explicit calls of finish-output in order to flush to
; standard output when *print-pretty* is nil.

           (progn #+(and allegro allegro-version>= (version>= 6 0))
                  (if (eq channel *standard-co*)
                      (finish-output
                       (get-output-stream-from-channel *standard-co*)))
                  (mv col state)))
   #+acl2-loop-only
   (fmt0 (the-string! str 'fmt1) alist 0
         (the-fixnum! (length str) 'fmt1)
         (the-fixnum! col 'fmt1)
         channel state evisc-tuple)))

(defun fmt (str alist channel state evisc-tuple)

; WARNING: IF you change the list of tilde-directives, change the copy of it in
; the :DOC for fmt1 and fms.

  ":Doc-Section ACL2::Programming

  formatted printing~/

  ACL2 provides the functions ~c[fmt], ~ilc[fmt1], and ~ilc[fms] as substitutes for Common
  Lisp's ~c[format] function.  Also ~pl[fmt!], ~pl[fmt1!], and ~pl[fms!] for
  versions of these functions that write forms to files in a manner that allows
  them to be read, by avoiding using backslash (~c[\\]) to break long lines.

  All three print a given string under an alist pairing character
  objects with values, interpreting certain ``tilde-directives'' in
  the string.  ~c[Channel] must be a character output channel (e.g.,
  ~ilc[*standard-co*]).
  ~bv[]
  General Forms:                                            result
  (fms string alist channel state evisc-tuple)         ; state
  (fmt string alist channel state evisc-tuple)         ; (mv col state)
  (fmt1 string alist column channel state evisc-tuple) ; (mv col state)
  ~ev[]
  ~ilc[Fms] and ~c[fmt] print an initial newline to put ~c[channel] in column ~c[0];
  ~ilc[Fmt1] requires the current column as input.  Columns are numbered
  from ~c[0].  The current column is the column into which the next
  character will be printed.  (Thus, the current column number is also
  the number of ~il[characters] printed since the last newline.)  The ~c[col]
  returned by ~c[fmt] and ~ilc[fmt1] is the current column at the conclusion of
  the formatting.  ~c[Evisc-tuple] must be either ~c[nil] (meaning no
  abbreviations are used when objects are printed) or an
  ``evisceration tuple'' such as that returned by
  ~c[(default-evisc-tuple state)].

  We list the tilde-directives below.  The notation is explained after
  the chart.
  ~bv[]
  ~~xx  pretty print vx (maybe after printing a newline)
  ~~yx  pretty print vx starting in current column; end with newline
  ~~Xxy like ~~xx but use vy as the evisceration tuple
  ~~Yxy like ~~yx but use vy as the evisceration tuple
  ~~px  pretty print term (maybe with infix) vx
       (maybe after printing a newline)
  ~~qx  pretty print term (maybe with infix) vx
       starting in current column; end with newline
  ~~Pxy like ~~px but use vy as the evisceration tuple
  ~~Qxy like ~~qx but use vy as the evisceration tuple
  ~~@x  if vx is a string, \"str\",  recursively format \"str\"
       if vx is (\"str\" . a), recursively format \"str\" under a+
  ~~#x~~[...~~/...~~/ ... ~~/...~~] cases on vx
       ^    ^     ...   ^  if 0<=vx<=k, choose vxth alternative
       0    1     ...   k  if vx is a list of length 1, case 0; else 1
  ~~*x  iterator: vx must be of the form
       (\"str0\" \"str1\" \"str2\" \"str3\" lst . a);
       if lst is initially empty, format \"str0\" under a+; otherwise,
       bind #\\* successively to the elements of lst and then
       recursively format \"stri\" under a+, where i=1 if there is one
       element left to process, i=2 if there are two left, and i=3
       otherwise.
  ~~&x  print elements of vx with ~~x, separated by commas and a
       final ``and''
  ~~vx  print elements of vx with ~~x, separated by commas and a
       final ``or''
  ~~nx  if vx is a small positive integer, print it as a word, e.g.,
       seven;
       if vx is a singleton containing a small positive integer, print
         the corresponding ordinal as a word, e.g., seventh
  ~~Nx  like ~~nx but the word is capitalized, e.g., Seven or Seventh
  ~~tx  tab out to column vx; newline first if at or past column vx
  ~~cx  vx is (n . w), print integer n right justified in field of
       width w
  ~~fx  print object vx flat over as many lines as necessary
  ~~Fx  same as ~~f, except that subsequent lines are indented to
       start one character to the right of the first character printed
  ~~sx  if vx is a symbol, print vx, breaking on hyphens; if vx is a
       string, print the characters in it, breaking on hyphens
  ~~    tilde space: print a space
  ~~_x  print vx spaces
  ~~
       tilde newline: skip following whitespace
  ~~%   output a newline
  ~~|   output a newline unless already on left margin
  ~~~~   print a tilde
  ~~-   if close to rightmargin, output a hyphen and newline; else
       skip this char
  ~ev[]
  If ~c[x] is a character, then ~c[vx] is the value of ~c[#\\x] under the
  current alist.  When we say ``format ~c[str] under ~c[a+]'' we mean
  recursively process the given string under an alist obtained by
  appending ~c[a] to the current alist.~/

  ACL2's formatting functions print to the indicated channel, keeping
  track of which column they are in.  ~ilc[Fmt1] can be used if the caller
  knows which column the channel is in (i.e., how many ~il[characters] have
  been printed since the last newline).  Otherwise, ~c[fmt] or ~ilc[fms] must be
  used, both of which output a newline so as to establish the column
  position at ~c[0].  Unlike Common Lisp's ~c[format] routine, ~c[fmt] and its
  relatives break the output into lines so as to try to avoid printing
  past column ~c[77].  That number is built-into the definitions of ACL2's
  formatting functions.  Line breaks are automatically inserted as
  necessary in place of spaces and after hyphens in the text being
  printed.

  The formatting functions scan the string from left to right,
  printing each successive character unless it is a tilde ~c[(~~)].  Upon
  encountering tildes the formatters take action determined by the
  character or ~il[characters] immediately following the tilde.  The
  typical tilde-directive is a group of three successive ~il[characters]
  from the string being printed.  For example, ~c[~~x0] is a 3 character
  ~c[tilde-directive].  The first character in a tilde-directive is always
  the tilde character itself.  The next character is called the
  ``command'' character.  The character after that is usually taken as
  the name of a ``format variable'' that is bound in the alist under
  which the string is being printed.  Format variables are, by
  necessity, ~il[characters].  The objects actually printed by a
  tilde-directive are the objects obtained by looking up the command's
  format variables in the alist.  Typical format variable names are ~c[0],
  ~c[1], ~c[2], ..., ~c[9], ~c[a], ~c[b], ~c[c], etc., and if a tilde-directive uses the
  format variable ~c[0], as in ~c[~~x0], then the character ~c[#\\0] must be bound
  in the alist.  Some tilde commands take no arguments and others take
  more than one, so some directives are of length two and others are
  longer.

  It should be noted that this use of ~il[characters] in the string to
  denote arguments is another break from Common Lisp's ~c[format] routine.
  In Common Lisp, the directives refer implicitly to the ``next item
  to be printed.''  But in ACL2 the directives name each item
  explicitly with our format variables.

  The following text contains examples that can be evaluated.  To make
  this process easier, we use a macro which is defined as part of ACL2
  just for this ~il[documentation].  The macro is named ~c[fmx] and it takes up
  to eleven arguments, the first of which is a format string, ~c[str], and
  the others of which are taken as the values of format variables.
  The variables used are ~c[#\\0] through ~c[#\\9].  The macro constructs an
  appropriate alist, ~c[a], and then evaluates
  ~c[(fmt str a *standard-co* state nil)].

  Thus,
  ~bv[]
  (fmx \"Here is v0, ~~x0, and here is v1, ~~x1.\"
       (cons 'value 0)
       (cons 'value 1))
  ~ev[]
  is just an abbreviation for
  ~bv[]
  (fmt \"Here is v0, ~~x0, and here is v1, ~~x1.\"
       (list (cons #\\0 (cons 'value 0))
             (cons #\\1 (cons 'value 1)))
       *standard-co*
       state
       nil)
  ~ev[]
  which returns ~c[(mv 53 state)] after printing the line
  ~bv[]
     Here is v0, (VALUE . 0), and here is v1, (VALUE . 1).
  ~ev[]
  We now devote special attention to three of the tilde-directives
  whose use is non-obvious.

  ~em[The Case Statement]

  ~c[~~#x] is essentially a ``case statement'' in the language of ~c[fmt].
  The proper form of the statement is
  ~bv[]
  ~~#x~~[case-0~~/case-1~~/ ... ~~/case-k~~],
  ~ev[]
  where each of the ~c[case-i] is a format string.  In the most common
  use, the variable ~c[x] has an integer value, ~c[vx], between ~c[0] and ~c[k],
  inclusive.  The effect of formatting the directive is to format
  ~c[case-vx].

  For example
  ~bv[]
  (fmx \"Go ~~#0~~[North~~/East~~/South~~/West~~].~~%\" 1)
  ~ev[]
  will print ``Go East.'' followed by a newline and will return

  ~c[(mv 0 state)], while if you change the ~c[1] above to ~c[3] (the
  maximum legal value), it will print ``Go West.''

  In order to make it easier to print such phrases as ``there are
  seven cases'' requiring agreement between subject and verb based on
  the number of elements of a list, the case statement allows its
  variable to take a list as its value and selects ~c[case-0] if the list
  has length ~c[1] and ~c[case-1] otherwise.
  ~bv[]
  (let ((cases '(a b c)))
    (fmx \"There ~~#0~~[is ~~n1 case~~/are ~~n1 cases~~].\"
         cases
         (length cases)))
  ~ev[]
  will print ``There are three cases.'' but if you change the

  ~c['(a b c)] above simply to ~c['(a)] it will print ``There is one
  case.'' and if you change it to ~c[nil] it will print ``There are
  zero cases.''

  ~em[Indirection]

  Roughly speaking, ~c[~~@] will act as though the value of its argument
  is a format string and splice it into the current string at the
  current position.  It is often used when the phrase to be printed
  must be computed.  For example,
  ~bv[]
  (let ((ev 'DEFUN))
   (fmx \"~~x0 is an event~~@1.\"
        'foo
        (if (member-eq ev '(defun defstub encapsulate))
            \" that may introduce a function symbol\"
            \"\")))
  ~ev[]
  will print ``~c[foo] is an event that may introduce a function
  symbol,'' but if the value of ~c[ev] is changed from ~c[']~ilc[defun] to ~c[']~ilc[defthm],
  it prints ``~c[foo] is an event.''  The ~c[~~@] directive ``splices'' in the
  computed phrase (which might be empty).  Of course, this particular
  example could be done with the case statement
  ~bv[]
  ~~#1~~[~~/ that may introduce a function symbol~~]
  ~ev[]
  where the value of ~c[#\\1] is appropriately computed to be ~c[0] or ~c[1].

  If the argument to ~c[~~@] is a pair, it is taken to be a format string
  ~ilc[cons]ed onto an alist, i.e., ~c[(\"str\" . a)], and the alist, ~c[a], is used
  to extend the current one before ~c[\"str\"] is recursively processed.
  This feature of ~c[fmt] can be used to pass around ``phrases'' that
  contain computed contextual information in ~c[a].  The most typical use
  is as ``error messages.''  For example, suppose you are writing a
  function which does not have access to ~ilc[state] and so cannot print an
  error message.  It may nevertheless be necessary for it to signal an
  error to its caller, say by returning two results, the first of
  which is interpreted as an error message if non-~c[nil].  Our convention
  is to use a ~c[~~@] pair to represent such messages.  For example, the
  error value might be produced by the code:
  ~bv[]
  (cons
    \"Error:  The instruction ~~x0 is illegal when the stack is ~~x1.~~%\"
    (list (cons #\\0 (current-instruction st))
          (cons #\\1 (i-stack st))))
  ~ev[]
  If the ~c[current-instruction] and ~c[i-stack] (whatever they are) are
  ~c['(popi 3)] and ~c['(a b)] when the ~ilc[cons] above is evaluated, then it
  produces
  ~bv[]
  '(\"Error:  The instruction ~~x0 is illegal when the stack is ~~x1.~~%\"
    (#\\0 POPI 3)
    (#\\1 A B))
  ~ev[]
  and if this pair is made the value of the ~c[fmt] variable ~c[0], then
  ~c[~~@0] will print
  ~bv[]
     Error:  The instruction (POPI 3) is illegal when the stack is (A B).
  ~ev[]
  For example, evaluate
  ~bv[]
  (let
   ((pair
    '(\"Error:  The instruction ~~x0 is illegal when the stack is ~~x1.~~%\"
      (#\\0 POPI 3)
      (#\\1 A B))))
   (fmx \"~~@0\" pair)).
  ~ev[]
  Thus, even though the function that produced the ``error'' could
  not print it, it could specify exactly what error message and data
  are to be printed.

  This example raises another issue.  Sometimes it is desirable to
  break lines in your format strings so as to make your source code
  more attractive.  That is the purpose of the ~c[tilde-newline]
  directive.  The following code produces exactly the same output as
  described above.
  ~bv[]
  (let ((pair '(\"Error:  The instruction ~~x0 ~~
                is illegal when the stack is ~~
                ~~x1.~~%\"
                (#\\0 POPI 3)
                (#\\1 A B))))
   (fmx \"~~@0\" pair)).
  ~ev[] 
  Finally, observe that when ~c[~~@0] extends the current alist, ~c[alist],
  with the one, ~c[a], in its argument, the bindings from ~c[a] are added to
  the front of ~c[alist], overriding the current values of any shared
  variables.  This ensures that the variable values seen by the
  recursively processed string, ~c[\"str\"], are those from ~c[a], but if
  ~c[\"str\"] uses variables not bound in ~c[a], their values are as specified
  in the original alist.  Intuitively, variables bound in ~c[a] are local
  to the processing of ~c[(\"str\" . a)] but ~c[\"str\"] may use ``global
  variables.''  The example above illustrates this because when the
  ~c[~~@0] is processed, ~c[#\\0] is bound to the error message pair.  But
  when the ~c[~~x0] in the error string is processed, ~c[#\\0] is bound to the
  illegal instruction.

  ~em[Iteration]

  The ~c[~~*] directive is used to process each element of a list.  For
  example,
  ~bv[]
  (let ((lst '(a b c d e f g h))) ; a true-list whose elements we exhibit
   (fmx \"~~*0\"
        `(\"Whoa!\"          ; what to print if there's nothing to print
          \"~~x*!\"           ; how to print the last element
          \"~~x* and \"       ; how to print the 2nd to last element
          \"~~x*, \"          ; how to print all other elements
          ,lst)))          ; the list of elements to print
  ~ev[] 
  will print ``~c[A, B, C, D, E, F, G and H!]''.  Try this example with
  other true list values of ~c[lst], such as ~c['(a b)], ~c['(a)], and ~c[nil].  The
  tilde-directives ~c[~~&0] and ~c[~~v0], which take a true list argument and
  display its elements separated by commas and a final ``and'' or
  ``or,'' are implemented in terms of the more general ~c[~~*].

  The ~c[~~*] directive allows the 5-tuple to specify in its final ~ilc[cdr] an
  alist with which to extend the current one before processing the
  individual elements.

  We often use ~c[~~*] to print a series of phrases, separated by suitable
  punctuation, whitespace and noise words.  In such use, the ~c[~~*]
  handles the separation of the phrases and each phrase is generally
  printed by ~c[~~@].

  Here is a complex example.  In the ~ilc[let*], below, we bind phrases to a
  list of ~c[~~@] pairs and then we create a ~c[~~*] 5-tuple to print out the
  conjunction of the phrases with a parenthetical ``finally!'' if the
  series is longer than 3.
  ~bv[]
  (let* ((phrases
          (list (list \"simplifying with the replacement rules ~~&0\"
                      (cons #\\0 '(rewrite-rule1 
                                  rewrite-rule2
                                  rewrite-rule3)))
                (list \"destructor elimination using ~~x0\"
                      (cons #\\0 'elim-rule))
                (list \"generalizing the terms ~~&0\"
                      (cons #\\0 '((rev x) (app u v))))
                (list \"inducting on ~~x0\"
                      (cons #\\0 'I))))
         (5-tuple
          (list
           \"magic\"                            ; no phrases
           \"~~@*\"                              ; last phrase
           \"~~@*, and~~#f~~[~~/ (finally!)~~] \"    ; second to last phrase
           \"~~@*, \"                            ; other phrases
           phrases                            ; the phrases themselves
           (cons #\\f 
                 (if (>(length phrases) 3) 1 0))))) ;print ``finally''?
    (fmx \"We did it by ~~*0.\" 5-tuple))
  ~ev[]
  This ~ilc[let*] prints
  ~bv[]
     We did it by simplifying with the replacement rules REWRITE-RULE1,
     REWRITE-RULE2 and REWRITE-RULE3, destructor elimination using ELIM-
     RULE, generalizing the terms (REV X) and (APP U V), and (finally!)
     inducting on I.
  ~ev[]
  You might wish to try evaluating the ~ilc[let*] after removing elements
  of phrases.

  Most of the output produced by ACL2 is produced via ~c[fmt] statements.
  Thus, inspection of the source code will yield many examples.  A
  complicated example is the code that explains the simplifier's work.
  See ~c[:]~ilc[pc] ~c[simplify-clause-msg1].  An ad hoc example is provided by the
  function ~c[fmt-doc-example], which takes two arguments: an arbitrary
  true list and ~ilc[state].  To see how ~c[fmt-doc-example] works, ~c[:]~ilc[pe]
  ~c[fmt-doc-example].
  ~bv[]
  (fmt-doc-example '(a b c d e f g h i j k l m n o p) state)
  ~ev[]
  will produce the output
  ~bv[]
     Here is a true list:  (A B C D E F G H I J K L M N O P).  It has 16
     elements, the third of which is C.

     We could print each element in square brackets:
     ([A], [B], [C], [D], [E], [F], [G], [H], [I], [J], [K], [L], [M], [N],
     [almost there: O], [the end: P]).  And if we wished to itemize them
     into column 15 we could do it like this
     0123456789012345
         0 (zeroth) A
         1 (first)  B
         2 (second) C
         3 (third)  D
         4 (fourth) E
         5 (fifth)  F
         6 (sixth)  G
         7 (seventh)
                    H
         8 (eighth) I
         9 (ninth)  J
        10 (tenth)  K
        11 (eleventh)
                    L
        12 (twelfth)
                    M
        13 (thirteenth)
                    N
        14 (14th)   O
        15 (15th)   P
     End of example.
  ~ev[]
  and return ~c[(mv 15 state)].

  Finally, we should remind the reader that ~c[fmt] and its subfunctions,
  most importantly ~c[fmt0], are written entirely in ACL2.  We make this
  comment for two reasons.  First, it illustrates the fact that quite
  low level code can be efficiently written in the language.  Second,
  it means that as a last resort for documentation purposes you can
  read the source code without changing languages."

  (the2s
   (signed-byte 29)
   (pprogn
    (newline channel state)
    (fmt1 str alist 0 channel state evisc-tuple))))

(defun fms (str alist channel state evisc-tuple)

; WARNING: The master copy of the tilde-directives list is in :DOC fmt.

  ":Doc-Section ACL2::Programming

  ~c[:(str alist co-channel state evisc) => state]~/

  ~l[fmt] for further explanation, including documentation of the
  tilde-directives.~/~/"

  (pprogn
   (newline channel state)
   (mv-let (col state)
           (fmt1 str alist 0 channel state evisc-tuple)
           (declare (ignore col))
           state)))

(defun fmt1! (str alist col channel state evisc-tuple)

; WARNING: The master copy of the tilde-directives list is in :DOC fmt.

  ":Doc-Section ACL2::Programming

  ~c[:(str alist col channel state evisc) => (mv col state)]~/

  This function is nearly identical to ~c[fmt1]; ~pl[fmt1].  The only
  difference is that ~c[fmt1] may insert backslash (\\) characters when
  forced to print past the right margin in order to make the output a
  bit clearer in that case.  Use ~c[fmt1!] instead if you want to be able
  to read the forms back in.~/~/"

  (mv-let (erp col state)
          (state-global-let*
           ((write-for-read t))
           (mv-let (col state)
                   (fmt1 str alist col channel state evisc-tuple)
                   (mv nil col state)))
          (declare (ignore erp))
          (mv col state)))

(defun fmt! (str alist channel state evisc-tuple)

; WARNING: The master copy of the tilde-directives list is in :DOC fmt.

  ":Doc-Section ACL2::Programming

  ~c[:(str alist co-channel state evisc) => state]~/

  This function is nearly identical to ~c[fmt]; ~pl[fmt].  The only
  difference is that ~c[fmt] may insert backslash (\\) characters when
  forced to print past the right margin in order to make the output a
  bit clearer in that case.  Use ~c[fmt!] instead if you want to be able
  to read the forms back in.~/~/"

  (mv-let (erp col state)
          (state-global-let*
           ((write-for-read t))
           (mv-let (col state)
                   (fmt str alist channel state evisc-tuple)
                   (mv nil col state)))
          (declare (ignore erp))
          (mv col state)))

(defun fms! (str alist channel state evisc-tuple)

; WARNING: The master copy of the tilde-directives list is in :DOC fmt.

  ":Doc-Section ACL2::Programming

  ~c[:(str alist co-channel state evisc) => state]~/

  This function is nearly identical to ~c[fms]; ~pl[fms].  The only
  difference is that ~c[fms] may insert backslash (\\) characters when
  forced to print past the right margin in order to make the output a
  bit clearer in that case.  Use ~c[fms!] instead if you want to be able
  to read the forms back in.~/~/"

  (mv-let (erp val state)
          (state-global-let*
           ((write-for-read t))
           (pprogn (fms str alist channel state evisc-tuple)
                   (mv nil nil state)))
          (declare (ignore erp val))
          state))

(defmacro fmx (str &rest args)
  (declare (xargs :guard (<= (length args) 10)))
  `(fmt ,str ,(make-fmt-bindings '(#\0 #\1 #\2 #\3 #\4
                                   #\5 #\6 #\7 #\8 #\9)
                                 args)
        *standard-co* state nil))

(defun fmt-doc-example1 (lst i)
  (cond ((null lst) nil)
        (t (cons (cons "~c0 (~n1)~tc~y2~|"
                       (list (cons #\0 (cons i 5))
                             (cons #\1 (list i))
                             (cons #\2 (car lst))))
                 (fmt-doc-example1 (cdr lst) (1+ i))))))

(defun fmt-doc-example (x state)
  (fmt "Here is a true list:  ~x0.  It has ~#1~[no elements~/a single ~
        element~/~n2 elements~], ~@3~%~%We could print each element in square ~
        brackets:~%(~*4).  And if we wished to itemize them into column 15 we ~
        could do it like this~%0123456789012345~%~*5End of example."
       (list (cons #\0 x)
             (cons #\1 (cond ((null x) 0) ((null (cdr x)) 1)(t 2)))
             (cons #\2 (length x))
             (cons #\3 (cond ((< (length x) 3) "and so we can't print the third one!")
                             (t (cons "the third of which is ~x0."
                                      (list (cons #\0 (caddr x)))))))
             (cons #\4 (list "[empty]"
                             "[the end: ~y*]"
                             "[almost there: ~y*], "
                             "[~y*], "
                             x))
             (cons #\5 (list* "" "~@*" "~@*" "~@*"
                              (fmt-doc-example1 x 0)
                              (list (cons #\c 15)))))
         *standard-co* state nil))

(defconst *fmt-ctx-spacers*
  '(defun
     #+:non-standard-analysis defun-std
     mutual-recursion
     defuns
     defthm
     #+:non-standard-analysis defthm-std
     defaxiom
     defconst
     defstobj
     defpkg
     deflabel
     defdoc
     deftheory
     defchoose
     verify-guards
     verify-termination
     defmacro
     in-theory
     in-arithmetic-theory
     push-untouchable
     remove-untouchable
     reset-prehistory
     set-body
     table
     encapsulate
     include-book))

(defun fmt-ctx (ctx col channel state)

; We print the context in which an error has occurred.  If infix printing is
; being used (infixp = t or :out) then ctx is just the event form itself and we
; print it with evisceration.  Otherwise, we are more efficient in our choice
; of ctx and we interpret it according to its type, to make it convenient to
; construct the more common contexts.  If ctx is nil, we print nothing.  If ctx
; is a symbol, we print it from #\0 via "~x0".  If ctx is a pair whose car is a
; symbol, we print its car and cdr from #\0 and #\1 respectively with "(~x0 ~x1
; ...)".  Otherwise, we print it from #\0 with "~@0".

; We print no other words, spaces or punctuation.  We return the new
; col and state.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (cond ((output-in-infixp state)
          (fmt1 "~p0"
                (list (cons #\0 ctx))
                col channel state 
                (evisc-tuple 1 2 nil nil)))
         ((null ctx)
          (mv col state))
         ((symbolp ctx)
          (fmt1 "~x0" (list (cons #\0 ctx)) col channel state nil))
         ((and (consp ctx)
               (symbolp (car ctx)))
          (fmt1 "(~@0~x1 ~x2 ...)"
                (list (cons #\0
                            (if (member-eq (car ctx) *fmt-ctx-spacers*) " " ""))
                      (cons #\1 (car ctx))
                      (cons #\2 (cdr ctx)))
                col channel state nil))
         (t (fmt1 "~@0" (list (cons #\0 ctx)) col channel state nil)))))

(defun fmt-in-ctx (ctx col channel state)

; We print the phrase " in ctx:  ", if ctx is non-nil, and return
; the new col and state.

  (declare (type (signed-byte 29) col))
  (the2s
   (signed-byte 29)
   (cond ((null ctx)
          (fmt1 ":  " nil col channel state nil))
         (t (mv-let (col state)
                    (fmt1 " in " nil col channel state nil)
                    (mv-let (col state)
                            (fmt-ctx ctx col channel state)
                            (fmt1 ":  " nil col channel state nil)))))))

(defun error-fms (hardp ctx str alist state)

; This function prints the "ACL2 Error" banner and ctx, then the
; user's str and alist, and then two carriage returns.  It returns state.

; Historical Note about ACL2

; Once upon a time we accomplished all this with something like: "ACL2
; Error (in ~xc): ~@s~%~%" and it bound #\c and #\s to ctx and str in
; alist.  That suffers from the fact that it may overwrite the user's
; bindings of #\c and #\s -- unlikely if this error call was generated
; by our er macro.  We rewrote the function this way simply so we
; would not have to remember that some variables are special.

  (let ((channel (f-get-global 'standard-co state)))
    (mv-let (col state)
            (fmt1 (if hardp
                      "~%~%HARD ACL2 ERROR"
                    "~%~%ACL2 Error")
                  nil 0 channel state nil)
            (mv-let (col state)
                    (fmt-in-ctx ctx col channel state)
                    (mv-let (col state)
                            (fmt1 str alist col channel state
                                  (default-evisc-tuple state))
                            (mv-let (col state)
                                    (fmt1 "~%~%" nil col channel state nil)
                                    (declare (ignore col))
                                    state))))))

(defun push-warning-frame (state)
  (f-put-global 'accumulated-warnings
                (cons nil (f-get-global 'accumulated-warnings state))
                state))

(defun absorb-frame (lst stk)
  (if (consp stk)
      (cons (union-equal lst (car stk))
            (cdr stk))
    stk))

(defun pop-warning-frame (accum-p state)

; When a "compound" event has a "sub-event" that generates warnings, we want
; the warning strings from the sub-event's summary to appear in the parent
; event's summary.  Accum-p should be nil if and only if the sub-event whose
; warning frame we are popping had its warnings suppressed.

  (let ((stk (f-get-global 'accumulated-warnings state)))
    (cond ((consp stk)
           (pprogn
            (f-put-global 'accumulated-warnings
                          (if accum-p
                              (absorb-frame (car stk) (cdr stk))
                            (cdr stk))
                          state)
            (mv (car stk) state)))
          (t (mv (er hard 'pop-warning-frame
                     "The 'accumulated-warnings stack is empty.")
                 state)))))

(defun push-warning (summary state)
  (let ((stk (f-get-global 'accumulated-warnings state)))
    (cond ((consp stk)
           (f-put-global 'accumulated-warnings
                         (cons (add-to-set-equal summary (car stk))
                               (cdr stk))
                         state))
          (t 

; We used to cause an error, shown below, in this situation.  But WARNINGs are
; increasingly used by non-events, such as :trans and (thm ...) and rather than
; protect them all with push-warning-frame/pop-warning-frame we are just
; adopting the policy of not pushing warnings if the stack isn't set up for
; them.  Here is the old code.

;            (prog2$ (er hard 'push-warning
;                        "The 'accumulated-warnings stack is empty but we were ~
;                         asked to add ~x0 to the top frame."
;                        summary)
;                     state)

           state))))

(defun member-string-equal (str lst)
  (cond
   ((endp lst) nil)
   (t (or (string-equal str (car lst))
          (member-string-equal str (cdr lst))))))

(defabbrev flambda-applicationp (term)

; Term is assumed to be nvariablep.

  (consp (car term)))

(defabbrev lambda-applicationp (term)
  (and (consp term)
       (flambda-applicationp term)))

(defabbrev flambdap (fn)

; Fn is assumed to be the fn-symb of some term.

  (consp fn))

(defabbrev lambda-formals (x) (cadr x))

(defabbrev lambda-body (x) (caddr x))

(defabbrev make-lambda (args body)
  (list 'lambda args body))

(defabbrev make-let (bindings body)
  (list 'let bindings body))

(defmacro er-let* (alist body)

; This macro introduces the variable er-let-star-use-nowhere-else.
; The user who uses that variable in his forms is likely to be
; disappointed by the fact that we rebind it.

  (declare (xargs :guard (alistp alist)))
  (cond ((null alist)
         (list 'check-vars-not-free
               '(er-let-star-use-nowhere-else)
               body))
        (t (list 'mv-let
                 (list 'er-let-star-use-nowhere-else
                       (caar alist)
                       'state)
                 (cadar alist)
                 (list 'cond
                       (list 'er-let-star-use-nowhere-else
                             (list 'mv
                                   'er-let-star-use-nowhere-else
                                   (caar alist)
                                   'state))
                       (list t (list 'er-let* (cdr alist) body)))))))

(defmacro match (x pat)
  (list 'case-match x (list pat t)))

(defmacro match! (x pat)
  (list 'or (list 'case-match x
                  (list pat '(value nil)))
        (list 'er 'soft nil
              "The form ~x0 was supposed to match the pattern ~x1."
              x (kwote pat))))

#+:non-standard-analysis
(defconst *non-standard-primitives*
  '(standard-numberp
    standard-part
    i-large-integer))

(defun def-basic-type-sets1 (lst i)
  (declare (xargs :guard (and (integerp i)
                              (true-listp lst))))
  (cond ((null lst) nil)
        (t (cons (list 'defconst (car lst) (list 'the-type-set (expt 2 i)))
                 (def-basic-type-sets1 (cdr lst) (+ i 1))))))

(defmacro def-basic-type-sets (&rest lst)
  (let ((n (length lst)))
    `(progn
       (defconst *actual-primitive-types* ',lst)
       (defconst *min-type-set* (- (expt 2 ,n)))
       (defconst *max-type-set* (- (expt 2 ,n) 1))
       (defmacro the-type-set (x)

; Warning: Keep this definition in sync with the type declaration in
; ts-subsetp0 and ts-subsetp.

         `(the (integer ,*min-type-set* ,*max-type-set*) ,x))
       ,@(def-basic-type-sets1 lst 0))))

(defun list-of-the-type-set (x)
  (cond ((consp x)
         (cons (list 'the-type-set (car x))
               (list-of-the-type-set (cdr x))))
        (t nil)))

(defmacro ts= (a b)
  (list '= (list 'the-type-set a) (list 'the-type-set b)))

; We'll create fancier versions of ts-complement0, ts-union0, and
; ts-intersection0 once we have defined the basic type sets.

(defmacro ts-complement0 (x)
  (list 'the-type-set (list 'lognot (list 'the-type-set x))))

(defmacro ts-complementp (x)
  (list 'minusp x))

(defun ts-union0-fn (x)
  (list 'the-type-set
        (cond ((null x) '*ts-empty*)
              ((null (cdr x)) (car x))
              (t (xxxjoin 'logior
                          (list-of-the-type-set x))))))

(defmacro ts-union0 (&rest x)
  (declare (xargs :guard (true-listp x)))
  (ts-union0-fn x))

(defmacro ts-intersection0 (&rest x)
  (list 'the-type-set
        (cons 'logand (list-of-the-type-set x))))

(defmacro ts-intersectp (&rest x)
  (list 'not (list 'ts= (cons 'ts-intersection x) '*ts-empty*)))

; We do not define ts-subsetp0, both because we don't need it and because if we
; do define it, we will be tempted to add the declaration found in ts-subsetp,
; yet we have not yet defined *min-type-set* or *max-type-set*.

(defun ts-builder-case-listp (x)

; A legal ts-builder case list is a list of the form
;    ((key1 val1 ...) (key2 val2 ...) ... (keyk valk ...))
; where none of the keys is 'otherwise or 't except possibly keyk and
; every key is a symbolp if keyk is 'otherwise or 't.

; This function returns t, nil, or 'otherwise.  A non-nil value means
; that x is a legal ts-builder case list.  If it returns 'otherwise,
; it means keyk is an 'otherwise or a 't clause.  That aspect of the
; function is not used outside of its definition, but it is used in
; the definition below.

; If keyk is an 'otherwise or 't then each of the other keys will
; occur twice in the expanded form of the ts-builder expression and
; hence those keys must all be symbols.

  (cond ((atom x) (eq x nil))
        ((and (consp (car x))
              (true-listp (car x))
              (not (null (cdr (car x)))))
         (cond ((or (eq t (car (car x)))
                    (eq 'otherwise (car (car x))))
                (cond ((null (cdr x)) 'otherwise)
                      (t nil)))
               (t (let ((ans (ts-builder-case-listp (cdr x))))
                    (cond ((eq ans 'otherwise)
                           (cond ((symbolp (car (car x)))
                                  'otherwise)
                                 (t nil)))
                          (t ans))))))
        (t nil)))

(defun ts-builder-macro1 (x case-lst seen)
  (declare (xargs :guard (and (symbolp x)
                              (ts-builder-case-listp case-lst))))
  (cond ((null case-lst) nil)
        ((or (eq (caar case-lst) t)
             (eq (caar case-lst) 'otherwise))
         (sublis (list (cons 'x x)
                       (cons 'seen seen)
                       (cons 'ts2 (cadr (car case-lst))))
                 '((cond ((ts-intersectp x (ts-complement0 (ts-union0 . seen)))
                          ts2)
                         (t *ts-empty*)))))
        (t (cons (sublis (list (cons 'x x)
                               (cons 'ts1 (caar case-lst))
                               (cons 'ts2 (cadr (car case-lst))))
                         '(cond ((ts-intersectp x ts1) ts2)
                                (t *ts-empty*)))
                 (ts-builder-macro1 x (cdr case-lst) (cons (caar case-lst)
                                                           seen))))))

(defun ts-builder-macro (x case-lst)
  (declare (xargs :guard (and (symbolp x)
                              (ts-builder-case-listp case-lst))))
  (cons 'ts-union
        (ts-builder-macro1 x case-lst nil)))

(defmacro ts-builder (&rest args)
  #|
  (declare (xargs :guard (and (consp args)
                       (symbolp (car args))
                       (ts-builder-case-listp (cdr args)))))
  |#
  (ts-builder-macro (car args) (cdr args)))

(defun standard-guard (sym)
  (cond ((symbolp sym)
         (let* ((str (symbol-name sym))
                (c (cond ((int= (length str) 0) nil)
                         (t (char str 0)))))
           (case c
                 ((#\I #\J #\K #\M #\N) (list 'integerp sym))
                 (#\L (list 'true-listp sym))
                 (otherwise
                  (cond ((eql (string<= "TERM-L" str) 6)
                         (list 'pseudo-term-listp sym))
                        ((eql (string<= "TERM" str) 4)
                         (list 'pseudo-termp sym))
                        ((eql (string<= "SYM" str) 3)
                         (list 'symbolp sym))
                        ((eql (string<= "STR" str) 3)
                         (list 'stringp sym))
                        ((eql (string<= "ALIST" str) 5)
                         (list 'alistp sym))
                        (t nil))))))
        (t nil)))

(defun standard-guard-lst (lst)
  (cond ((atom lst)
         (cond ((eq lst nil) nil)
               (t (list nil))))
        (t (cons (standard-guard (car lst))
                 (standard-guard-lst (cdr lst))))))

(defmacro std (&rest x)
  (let ((hyps (standard-guard-lst x)))
    (cond ((member nil hyps)
           (er hard 'std
               "The standard guard macro std was given an argument ~
                list, ~x0, which it did not recognize.  Some element ~
                of the list does not have a standard type associated ~
                with its name."
               x))
          (t (cons 'and hyps)))))

(defabbrev strip-not (term)

; A typical use of this macro is:
; (mv-let (not-flg atm) (strip-not term)
;         ...body...)
; which has the effect of binding not-flg to T and atm to x if term
; is of the form (NOT x) and binding not-flg to NIL and atm to term
; otherwise.

  (cond ((and (nvariablep term)
;             (nquotep term)
              (eq (ffn-symb term) 'not))
         (mv t (fargn term 1)))
        (t (mv nil term))))

; The ACL2 Record Facilities

; Our record facility gives us the ability to declare "new" types of
; structures which are represented as lists.  If desired the lists
; are tagged with the name of the new record type.  Otherwise they are
; not tagged and are called "cheap" records.

; The expression (DEFREC SHIP (X . Y) NIL) declares SHIP to
; be a tagged (non-cheap) record of two components X and Y.  An
; example concrete SHIP is '(SHIP 2 . 4).  Note that cheapness refers
; only to whether the record is tagged and whether the tag is tested
; upon access and change, not whether the final cdr is used.

; To make a ship:  (MAKE SHIP :X x :Y y) or (MAKE SHIP :Y y :X x).
; To access the Xth component of the ship object obj: (ACCESS SHIP obj :X).
; To change the Xth component to val: (CHANGE SHIP obj :X val).
; Note the use of keywords in these forms.

; It is possible to change several fields at once, e.g.,
; (CHANGE SHIP obj :X val-x :Y val-y).  In general, to cons up a changed
; record one only does the conses necessary.

; The implementation of records is as follows.  DEFREC expands
; into a collection of macro definitions for certain generated function
; symbols.  In the example above we define the macros:

; |Make SHIP record|
; |Access SHIP record field X|
; |Access SHIP record field Y|
; |Change SHIP record fields|

; The macro expression (MAKE SHIP ...) expands to a call of the first
; function.  (ACCESS SHIP ... :X) expands to a call of the second.
; (CHANGE SHIP obj :X val-x :Y val-y) expands to
; (|Change SHIP record fields| obj :X val-x :Y val-y).

; The five new symbols above are defined as macros that further expand
; into raw CAR/CDR nests if the record is cheap and a similar nest
; that first checks the type of the record otherwise.

; In using the record facility I have sometimes pondered which fields I should
; allocate where to maximize access speed.  Other times I have just laid them
; out in an arbitrary fashion.  In any case, the following functions might be
; useful if you are wondering how to lay out a record.  That is, grab the
; following progn and execute it in the full ACL2 system.  (It cannot be
; executed at this point in basis.lisp because it uses functions defined
; elsewhere; it is here only to be easy to find when looking up the comments
; about records.)  Note that it changes the default-defun-mode to :program.  Then
; invoke :sbt n, where n is an integer.

; For example
; ACL2 g>:sbt 5

; The Binary Trees with Five Tips
; 2.400  ((2 . 2) 2 3 . 3)
; 2.600  (1 (3 . 3) 3 . 3)
; 2.800  (1 2 3 4 . 4)

; Sbt will print out all of the interesting binary trees with the
; given number of tips.  The integer appearing at a tip is the number
; of car/cdrs necessary to access that field of a cheap record laid
; out as shown.  That is also the number of conses required to change
; that single field.  The decimal number in the left column is the
; average number of car/cdrs required to access a field, assuming all
; fields are accessed equally often.  The number of trees generated
; grows exponentially with n.  Roughly 100 trees are printed for size
; 10.  Beware!

; The function (analyze-tree x state) is also helpful.  E.g.,

; ACL2 g>(analyze-tree '((type-alist . term) cl-ids rewrittenp
;                          force-flg . rune-or-non-rune)
;                        state)

; Shape:  ((2 . 2) 2 3 4 . 4)
; Field Depths:  
; ((TYPE-ALIST . 2)
;  (TERM . 2)
;  (CL-IDS . 2)
;  (REWRITTENP . 3)
;  (FORCE-FLG . 4)
;  (RUNE-OR-NON-RUNE . 4))
; Avg Depth:  2.833

#|
(progn
  (program)
  (defun bump-binary-tree (tree)
    (cond ((atom tree) (1+ tree))
          (t (cons (bump-binary-tree (car tree))
                   (bump-binary-tree (cdr tree))))))

  (defun cons-binary-trees (t1 t2)
    (cons (bump-binary-tree t1) (bump-binary-tree t2)))

  (defun combine-binary-trees1 (t1 lst2 ans)
    (cond ((null lst2) ans)
          (t (combine-binary-trees1 t1 (cdr lst2)
                                    (cons (cons-binary-trees t1 (car lst2))
                                          ans)))))

  (defun combine-binary-trees (lst1 lst2 ans)
    (cond
     ((null lst1) ans)
     (t (combine-binary-trees (cdr lst1)
                              lst2
                              (combine-binary-trees1 (car lst1) lst2 ans)))))

  (mutual-recursion

   (defun all-binary-trees1 (i n)
     (cond ((= i 0) nil)
           (t (revappend (combine-binary-trees (all-binary-trees i)
                                               (all-binary-trees (- n i))
                                               nil)
                         (all-binary-trees1 (1- i) n)))))

   (defun all-binary-trees (n)
     (cond ((= n 1) (list 0))
           (t (all-binary-trees1 (floor n 2) n))))
   )

  (defun total-access-time-binary-tree (x)
    (cond ((atom x) x)
          (t (+ (total-access-time-binary-tree (car x))
                (total-access-time-binary-tree (cdr x))))))

  (defun total-access-time-binary-tree-lst (lst)

; Pairs each tree in lst with its total-access-time.

    (cond ((null lst) nil)
          (t (cons (cons (total-access-time-binary-tree (car lst))
                         (car lst))
                   (total-access-time-binary-tree-lst (cdr lst))))))

  (defun show-binary-trees1 (n lst state)
    (cond ((null lst) state)
          (t (let* ((tat (floor (* (caar lst) 1000) n))
                    (d0 (floor tat 1000)) 
                    (d1 (- (floor tat 100) (* d0 10)))
                    (d2 (- (floor tat 10) (+ (* d0 100) (* d1 10))))
                    (d3 (- tat (+ (* d0 1000) (* d1 100) (* d2 10)))))

               (pprogn
                (mv-let (col state)
                        (fmt1 "~x0.~x1~x2~x3  ~x4~%"
                              (list (cons #\0 d0)
                                    (cons #\1 d1)
                                    (cons #\2 d2)
                                    (cons #\3 d3)
                                    (cons #\4 (cdar lst)))
                              0
                              *standard-co* state nil)
                        (declare (ignore col))
                        state)
                (show-binary-trees1 n (cdr lst) state))))))

  (defun show-binary-trees (n state)
    (let ((lst (reverse
                (merge-sort-car->
                 (total-access-time-binary-tree-lst
                  (all-binary-trees n))))))
      (pprogn
       (fms "The Binary Trees with ~N0 Tips~%"
            (list (cons #\0 n))
            *standard-co* state nil)
       (show-binary-trees1 n lst state))))

  (defun analyze-tree1 (x i)
    (cond ((atom x) i)
          (t (cons (analyze-tree1 (car x) (1+ i))
                   (analyze-tree1 (cdr x) (1+ i))))))

  (defun analyze-tree2 (x i)
    (cond ((atom x) (list (cons x i)))
          (t (append (analyze-tree2 (car x) (1+  i))
                     (analyze-tree2 (cdr x) (1+  i))))))

  (defun analyze-tree3 (x)
    (cond ((atom x) 1)
          (t (+ (analyze-tree3 (car x)) (analyze-tree3 (cdr x))))))

  (defun analyze-tree (x state)
    (let* ((binary-tree (analyze-tree1 x 0))
           (alist (analyze-tree2 x 0))
           (n (analyze-tree3 x))
           (k (total-access-time-binary-tree binary-tree)))
      (let* ((tat (floor (* k 1000) n))
             (d0 (floor tat 1000)) 
             (d1 (- (floor tat 100) (* d0 10)))
             (d2 (- (floor tat 10) (+ (* d0 100) (* d1 10))))
             (d3 (- tat (+ (* d0 1000) (* d1 100) (* d2 10)))))
        (pprogn
         (fms "Shape:  ~x0~%Field Depths:  ~x1~%Avg Depth:  ~x2.~x3~x4~x5~%"
              (list (cons #\0 binary-tree)
                    (cons #\1 alist)
                    (cons #\2 d0)
                    (cons #\3 d1)
                    (cons #\4 d2)
                    (cons #\5 d3))
              *standard-co* state nil)
         (value :invisible)))))

  (defmacro sbt (n) `(pprogn (show-binary-trees ,n state) (value :invisible))))

|#


(defun record-maker-function-name (name)
  (intern-in-package-of-symbol
   (coerce (append (coerce "Make " 'list)
                   (coerce (symbol-name name) 'list)
                   (coerce " record" 'list))
           'string)
   name))

(defun record-accessor-function-name (name field)
  (intern-in-package-of-symbol
   (coerce
    (append (coerce "Access " 'list)
            (coerce (symbol-name name) 'list)
            (coerce " record field " 'list)
            (coerce (symbol-name field) 'list))
    'string)
   name))

(defun record-changer-function-name (name)
  (intern-in-package-of-symbol
   (coerce
    (append (coerce "Change " 'list)
            (coerce (symbol-name name) 'list)
            (coerce " record fields" 'list))
    'string)
   name))

(defmacro make (&rest args)
  (cond ((keyword-value-listp (cdr args))
         (cons (record-maker-function-name (car args)) (cdr args)))
        (t (er hard 'record-error
               "Make was given a non-keyword as a field specifier.  ~
                The offending form is ~x0."
               (cons 'make args)))))

(defmacro access (name rec field)
  (cond ((keywordp field)
         (list (record-accessor-function-name name field)
               rec))
        (t (er hard 'record-error
               "Access was given a non-keyword as a field ~
                specifier.  The offending form was ~x0."
               (list 'access name rec field)))))

(defmacro change (&rest args)
  (cond ((keyword-value-listp (cddr args))
         (cons (record-changer-function-name (car args)) (cdr args)))
        (t (er hard 'record-error
               "Change was given a non-keyword as a field specifier.  ~
                The offending form is ~x0."
               (cons 'change args)))))

(defun record-error (name rec)
  (er hard 'record-error
      "An attempt was made to treat ~x0 as a record of type ~x1."
      rec name))

(defun make-record-car-cdrs1 (lst var)
  (cond ((null lst) var)
        (t (list (car lst) (make-record-car-cdrs1 (cdr lst) var)))))

(defun make-record-car-cdrs (field-layout car-cdr-lst)
  (cond ((atom field-layout)
         (cond ((null field-layout) nil)
               (t (list (make-record-car-cdrs1 car-cdr-lst field-layout)))))
        (t (append (make-record-car-cdrs (car field-layout)
                                         (cons 'car car-cdr-lst))
                   (make-record-car-cdrs (cdr field-layout)
                                         (cons 'cdr car-cdr-lst))))))

(defun make-record-accessors (name field-lst car-cdrs cheap)
  (cond ((null field-lst) nil)
        (t
         (cons (cond
                (cheap
                 (list 'defabbrev
                       (record-accessor-function-name name (car field-lst))
                       (list (car field-lst))
                       (car car-cdrs)))
                (t (list 'defabbrev
                         (record-accessor-function-name name (car field-lst))
                         (list (car field-lst))
                         (sublis (list (cons 'name name)
                                       (cons 'x (car field-lst))
                                       (cons 'z (car car-cdrs)))
                                 '(prog2$ (or (and (consp x)
                                                   (eq (car x) (quote name)))
                                              (record-error (quote name) x))
                                          z)))))
               (make-record-accessors name
                                      (cdr field-lst)
                                      (cdr car-cdrs)
                                      cheap)))))

(defun symbol-name-tree-occur (sym sym-tree)

; Sym is a symbol -- in fact, a keyword in proper usage -- and
; sym-tree is a tree of symbols.  We ask whether a symbol with
; the same symbol-name as key occurs in sym-tree.  If so, we return
; that symbol.  Otherwise we return nil.

  (cond ((symbolp sym-tree)
         (cond ((equal (symbol-name sym) (symbol-name sym-tree))
                sym-tree)
               (t nil)))
        ((atom sym-tree)
         nil)
        (t (or (symbol-name-tree-occur sym (car sym-tree))
               (symbol-name-tree-occur sym (cdr sym-tree))))))

(defun some-symbol-name-tree-occur (syms sym-tree)
  (cond ((null syms) nil)
        ((symbol-name-tree-occur (car syms) sym-tree) t)
        (t (some-symbol-name-tree-occur (cdr syms) sym-tree))))

(defun make-record-changer-cons (fields field-layout x)

; Fields is the list of keyword field specifiers that are being
; changed.  Field-layout is the user's layout of the record.  X is the
; name of the variable holding the instance of the record.

  (cond ((not (some-symbol-name-tree-occur fields field-layout))
         x)
        ((atom field-layout)
         field-layout)
        (t
         (list 'cons
               (make-record-changer-cons fields
                                         (car field-layout)
                                         (list 'car x))
               (make-record-changer-cons fields
                                         (cdr field-layout)
                                         (list 'cdr x))))))

(defun make-record-changer-let-bindings (field-layout lst)

; Field-layout is the symbol tree provided by the user describing the
; layout of the fields.  Lst is the keyword/value list in a change
; form.  We want to bind each field name to the corresponding value.
; The only reason we take field-layout as an argument is that we
; don't know from :key which package 'key is in.

  (cond ((null lst) nil)
        (t (let ((var (symbol-name-tree-occur (car lst) field-layout)))
             (cond ((null var)
                    (er hard 'record-error
                        "A make or change form has used ~x0 as though ~
                         it were a legal field specifier in a record ~
                         with the layout ~x1."
                        (car lst)
                        field-layout))
                   (t
                    (cons (list var (cadr lst))
                          (make-record-changer-let-bindings field-layout
                                                            (cddr lst)))))))))

(defun make-record-changer-let (name field-layout cheap rec lst)
  (cond
   (cheap
    (list 'let (cons (list 'record-changer-not-to-be-used-elsewhere rec)
                     (make-record-changer-let-bindings field-layout lst))
          (make-record-changer-cons
           (evens lst)
           field-layout
           'record-changer-not-to-be-used-elsewhere)))
   (t
    (list 'let (cons (list 'record-changer-not-to-be-used-elsewhere rec)
                     (make-record-changer-let-bindings field-layout lst))
          (sublis
           (list (cons 'name name)
                 (cons 'cons-nest
                       (make-record-changer-cons
                        (evens lst)
                        field-layout
                        '(cdr record-changer-not-to-be-used-elsewhere))))
           '(prog2$ (or (and (consp record-changer-not-to-be-used-elsewhere)
                             (eq (car record-changer-not-to-be-used-elsewhere)
                                 (quote name)))
                        (record-error (quote name)
                                      record-changer-not-to-be-used-elsewhere))
                    (cons (quote name) cons-nest)))))))

(defun make-record-changer (name field-layout cheap)
  (list 'defmacro
        (record-changer-function-name name)
        '(&rest args)
        (list 'make-record-changer-let
              (kwote name)
              (kwote field-layout)
              cheap
              '(car args)
              '(cdr args))))

(defun make-record-maker-cons (fields field-layout)

; Fields is the list of keyword field specifiers being initialized in
; a record.  Field-layout is the user's specification of the layout.
; We lay down a cons tree isomorphic to field-layout whose tips are
; either the corresponding tip of field-layout or nil according to
; whether the keyword corresponding to the field-layout tip is in fields.

  (cond ((atom field-layout)
         (cond ((some-symbol-name-tree-occur fields field-layout)

; The above call is a little strange isn't it?  Field-layout is an
; atom, a symbol really, and here we are asking whether any element of
; fields symbol-name-tree-occurs in it.  We're really just exploiting
; some-symbol-name-tree-occur to walk down fields for us taking the
; symbol-name of each element and seeing if it occurs in (i.e., in
; this case, is) the symbol name of field-layout.

                field-layout)
               (t nil)))
        (t
         (list 'cons
               (make-record-maker-cons fields
                                       (car field-layout))
               (make-record-maker-cons fields
                                       (cdr field-layout))))))

(defun make-record-maker-let (name field-layout cheap lst)
  (cond
   (cheap
    (list 'let (make-record-changer-let-bindings field-layout lst)
          (make-record-maker-cons (evens lst)
                                  field-layout)))
   (t
    (list 'let (make-record-changer-let-bindings field-layout lst)
          (list 'cons
                (kwote name)
                (make-record-maker-cons (evens lst)
                                        field-layout))))))

(defun make-record-maker (name field-layout cheap)
  (list 'defmacro
        (record-maker-function-name name)
        '(&rest args)
        (list 'make-record-maker-let
              (kwote name)
              (kwote field-layout)
              cheap
              'args)))

(defun make-record-field-lst (field-layout)
  (cond ((atom field-layout)
         (cond ((null field-layout) nil)
               (t (list field-layout))))
        (t (append (make-record-field-lst (car field-layout))
                   (make-record-field-lst (cdr field-layout))))))

(defun record-macros (name field-layout cheap)
  (cons 'progn
        (append
         (make-record-accessors name
                                (make-record-field-lst field-layout)
                                (make-record-car-cdrs field-layout
                                                      (if cheap nil '(cdr)))
                                cheap)
         (list (make-record-changer name field-layout cheap)
               (make-record-maker name field-layout cheap)))))

; WARNING: If you change the layout of records, you must change
; certain functions that build them in.  Generally, these functions
; are defined before defrec was defined, but need to access
; components.  See the warning associated with defrec rewrite-constant
; for a list of one group of such functions.  You might also search
; for occurrences of the word defrec prior to this definition of it.

(defmacro defrec (name field-lst cheap)
  (record-macros name field-lst cheap))

(defabbrev equalityp (term)

; Note that the fquotep below is commented out.  This function violates
; our standard rules on the use of ffn-symb but is ok since we are looking
; for 'equal and not for 'quote or any constructor that might be hidden
; inside a quoted term.

  (and (nvariablep term)
;      (not (fquotep term))
       (eq (ffn-symb term) 'equal)))

(defabbrev inequalityp (term)

; Note that the fquotep below is commented out.  This function violates
; our standard rules on the use of ffn-symb but is ok since we are looking
; for 'equal and not for 'quote or any constructor that might be hidden
; inside a quoted term.

  (and (nvariablep term)
;      (not (fquotep term))
       (eq (ffn-symb term) '<)))

(defabbrev consityp (term)

; Consityp is to cons what equalityp is equal:  it recognizes terms
; that are non-evg cons expressions.

  (and (nvariablep term)
       (not (fquotep term))
       (eq (ffn-symb term) 'cons)))

(defun power-rep (n b)
  (if (< n b)
      (list n)
    (cons (rem n b)
          (power-rep (floor n b) b))))

(defun decode-idate (n)
  (let ((tuple (power-rep n 100)))
    (cond
     ((< (len tuple) 6)
      (er hard 'decode-idate
          "Idates are supposed to decode to a list of at least length six ~
           but ~x0 decoded to ~x1."
          n tuple))
     ((equal (len tuple) 6) tuple)
     (t 
        
; In this case, tuple is (secs mins hrs day month yr1 yr2 ...) where 0
; <= yri < 100 and (yr1 yr2 ...) represents a big number, yr, in base
; 100.  Yr is the number of years since 1900.

        (let ((secs (nth 0 tuple))
              (mins (nth 1 tuple))
              (hrs  (nth 2 tuple))
              (day  (nth 3 tuple))
              (mo   (nth 4 tuple))
              (yr (power-eval (cdr (cddddr tuple)) 100)))
          (list secs mins hrs day mo yr))))))

(defun pcd2 (n channel state)
  (declare (xargs :guard (integerp n)))
  (cond ((< n 10)
         (pprogn (princ$ "0" channel state)
                 (princ$ n channel state)))
        (t (princ$ n channel state))))

(defun print-idate (n channel state)
  (let* ((x (decode-idate n))
         (sec (car x))
         (minimum (cadr x))
         (hrs (caddr x))
         (day (cadddr x))
         (mo (car (cddddr x)))
         (yr (cadr (cddddr x))))  ; yr = years since 1900.  It is possible
                                  ; that yr > 99!